From c2114f3b77806627e47ece113336d3f5ffc001a9 Mon Sep 17 00:00:00 2001 From: rohitmalhotra1420 Date: Tue, 5 Nov 2024 15:44:02 +0530 Subject: [PATCH] Updates --- assets/{ccip-CiOu7uMi.js => ccip-BBxDHENs.js} | 2 +- ...8000-DPntdE7M.js => index-8e228000-BM2OJ2QW.js} | 2 +- assets/index-B0ywuJCf.js | 2 -- assets/{index-FF2LIIm3.js => index-BlNib8lH.js} | 2 +- assets/index-Cl2DsYqV.js | 2 ++ assets/{index-CiyH7SV9.js => index-CqoM6a8-.js} | 14 +++++++------- ...decrypto-Co9-WRDE.js => nodecrypto-BXD6e4iz.js} | 2 +- assets/{purejs-IJPcfd_M.js => purejs-BONB21cl.js} | 2 +- assets/{utils-D-KHXRuV.js => utils-C3TScgcd.js} | 2 +- ...webcrypto-3I5ubJVL.js => webcrypto-6IU6aAco.js} | 2 +- index.html | 6 +++--- 11 files changed, 19 insertions(+), 19 deletions(-) rename assets/{ccip-CiOu7uMi.js => ccip-BBxDHENs.js} (97%) rename assets/{index-8e228000-DPntdE7M.js => index-8e228000-BM2OJ2QW.js} (99%) delete mode 100644 assets/index-B0ywuJCf.js rename assets/{index-FF2LIIm3.js => index-BlNib8lH.js} (99%) create mode 100644 assets/index-Cl2DsYqV.js rename assets/{index-CiyH7SV9.js => index-CqoM6a8-.js} (99%) rename assets/{nodecrypto-Co9-WRDE.js => nodecrypto-BXD6e4iz.js} (64%) rename assets/{purejs-IJPcfd_M.js => purejs-BONB21cl.js} (92%) rename assets/{utils-D-KHXRuV.js => utils-C3TScgcd.js} (98%) rename assets/{webcrypto-3I5ubJVL.js => webcrypto-6IU6aAco.js} (90%) diff --git a/assets/ccip-CiOu7uMi.js b/assets/ccip-BBxDHENs.js similarity index 97% rename from assets/ccip-CiOu7uMi.js rename to assets/ccip-BBxDHENs.js index 1b8ef15..5f9a6e6 100644 --- a/assets/ccip-CiOu7uMi.js +++ b/assets/ccip-BBxDHENs.js @@ -1 +1 @@ -import{j as p,k as m,l as y,m as k,n as b,o as O,q as E,t as L,H as h,v as x}from"./index-CiyH7SV9.js";class M extends p{constructor({callbackSelector:r,cause:a,data:o,extraData:i,sender:d,urls:t}){var n;super(a.shortMessage||"An error occurred while fetching for an offchain result.",{cause:a,metaMessages:[...a.metaMessages||[],(n=a.metaMessages)!=null&&n.length?"":[],"Offchain Gateway Call:",t&&[" Gateway URL(s):",...t.map(f=>` ${m(f)}`)],` Sender: ${d}`,` Data: ${o}`,` Callback selector: ${r}`,` Extra data: ${i}`].flat(),name:"OffchainLookupError"})}}class R extends p{constructor({result:r,url:a}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${m(a)}`,`Response: ${y(r)}`],name:"OffchainLookupResponseMalformedError"})}}class S extends p{constructor({sender:r,to:a}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${a}`,`OffchainLookup sender address: ${r}`],name:"OffchainLookupSenderMismatchError"})}}const A="0x556f1830",$={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function C(c,{blockNumber:r,blockTag:a,data:o,to:i}){const{args:d}=k({data:o,abi:[$]}),[t,n,f,u,s]=d,{ccipRead:e}=c,w=e&&typeof(e==null?void 0:e.request)=="function"?e.request:q;try{if(!b(i,t))throw new S({sender:t,to:i});const l=await w({data:f,sender:t,urls:n}),{data:g}=await O(c,{blockNumber:r,blockTag:a,data:E([u,L([{type:"bytes"},{type:"bytes"}],[l,s])]),to:i});return g}catch(l){throw new M({callbackSelector:u,cause:l,data:o,extraData:s,sender:t,urls:n})}}async function q({data:c,sender:r,urls:a}){var i;let o=new Error("An unknown error occurred.");for(let d=0;d` ${m(f)}`)],` Sender: ${d}`,` Data: ${o}`,` Callback selector: ${r}`,` Extra data: ${i}`].flat(),name:"OffchainLookupError"})}}class R extends p{constructor({result:r,url:a}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${m(a)}`,`Response: ${y(r)}`],name:"OffchainLookupResponseMalformedError"})}}class S extends p{constructor({sender:r,to:a}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${a}`,`OffchainLookup sender address: ${r}`],name:"OffchainLookupSenderMismatchError"})}}const A="0x556f1830",$={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function C(c,{blockNumber:r,blockTag:a,data:o,to:i}){const{args:d}=k({data:o,abi:[$]}),[t,n,f,u,s]=d,{ccipRead:e}=c,w=e&&typeof(e==null?void 0:e.request)=="function"?e.request:q;try{if(!b(i,t))throw new S({sender:t,to:i});const l=await w({data:f,sender:t,urls:n}),{data:g}=await O(c,{blockNumber:r,blockTag:a,data:E([u,L([{type:"bytes"},{type:"bytes"}],[l,s])]),to:i});return g}catch(l){throw new M({callbackSelector:u,cause:l,data:o,extraData:s,sender:t,urls:n})}}async function q({data:c,sender:r,urls:a}){var i;let o=new Error("An unknown error occurred.");for(let d=0;de in t?Dl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_e=(t,e,s)=>(jl(t,typeof e!="symbol"?e+"":e,s),s),Qi={exports:{}},ks=typeof Reflect=="object"?Reflect:null,zn=ks&&typeof ks.apply=="function"?ks.apply:function(t,e,s){return Function.prototype.apply.call(t,e,s)},$r;ks&&typeof ks.ownKeys=="function"?$r=ks.ownKeys:Object.getOwnPropertySymbols?$r=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:$r=function(t){return Object.getOwnPropertyNames(t)};function zl(t){console&&console.warn&&console.warn(t)}var Qa=Number.isNaN||function(t){return t!==t};function Pe(){Pe.init.call(this)}Qi.exports=Pe;Qi.exports.once=Kl;Pe.EventEmitter=Pe;Pe.prototype._events=void 0;Pe.prototype._eventsCount=0;Pe.prototype._maxListeners=void 0;var qn=10;function ri(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Pe,"defaultMaxListeners",{enumerable:!0,get:function(){return qn},set:function(t){if(typeof t!="number"||t<0||Qa(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");qn=t}});Pe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Qa(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Xa(t){return t._maxListeners===void 0?Pe.defaultMaxListeners:t._maxListeners}Pe.prototype.getMaxListeners=function(){return Xa(this)};Pe.prototype.emit=function(t){for(var e=[],s=1;s0&&(n=e[0]),n instanceof Error)throw n;var c=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw c.context=n,c}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")zn(a,this,e);else for(var l=a.length,d=rc(a,l),s=0;s0&&c.length>i&&!c.warned){c.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=c.length,zl(a)}return t}Pe.prototype.addListener=function(t,e){return Za(this,t,e,!1)};Pe.prototype.on=Pe.prototype.addListener;Pe.prototype.prependListener=function(t,e){return Za(this,t,e,!0)};function ql(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ec(t,e,s){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:s},i=ql.bind(r);return i.listener=s,r.wrapFn=i,i}Pe.prototype.once=function(t,e){return ri(e),this.on(t,ec(this,t,e)),this};Pe.prototype.prependOnceListener=function(t,e){return ri(e),this.prependListener(t,ec(this,t,e)),this};Pe.prototype.removeListener=function(t,e){var s,r,i,n,c;if(ri(e),r=this._events,r===void 0)return this;if(s=r[t],s===void 0)return this;if(s===e||s.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,s.listener||e));else if(typeof s!="function"){for(i=-1,n=s.length-1;n>=0;n--)if(s[n]===e||s[n].listener===e){c=s[n].listener,i=n;break}if(i<0)return this;i===0?s.shift():$l(s,i),s.length===1&&(r[t]=s[0]),r.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};Pe.prototype.off=Pe.prototype.removeListener;Pe.prototype.removeAllListeners=function(t){var e,s,r;if(s=this._events,s===void 0)return this;if(s.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):s[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete s[t]),this;if(arguments.length===0){var i=Object.keys(s),n;for(r=0;r=0;r--)this.removeListener(t,e[r]);return this};function tc(t,e,s){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?s?[i.listener||i]:[i]:s?Vl(i):rc(i,i.length)}Pe.prototype.listeners=function(t){return tc(this,t,!0)};Pe.prototype.rawListeners=function(t){return tc(this,t,!1)};Pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):sc.call(t,e)};Pe.prototype.listenerCount=sc;function sc(t){var e=this._events;if(e!==void 0){var s=e[t];if(typeof s=="function")return 1;if(s!==void 0)return s.length}return 0}Pe.prototype.eventNames=function(){return this._eventsCount>0?$r(this._events):[]};function rc(t,e){for(var s=new Array(e),r=0;re in t?Dl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_e=(t,e,s)=>(jl(t,typeof e!="symbol"?e+"":e,s),s),Qi={exports:{}},ks=typeof Reflect=="object"?Reflect:null,zn=ks&&typeof ks.apply=="function"?ks.apply:function(t,e,s){return Function.prototype.apply.call(t,e,s)},$r;ks&&typeof ks.ownKeys=="function"?$r=ks.ownKeys:Object.getOwnPropertySymbols?$r=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:$r=function(t){return Object.getOwnPropertyNames(t)};function zl(t){console&&console.warn&&console.warn(t)}var Qa=Number.isNaN||function(t){return t!==t};function Pe(){Pe.init.call(this)}Qi.exports=Pe;Qi.exports.once=Kl;Pe.EventEmitter=Pe;Pe.prototype._events=void 0;Pe.prototype._eventsCount=0;Pe.prototype._maxListeners=void 0;var qn=10;function ri(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Pe,"defaultMaxListeners",{enumerable:!0,get:function(){return qn},set:function(t){if(typeof t!="number"||t<0||Qa(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");qn=t}});Pe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Qa(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Xa(t){return t._maxListeners===void 0?Pe.defaultMaxListeners:t._maxListeners}Pe.prototype.getMaxListeners=function(){return Xa(this)};Pe.prototype.emit=function(t){for(var e=[],s=1;s0&&(n=e[0]),n instanceof Error)throw n;var c=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw c.context=n,c}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")zn(a,this,e);else for(var l=a.length,d=rc(a,l),s=0;s0&&c.length>i&&!c.warned){c.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=c.length,zl(a)}return t}Pe.prototype.addListener=function(t,e){return Za(this,t,e,!1)};Pe.prototype.on=Pe.prototype.addListener;Pe.prototype.prependListener=function(t,e){return Za(this,t,e,!0)};function ql(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ec(t,e,s){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:s},i=ql.bind(r);return i.listener=s,r.wrapFn=i,i}Pe.prototype.once=function(t,e){return ri(e),this.on(t,ec(this,t,e)),this};Pe.prototype.prependOnceListener=function(t,e){return ri(e),this.prependListener(t,ec(this,t,e)),this};Pe.prototype.removeListener=function(t,e){var s,r,i,n,c;if(ri(e),r=this._events,r===void 0)return this;if(s=r[t],s===void 0)return this;if(s===e||s.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,s.listener||e));else if(typeof s!="function"){for(i=-1,n=s.length-1;n>=0;n--)if(s[n]===e||s[n].listener===e){c=s[n].listener,i=n;break}if(i<0)return this;i===0?s.shift():$l(s,i),s.length===1&&(r[t]=s[0]),r.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};Pe.prototype.off=Pe.prototype.removeListener;Pe.prototype.removeAllListeners=function(t){var e,s,r;if(s=this._events,s===void 0)return this;if(s.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):s[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete s[t]),this;if(arguments.length===0){var i=Object.keys(s),n;for(r=0;r=0;r--)this.removeListener(t,e[r]);return this};function tc(t,e,s){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?s?[i.listener||i]:[i]:s?Vl(i):rc(i,i.length)}Pe.prototype.listeners=function(t){return tc(this,t,!0)};Pe.prototype.rawListeners=function(t){return tc(this,t,!1)};Pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):sc.call(t,e)};Pe.prototype.listenerCount=sc;function sc(t){var e=this._events;if(e!==void 0){var s=e[t];if(typeof s=="function")return 1;if(s!==void 0)return s.length}return 0}Pe.prototype.eventNames=function(){return this._eventsCount>0?$r(this._events):[]};function rc(t,e){for(var s=new Array(e),r=0;ri.map(i=>d[i]); -import{B as pe,_ as me}from"./index-CiyH7SV9.js";const he=Symbol(),ee=Object.getPrototypeOf,Y=new WeakMap,ge=e=>e&&(Y.has(e)?Y.get(e):ee(e)===Object.prototype||ee(e)===Array.prototype),ye=e=>ge(e)&&e[he]||null,te=(e,t=!0)=>{Y.set(e,t)},z={BASE_URL:"/push-wallet/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_DYNAMIC_ENV_ID:"7a6006b6-fa19-4e7a-abcf-34add623dff5",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"},F=e=>typeof e=="object"&&e!==null,L=new WeakMap,x=new WeakSet,ve=(e=Object.is,t=(o,g)=>new Proxy(o,g),s=o=>F(o)&&!x.has(o)&&(Array.isArray(o)||!(Symbol.iterator in o))&&!(o instanceof WeakMap)&&!(o instanceof WeakSet)&&!(o instanceof Error)&&!(o instanceof Number)&&!(o instanceof Date)&&!(o instanceof String)&&!(o instanceof RegExp)&&!(o instanceof ArrayBuffer),n=o=>{switch(o.status){case"fulfilled":return o.value;case"rejected":throw o.reason;default:throw o}},l=new WeakMap,c=(o,g,I=n)=>{const v=l.get(o);if((v==null?void 0:v[0])===g)return v[1];const b=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o));return te(b,!0),l.set(o,[g,b]),Reflect.ownKeys(o).forEach(j=>{if(Object.getOwnPropertyDescriptor(b,j))return;const O=Reflect.get(o,j),A={value:O,enumerable:!0,configurable:!0};if(x.has(O))te(O,!1);else if(O instanceof Promise)delete A.value,A.get=()=>I(O);else if(L.has(O)){const[y,H]=L.get(O);A.value=c(y,H(),I)}Object.defineProperty(b,j,A)}),Object.preventExtensions(b)},d=new WeakMap,f=[1,1],W=o=>{if(!F(o))throw new Error("object required");const g=d.get(o);if(g)return g;let I=f[0];const v=new Set,b=(i,a=++f[0])=>{I!==a&&(I=a,v.forEach(r=>r(i,a)))};let j=f[1];const O=(i=++f[1])=>(j!==i&&!v.size&&(j=i,y.forEach(([a])=>{const r=a[1](i);r>I&&(I=r)})),I),A=i=>(a,r)=>{const h=[...a];h[1]=[i,...h[1]],b(h,r)},y=new Map,H=(i,a)=>{if((z?"production":void 0)!=="production"&&y.has(i))throw new Error("prop listener already exists");if(v.size){const r=a[3](A(i));y.set(i,[a,r])}else y.set(i,[a])},Z=i=>{var a;const r=y.get(i);r&&(y.delete(i),(a=r[1])==null||a.call(r))},ue=i=>(v.add(i),v.size===1&&y.forEach(([r,h],U)=>{if((z?"production":void 0)!=="production"&&h)throw new Error("remove already exists");const N=r[3](A(U));y.set(U,[r,N])}),()=>{v.delete(i),v.size===0&&y.forEach(([r,h],U)=>{h&&(h(),y.set(U,[r]))})}),q=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o)),R=t(q,{deleteProperty(i,a){const r=Reflect.get(i,a);Z(a);const h=Reflect.deleteProperty(i,a);return h&&b(["delete",[a],r]),h},set(i,a,r,h){const U=Reflect.has(i,a),N=Reflect.get(i,a,h);if(U&&(e(N,r)||d.has(r)&&e(N,d.get(r))))return!0;Z(a),F(r)&&(r=ye(r)||r);let V=r;if(r instanceof Promise)r.then(C=>{r.status="fulfilled",r.value=C,b(["resolve",[a],C])}).catch(C=>{r.status="rejected",r.reason=C,b(["reject",[a],C])});else{!L.has(r)&&s(r)&&(V=W(r));const C=!x.has(V)&&L.get(V);C&&H(a,C)}return Reflect.set(i,a,V,h),b(["set",[a],r,N]),!0}});d.set(o,R);const fe=[q,O,c,ue];return L.set(R,fe),Reflect.ownKeys(o).forEach(i=>{const a=Object.getOwnPropertyDescriptor(o,i);"value"in a&&(R[i]=o[i],delete a.value,delete a.writable),Object.defineProperty(q,i,a)}),R})=>[W,L,x,e,t,s,n,l,c,d,f],[be]=ve();function P(e={}){return be(e)}function S(e,t,s){const n=L.get(e);(z?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let l;const c=[],d=n[3];let f=!1;const o=d(g=>{c.push(g),l||(l=Promise.resolve().then(()=>{l=void 0,f&&t(c.splice(0))}))});return f=!0,()=>{f=!1,o()}}function we(e,t){const s=L.get(e);(z?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[n,l,c]=s;return c(n,l(),t)}const u=P({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),de={state:u,subscribe(e){return S(u,()=>e(u))},push(e,t){e!==u.view&&(u.view=e,t&&(u.data=t),u.history.push(e))},reset(e){u.view=e,u.history=[e]},replace(e){u.history.length>1&&(u.history[u.history.length-1]=e,u.view=e)},goBack(){if(u.history.length>1){u.history.pop();const[e]=u.history.slice(-1);u.view=e}},setData(e){u.data=e}},m={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return m.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const e=navigator.userAgent.toLowerCase();return m.isMobile()&&(e.includes("iphone")||e.includes("ipad"))},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},isArray(e){return Array.isArray(e)&&e.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(e,t,s){if(m.isHttpUrl(e))return this.formatUniversalUrl(e,t,s);let n=e;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},formatUniversalUrl(e,t,s){if(!m.isHttpUrl(e))return this.formatNativeUrl(e,t,s);let n=e;if(n.startsWith("https://t.me")){const c=pe.from(t).toString("base64").replace(/[=]/g,"");n.endsWith("/")&&(n=n.slice(0,-1)),this.setWalletConnectDeepLink(n,s);const d=new URL(n);return d.searchParams.set("startapp",c),d.toString()}n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},async wait(e){return new Promise(t=>{setTimeout(t,e)})},openHref(e,t){const s=this.isTelegram()?"_blank":t;window.open(e,s,"noreferrer noopener")},setWalletConnectDeepLink(e,t){try{localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(e){try{const[t]=e.split("?");localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(m.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(m.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var e;const t=(e=de.state.data)==null?void 0:e.Wallet;if(!t)throw new Error('Missing "Wallet" view data');return t}},Ie=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),p=P({enabled:Ie,userSessionId:"",events:[],connectedWalletId:void 0}),_e={state:p,subscribe(e){return S(p.events,()=>e(we(p.events[p.events.length-1])))},initialize(){p.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(p.userSessionId=crypto.randomUUID())},setConnectedWalletId(e){p.connectedWalletId=e},click(e){if(p.enabled){const t={type:"CLICK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},track(e){if(p.enabled){const t={type:"TRACK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},view(e){if(p.enabled){const t={type:"VIEW",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}}},_=P({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),w={state:_,subscribe(e){return S(_,()=>e(_))},setChains(e){_.chains=e},setWalletConnectUri(e){_.walletConnectUri=e},setIsCustomDesktop(e){_.isCustomDesktop=e},setIsCustomMobile(e){_.isCustomMobile=e},setIsDataLoaded(e){_.isDataLoaded=e},setIsUiLoaded(e){_.isUiLoaded=e},setIsAuth(e){_.isAuth=e}},B=P({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),$={state:B,subscribe(e){return S(B,()=>e(B))},setConfig(e){var t,s;_e.initialize(),w.setChains(e.chains),w.setIsAuth(!!e.enableAuthMode),w.setIsCustomMobile(!!((t=e.mobileWallets)!=null&&t.length)),w.setIsCustomDesktop(!!((s=e.desktopWallets)!=null&&s.length)),m.setModalVersionInStorage(),Object.assign(B,e)}};var Ee=Object.defineProperty,se=Object.getOwnPropertySymbols,Oe=Object.prototype.hasOwnProperty,We=Object.prototype.propertyIsEnumerable,ne=(e,t,s)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ce=(e,t)=>{for(var s in t||(t={}))Oe.call(t,s)&&ne(e,s,t[s]);if(se)for(var s of se(t))We.call(t,s)&&ne(e,s,t[s]);return e};const G="https://explorer-api.walletconnect.com",Q="wcm",X="js-2.7.0";async function K(e,t){const s=Ce({sdkType:Q,sdkVersion:X},t),n=new URL(e,G);return n.searchParams.append("projectId",$.state.projectId),Object.entries(s).forEach(([c,d])=>{d&&n.searchParams.append(c,String(d))}),(await fetch(n)).json()}const M={async getDesktopListings(e){return K("/w3m/v1/getDesktopListings",e)},async getMobileListings(e){return K("/w3m/v1/getMobileListings",e)},async getInjectedListings(e){return K("/w3m/v1/getInjectedListings",e)},async getAllListings(e){return K("/w3m/v1/getAllListings",e)},getWalletImageUrl(e){return`${G}/w3m/v1/getWalletImage/${e}?projectId=${$.state.projectId}&sdkType=${Q}&sdkVersion=${X}`},getAssetImageUrl(e){return`${G}/w3m/v1/getAssetImage/${e}?projectId=${$.state.projectId}&sdkType=${Q}&sdkVersion=${X}`}};var Le=Object.defineProperty,oe=Object.getOwnPropertySymbols,Pe=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable,re=(e,t,s)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Me=(e,t)=>{for(var s in t||(t={}))Pe.call(t,s)&&re(e,s,t[s]);if(oe)for(var s of oe(t))Ae.call(t,s)&&re(e,s,t[s]);return e};const ae=m.isMobile(),E=P({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),Re={state:E,async getRecomendedWallets(){const{explorerRecommendedWalletIds:e,explorerExcludedWalletIds:t}=$.state;if(e==="NONE"||t==="ALL"&&!e)return E.recomendedWallets;if(m.isArray(e)){const n={recommendedIds:e.join(",")},{listings:l}=await M.getAllListings(n),c=Object.values(l);c.sort((d,f)=>{const W=e.indexOf(d.id),o=e.indexOf(f.id);return W-o}),E.recomendedWallets=c}else{const{chains:s,isAuth:n}=w.state,l=s==null?void 0:s.join(","),c=m.isArray(t),d={page:1,sdks:n?"auth_v1":void 0,entries:m.RECOMMENDED_WALLET_AMOUNT,chains:l,version:2,excludedIds:c?t.join(","):void 0},{listings:f}=ae?await M.getMobileListings(d):await M.getDesktopListings(d);E.recomendedWallets=Object.values(f)}return E.recomendedWallets},async getWallets(e){const t=Me({},e),{explorerRecommendedWalletIds:s,explorerExcludedWalletIds:n}=$.state,{recomendedWallets:l}=E;if(n==="ALL")return E.wallets;l.length?t.excludedIds=l.map(I=>I.id).join(","):m.isArray(s)&&(t.excludedIds=s.join(",")),m.isArray(n)&&(t.excludedIds=[t.excludedIds,n].filter(Boolean).join(",")),w.state.isAuth&&(t.sdks="auth_v1");const{page:c,search:d}=e,{listings:f,total:W}=ae?await M.getMobileListings(t):await M.getDesktopListings(t),o=Object.values(f),g=d?"search":"wallets";return E[g]={listings:[...E[g].listings,...o],total:W,page:c??1},{listings:o,total:W}},getWalletImageUrl(e){return M.getWalletImageUrl(e)},getAssetImageUrl(e){return M.getAssetImageUrl(e)},resetSearch(){E.search={listings:[],total:0,page:1}}},T=P({open:!1}),J={state:T,subscribe(e){return S(T,()=>e(T))},async open(e){return new Promise(t=>{const{isUiLoaded:s,isDataLoaded:n}=w.state;if(m.removeWalletConnectDeepLink(),w.setWalletConnectUri(e==null?void 0:e.uri),w.setChains(e==null?void 0:e.chains),de.reset("ConnectWallet"),s&&n)T.open=!0,t();else{const l=setInterval(()=>{const c=w.state;c.isUiLoaded&&c.isDataLoaded&&(clearInterval(l),T.open=!0,t())},200)}})},close(){T.open=!1}};var De=Object.defineProperty,ie=Object.getOwnPropertySymbols,Se=Object.prototype.hasOwnProperty,je=Object.prototype.propertyIsEnumerable,le=(e,t,s)=>t in e?De(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ue=(e,t)=>{for(var s in t||(t={}))Se.call(t,s)&&le(e,s,t[s]);if(ie)for(var s of ie(t))je.call(t,s)&&le(e,s,t[s]);return e};function Te(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const k=P({themeMode:Te()?"dark":"light"}),ce={state:k,subscribe(e){return S(k,()=>e(k))},setThemeConfig(e){const{themeMode:t,themeVariables:s}=e;t&&(k.themeMode=t),s&&(k.themeVariables=Ue({},s))}},D=P({open:!1,message:"",variant:"success"}),Ve={state:D,subscribe(e){return S(D,()=>e(D))},openToast(e,t){D.open=!0,D.message=e,D.variant=t},closeToast(){D.open=!1}};class $e{constructor(t){this.openModal=J.open,this.closeModal=J.close,this.subscribeModal=J.subscribe,this.setTheme=ce.setThemeConfig,ce.setThemeConfig(t),$.setConfig(t),this.initUi()}async initUi(){if(typeof window<"u"){await me(()=>import("./index-FF2LIIm3.js"),__vite__mapDeps([0,1,2]));const t=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",t),w.setIsUiLoaded(!0)}}}const xe=Object.freeze(Object.defineProperty({__proto__:null,WalletConnectModal:$e},Symbol.toStringTag,{value:"Module"}));export{m as C,Re as E,J as M,w as O,de as R,ce as T,Ve as a,_e as b,$ as c,xe as i}; diff --git a/assets/index-FF2LIIm3.js b/assets/index-BlNib8lH.js similarity index 99% rename from assets/index-FF2LIIm3.js rename to assets/index-BlNib8lH.js index 3eb1975..6fbbc1e 100644 --- a/assets/index-FF2LIIm3.js +++ b/assets/index-BlNib8lH.js @@ -1,4 +1,4 @@ -import{T as $t,M as oe,R as N,E as k,C as $,a as X,b as Br,O as Z,c as ht}from"./index-B0ywuJCf.js";import{w as Wr,x as Ur}from"./index-CiyH7SV9.js";/** +import{T as $t,M as oe,R as N,E as k,C as $,a as X,b as Br,O as Z,c as ht}from"./index-Cl2DsYqV.js";import{w as Wr,x as Ur}from"./index-CqoM6a8-.js";/** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: BSD-3-Clause diff --git a/assets/index-Cl2DsYqV.js b/assets/index-Cl2DsYqV.js new file mode 100644 index 0000000..cd54af1 --- /dev/null +++ b/assets/index-Cl2DsYqV.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BlNib8lH.js","assets/index-CqoM6a8-.js","assets/index-tWiYDii7.css"])))=>i.map(i=>d[i]); +import{B as pe,_ as me}from"./index-CqoM6a8-.js";const ge=Symbol(),ee=Object.getPrototypeOf,Y=new WeakMap,he=e=>e&&(Y.has(e)?Y.get(e):ee(e)===Object.prototype||ee(e)===Array.prototype),ye=e=>he(e)&&e[ge]||null,te=(e,t=!0)=>{Y.set(e,t)},z={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_DYNAMIC_ENV_ID:"7a6006b6-fa19-4e7a-abcf-34add623dff5",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"},F=e=>typeof e=="object"&&e!==null,L=new WeakMap,x=new WeakSet,ve=(e=Object.is,t=(o,h)=>new Proxy(o,h),s=o=>F(o)&&!x.has(o)&&(Array.isArray(o)||!(Symbol.iterator in o))&&!(o instanceof WeakMap)&&!(o instanceof WeakSet)&&!(o instanceof Error)&&!(o instanceof Number)&&!(o instanceof Date)&&!(o instanceof String)&&!(o instanceof RegExp)&&!(o instanceof ArrayBuffer),n=o=>{switch(o.status){case"fulfilled":return o.value;case"rejected":throw o.reason;default:throw o}},l=new WeakMap,c=(o,h,I=n)=>{const v=l.get(o);if((v==null?void 0:v[0])===h)return v[1];const b=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o));return te(b,!0),l.set(o,[h,b]),Reflect.ownKeys(o).forEach(j=>{if(Object.getOwnPropertyDescriptor(b,j))return;const O=Reflect.get(o,j),A={value:O,enumerable:!0,configurable:!0};if(x.has(O))te(O,!1);else if(O instanceof Promise)delete A.value,A.get=()=>I(O);else if(L.has(O)){const[y,H]=L.get(O);A.value=c(y,H(),I)}Object.defineProperty(b,j,A)}),Object.preventExtensions(b)},d=new WeakMap,f=[1,1],W=o=>{if(!F(o))throw new Error("object required");const h=d.get(o);if(h)return h;let I=f[0];const v=new Set,b=(i,a=++f[0])=>{I!==a&&(I=a,v.forEach(r=>r(i,a)))};let j=f[1];const O=(i=++f[1])=>(j!==i&&!v.size&&(j=i,y.forEach(([a])=>{const r=a[1](i);r>I&&(I=r)})),I),A=i=>(a,r)=>{const g=[...a];g[1]=[i,...g[1]],b(g,r)},y=new Map,H=(i,a)=>{if((z?"production":void 0)!=="production"&&y.has(i))throw new Error("prop listener already exists");if(v.size){const r=a[3](A(i));y.set(i,[a,r])}else y.set(i,[a])},Z=i=>{var a;const r=y.get(i);r&&(y.delete(i),(a=r[1])==null||a.call(r))},ue=i=>(v.add(i),v.size===1&&y.forEach(([r,g],U)=>{if((z?"production":void 0)!=="production"&&g)throw new Error("remove already exists");const N=r[3](A(U));y.set(U,[r,N])}),()=>{v.delete(i),v.size===0&&y.forEach(([r,g],U)=>{g&&(g(),y.set(U,[r]))})}),q=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o)),R=t(q,{deleteProperty(i,a){const r=Reflect.get(i,a);Z(a);const g=Reflect.deleteProperty(i,a);return g&&b(["delete",[a],r]),g},set(i,a,r,g){const U=Reflect.has(i,a),N=Reflect.get(i,a,g);if(U&&(e(N,r)||d.has(r)&&e(N,d.get(r))))return!0;Z(a),F(r)&&(r=ye(r)||r);let V=r;if(r instanceof Promise)r.then(C=>{r.status="fulfilled",r.value=C,b(["resolve",[a],C])}).catch(C=>{r.status="rejected",r.reason=C,b(["reject",[a],C])});else{!L.has(r)&&s(r)&&(V=W(r));const C=!x.has(V)&&L.get(V);C&&H(a,C)}return Reflect.set(i,a,V,g),b(["set",[a],r,N]),!0}});d.set(o,R);const fe=[q,O,c,ue];return L.set(R,fe),Reflect.ownKeys(o).forEach(i=>{const a=Object.getOwnPropertyDescriptor(o,i);"value"in a&&(R[i]=o[i],delete a.value,delete a.writable),Object.defineProperty(q,i,a)}),R})=>[W,L,x,e,t,s,n,l,c,d,f],[be]=ve();function P(e={}){return be(e)}function S(e,t,s){const n=L.get(e);(z?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let l;const c=[],d=n[3];let f=!1;const o=d(h=>{c.push(h),l||(l=Promise.resolve().then(()=>{l=void 0,f&&t(c.splice(0))}))});return f=!0,()=>{f=!1,o()}}function we(e,t){const s=L.get(e);(z?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[n,l,c]=s;return c(n,l(),t)}const u=P({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),de={state:u,subscribe(e){return S(u,()=>e(u))},push(e,t){e!==u.view&&(u.view=e,t&&(u.data=t),u.history.push(e))},reset(e){u.view=e,u.history=[e]},replace(e){u.history.length>1&&(u.history[u.history.length-1]=e,u.view=e)},goBack(){if(u.history.length>1){u.history.pop();const[e]=u.history.slice(-1);u.view=e}},setData(e){u.data=e}},m={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return m.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const e=navigator.userAgent.toLowerCase();return m.isMobile()&&(e.includes("iphone")||e.includes("ipad"))},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},isArray(e){return Array.isArray(e)&&e.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(e,t,s){if(m.isHttpUrl(e))return this.formatUniversalUrl(e,t,s);let n=e;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},formatUniversalUrl(e,t,s){if(!m.isHttpUrl(e))return this.formatNativeUrl(e,t,s);let n=e;if(n.startsWith("https://t.me")){const c=pe.from(t).toString("base64").replace(/[=]/g,"");n.endsWith("/")&&(n=n.slice(0,-1)),this.setWalletConnectDeepLink(n,s);const d=new URL(n);return d.searchParams.set("startapp",c),d.toString()}n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},async wait(e){return new Promise(t=>{setTimeout(t,e)})},openHref(e,t){const s=this.isTelegram()?"_blank":t;window.open(e,s,"noreferrer noopener")},setWalletConnectDeepLink(e,t){try{localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(e){try{const[t]=e.split("?");localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(m.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(m.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var e;const t=(e=de.state.data)==null?void 0:e.Wallet;if(!t)throw new Error('Missing "Wallet" view data');return t}},Ie=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),p=P({enabled:Ie,userSessionId:"",events:[],connectedWalletId:void 0}),_e={state:p,subscribe(e){return S(p.events,()=>e(we(p.events[p.events.length-1])))},initialize(){p.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(p.userSessionId=crypto.randomUUID())},setConnectedWalletId(e){p.connectedWalletId=e},click(e){if(p.enabled){const t={type:"CLICK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},track(e){if(p.enabled){const t={type:"TRACK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},view(e){if(p.enabled){const t={type:"VIEW",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}}},_=P({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),w={state:_,subscribe(e){return S(_,()=>e(_))},setChains(e){_.chains=e},setWalletConnectUri(e){_.walletConnectUri=e},setIsCustomDesktop(e){_.isCustomDesktop=e},setIsCustomMobile(e){_.isCustomMobile=e},setIsDataLoaded(e){_.isDataLoaded=e},setIsUiLoaded(e){_.isUiLoaded=e},setIsAuth(e){_.isAuth=e}},B=P({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),$={state:B,subscribe(e){return S(B,()=>e(B))},setConfig(e){var t,s;_e.initialize(),w.setChains(e.chains),w.setIsAuth(!!e.enableAuthMode),w.setIsCustomMobile(!!((t=e.mobileWallets)!=null&&t.length)),w.setIsCustomDesktop(!!((s=e.desktopWallets)!=null&&s.length)),m.setModalVersionInStorage(),Object.assign(B,e)}};var Ee=Object.defineProperty,se=Object.getOwnPropertySymbols,Oe=Object.prototype.hasOwnProperty,We=Object.prototype.propertyIsEnumerable,ne=(e,t,s)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ce=(e,t)=>{for(var s in t||(t={}))Oe.call(t,s)&&ne(e,s,t[s]);if(se)for(var s of se(t))We.call(t,s)&&ne(e,s,t[s]);return e};const G="https://explorer-api.walletconnect.com",Q="wcm",X="js-2.7.0";async function K(e,t){const s=Ce({sdkType:Q,sdkVersion:X},t),n=new URL(e,G);return n.searchParams.append("projectId",$.state.projectId),Object.entries(s).forEach(([c,d])=>{d&&n.searchParams.append(c,String(d))}),(await fetch(n)).json()}const M={async getDesktopListings(e){return K("/w3m/v1/getDesktopListings",e)},async getMobileListings(e){return K("/w3m/v1/getMobileListings",e)},async getInjectedListings(e){return K("/w3m/v1/getInjectedListings",e)},async getAllListings(e){return K("/w3m/v1/getAllListings",e)},getWalletImageUrl(e){return`${G}/w3m/v1/getWalletImage/${e}?projectId=${$.state.projectId}&sdkType=${Q}&sdkVersion=${X}`},getAssetImageUrl(e){return`${G}/w3m/v1/getAssetImage/${e}?projectId=${$.state.projectId}&sdkType=${Q}&sdkVersion=${X}`}};var Le=Object.defineProperty,oe=Object.getOwnPropertySymbols,Pe=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable,re=(e,t,s)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Me=(e,t)=>{for(var s in t||(t={}))Pe.call(t,s)&&re(e,s,t[s]);if(oe)for(var s of oe(t))Ae.call(t,s)&&re(e,s,t[s]);return e};const ae=m.isMobile(),E=P({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),Re={state:E,async getRecomendedWallets(){const{explorerRecommendedWalletIds:e,explorerExcludedWalletIds:t}=$.state;if(e==="NONE"||t==="ALL"&&!e)return E.recomendedWallets;if(m.isArray(e)){const n={recommendedIds:e.join(",")},{listings:l}=await M.getAllListings(n),c=Object.values(l);c.sort((d,f)=>{const W=e.indexOf(d.id),o=e.indexOf(f.id);return W-o}),E.recomendedWallets=c}else{const{chains:s,isAuth:n}=w.state,l=s==null?void 0:s.join(","),c=m.isArray(t),d={page:1,sdks:n?"auth_v1":void 0,entries:m.RECOMMENDED_WALLET_AMOUNT,chains:l,version:2,excludedIds:c?t.join(","):void 0},{listings:f}=ae?await M.getMobileListings(d):await M.getDesktopListings(d);E.recomendedWallets=Object.values(f)}return E.recomendedWallets},async getWallets(e){const t=Me({},e),{explorerRecommendedWalletIds:s,explorerExcludedWalletIds:n}=$.state,{recomendedWallets:l}=E;if(n==="ALL")return E.wallets;l.length?t.excludedIds=l.map(I=>I.id).join(","):m.isArray(s)&&(t.excludedIds=s.join(",")),m.isArray(n)&&(t.excludedIds=[t.excludedIds,n].filter(Boolean).join(",")),w.state.isAuth&&(t.sdks="auth_v1");const{page:c,search:d}=e,{listings:f,total:W}=ae?await M.getMobileListings(t):await M.getDesktopListings(t),o=Object.values(f),h=d?"search":"wallets";return E[h]={listings:[...E[h].listings,...o],total:W,page:c??1},{listings:o,total:W}},getWalletImageUrl(e){return M.getWalletImageUrl(e)},getAssetImageUrl(e){return M.getAssetImageUrl(e)},resetSearch(){E.search={listings:[],total:0,page:1}}},T=P({open:!1}),J={state:T,subscribe(e){return S(T,()=>e(T))},async open(e){return new Promise(t=>{const{isUiLoaded:s,isDataLoaded:n}=w.state;if(m.removeWalletConnectDeepLink(),w.setWalletConnectUri(e==null?void 0:e.uri),w.setChains(e==null?void 0:e.chains),de.reset("ConnectWallet"),s&&n)T.open=!0,t();else{const l=setInterval(()=>{const c=w.state;c.isUiLoaded&&c.isDataLoaded&&(clearInterval(l),T.open=!0,t())},200)}})},close(){T.open=!1}};var De=Object.defineProperty,ie=Object.getOwnPropertySymbols,Se=Object.prototype.hasOwnProperty,je=Object.prototype.propertyIsEnumerable,le=(e,t,s)=>t in e?De(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ue=(e,t)=>{for(var s in t||(t={}))Se.call(t,s)&&le(e,s,t[s]);if(ie)for(var s of ie(t))je.call(t,s)&&le(e,s,t[s]);return e};function Te(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const k=P({themeMode:Te()?"dark":"light"}),ce={state:k,subscribe(e){return S(k,()=>e(k))},setThemeConfig(e){const{themeMode:t,themeVariables:s}=e;t&&(k.themeMode=t),s&&(k.themeVariables=Ue({},s))}},D=P({open:!1,message:"",variant:"success"}),Ve={state:D,subscribe(e){return S(D,()=>e(D))},openToast(e,t){D.open=!0,D.message=e,D.variant=t},closeToast(){D.open=!1}};class $e{constructor(t){this.openModal=J.open,this.closeModal=J.close,this.subscribeModal=J.subscribe,this.setTheme=ce.setThemeConfig,ce.setThemeConfig(t),$.setConfig(t),this.initUi()}async initUi(){if(typeof window<"u"){await me(()=>import("./index-BlNib8lH.js"),__vite__mapDeps([0,1,2]));const t=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",t),w.setIsUiLoaded(!0)}}}const xe=Object.freeze(Object.defineProperty({__proto__:null,WalletConnectModal:$e},Symbol.toStringTag,{value:"Module"}));export{m as C,Re as E,J as M,w as O,de as R,ce as T,Ve as a,_e as b,$ as c,xe as i}; diff --git a/assets/index-CiyH7SV9.js b/assets/index-CqoM6a8-.js similarity index 99% rename from assets/index-CiyH7SV9.js rename to assets/index-CqoM6a8-.js index fa0b605..cdcedf9 100644 --- a/assets/index-CiyH7SV9.js +++ b/assets/index-CqoM6a8-.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/webcrypto-3I5ubJVL.js","assets/utils-D-KHXRuV.js","assets/nodecrypto-Co9-WRDE.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/webcrypto-6IU6aAco.js","assets/utils-C3TScgcd.js","assets/nodecrypto-BXD6e4iz.js"])))=>i.map(i=>d[i]); var _6=Object.defineProperty;var x6=(Xr,eo,to)=>eo in Xr?_6(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to;var Qu=(Xr,eo,to)=>x6(Xr,typeof eo!="symbol"?eo+"":eo,to);function _mergeNamespaces(Xr,eo){for(var to=0;toro[no]})}}}return Object.freeze(Object.defineProperty(Xr,Symbol.toStringTag,{value:"Module"}))}(function(){const eo=document.createElement("link").relList;if(eo&&eo.supports&&eo.supports("modulepreload"))return;for(const no of document.querySelectorAll('link[rel="modulepreload"]'))ro(no);new MutationObserver(no=>{for(const io of no)if(io.type==="childList")for(const oo of io.addedNodes)oo.tagName==="LINK"&&oo.rel==="modulepreload"&&ro(oo)}).observe(document,{childList:!0,subtree:!0});function to(no){const io={};return no.integrity&&(io.integrity=no.integrity),no.referrerPolicy&&(io.referrerPolicy=no.referrerPolicy),no.crossOrigin==="use-credentials"?io.credentials="include":no.crossOrigin==="anonymous"?io.credentials="omit":io.credentials="same-origin",io}function ro(no){if(no.ep)return;no.ep=!0;const io=to(no);fetch(no.href,io)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs$2(Xr){return Xr&&Xr.__esModule&&Object.prototype.hasOwnProperty.call(Xr,"default")?Xr.default:Xr}function getAugmentedNamespace(Xr){if(Xr.__esModule)return Xr;var eo=Xr.default;if(typeof eo=="function"){var to=function ro(){return this instanceof ro?Reflect.construct(eo,arguments,this.constructor):eo.apply(this,arguments)};to.prototype=eo.prototype}else to={};return Object.defineProperty(to,"__esModule",{value:!0}),Object.keys(Xr).forEach(function(ro){var no=Object.getOwnPropertyDescriptor(Xr,ro);Object.defineProperty(to,ro,no.get?no:{enumerable:!0,get:function(){return Xr[ro]}})}),to}var jsxRuntime={exports:{}},reactJsxRuntime_production_min={},react={exports:{}},react_production_min={};/** * @license React * react.production.min.js @@ -2155,11 +2155,11 @@ zoo`.split(` ${prettyStateOverride(go)}`),super(eo.shortMessage,{cause:eo,docsPath:ro,metaMessages:[...eo.metaMessages?[...eo.metaMessages," "]:[],"Raw Call Arguments:",vo].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=eo}}class ContractFunctionExecutionError extends BaseError{constructor(eo,{abi:to,args:ro,contractAddress:no,docsPath:io,functionName:oo,sender:ao}){const so=getAbiItem({abi:to,args:ro,name:oo}),co=so?formatAbiItemWithArgs({abiItem:so,args:ro,includeFunctionName:!1,includeName:!1}):void 0,lo=so?formatAbiItem(so,{includeName:!0}):void 0,fo=prettyPrint({address:no&&getContractAddress(no),function:lo,args:co&&co!=="()"&&`${[...Array((oo==null?void 0:oo.length)??0).keys()].map(()=>" ").join("")}${co}`,sender:ao});super(eo.shortMessage||`An unknown error occurred while executing the contract function "${oo}".`,{cause:eo,docsPath:io,metaMessages:[...eo.metaMessages?[...eo.metaMessages," "]:[],fo&&"Contract Call:",fo].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=to,this.args=ro,this.cause=eo,this.contractAddress=no,this.functionName=oo,this.sender=ao}}class ContractFunctionRevertedError extends BaseError{constructor({abi:eo,data:to,functionName:ro,message:no}){let io,oo,ao,so;if(to&&to!=="0x")try{oo=decodeErrorResult({abi:eo,data:to});const{abiItem:lo,errorName:fo,args:ho}=oo;if(fo==="Error")so=ho[0];else if(fo==="Panic"){const[go]=ho;so=panicReasons[go]}else{const go=lo?formatAbiItem(lo,{includeName:!0}):void 0,yo=lo&&ho?formatAbiItemWithArgs({abiItem:lo,args:ho,includeFunctionName:!1,includeName:!1}):void 0;ao=[go?`Error: ${go}`:"",yo&&yo!=="()"?` ${[...Array((fo==null?void 0:fo.length)??0).keys()].map(()=>" ").join("")}${yo}`:""]}}catch(lo){io=lo}else no&&(so=no);let co;io instanceof AbiErrorSignatureNotFoundError&&(co=io.signature,ao=[`Unable to decode signature "${co}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${co}.`]),super(so&&so!=="execution reverted"||co?[`The contract function "${ro}" reverted with the following ${co?"signature":"reason"}:`,so||co].join(` `):`The contract function "${ro}" reverted.`,{cause:io,metaMessages:ao,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=oo,this.reason=so,this.signature=co}}class ContractFunctionZeroDataError extends BaseError{constructor({functionName:eo}){super(`The contract function "${eo}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${eo}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class CounterfactualDeploymentFailedError extends BaseError{constructor({factory:eo}){super(`Deployment for counterfactual contract call failed${eo?` for factory "${eo}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class RawContractError extends BaseError{constructor({data:eo,message:to}){super(to||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=eo}}class HttpRequestError extends BaseError{constructor({body:eo,cause:to,details:ro,headers:no,status:io,url:oo}){super("HTTP request failed.",{cause:to,details:ro,metaMessages:[io&&`Status: ${io}`,`URL: ${getUrl(oo)}`,eo&&`Request body: ${stringify$4(eo)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=eo,this.headers=no,this.status=io,this.url=oo}}class RpcRequestError extends BaseError{constructor({body:eo,error:to,url:ro}){super("RPC Request failed.",{cause:to,details:to.message,metaMessages:[`URL: ${getUrl(ro)}`,`Request body: ${stringify$4(eo)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=to.code}}class TimeoutError extends BaseError{constructor({body:eo,url:to}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${getUrl(to)}`,`Request body: ${stringify$4(eo)}`],name:"TimeoutError"})}}const unknownErrorCode=-1;class RpcError extends BaseError{constructor(eo,{code:to,docsPath:ro,metaMessages:no,name:io,shortMessage:oo}){super(oo,{cause:eo,docsPath:ro,metaMessages:no||(eo==null?void 0:eo.metaMessages),name:io||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=io||eo.name,this.code=eo instanceof RpcRequestError?eo.code:to??unknownErrorCode}}class ProviderRpcError extends RpcError{constructor(eo,to){super(eo,to),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=to.data}}class ParseRpcError extends RpcError{constructor(eo){super(eo,{code:ParseRpcError.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(ParseRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class InvalidRequestRpcError extends RpcError{constructor(eo){super(eo,{code:InvalidRequestRpcError.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(InvalidRequestRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class MethodNotFoundRpcError extends RpcError{constructor(eo,{method:to}={}){super(eo,{code:MethodNotFoundRpcError.code,name:"MethodNotFoundRpcError",shortMessage:`The method${to?` "${to}"`:""} does not exist / is not available.`})}}Object.defineProperty(MethodNotFoundRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class InvalidParamsRpcError extends RpcError{constructor(eo){super(eo,{code:InvalidParamsRpcError.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(` `)})}}Object.defineProperty(InvalidParamsRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class InternalRpcError extends RpcError{constructor(eo){super(eo,{code:InternalRpcError.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(InternalRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class InvalidInputRpcError extends RpcError{constructor(eo){super(eo,{code:InvalidInputRpcError.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(` -`)})}}Object.defineProperty(InvalidInputRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class ResourceNotFoundRpcError extends RpcError{constructor(eo){super(eo,{code:ResourceNotFoundRpcError.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(ResourceNotFoundRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class ResourceUnavailableRpcError extends RpcError{constructor(eo){super(eo,{code:ResourceUnavailableRpcError.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(ResourceUnavailableRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class TransactionRejectedRpcError extends RpcError{constructor(eo){super(eo,{code:TransactionRejectedRpcError.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(TransactionRejectedRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class MethodNotSupportedRpcError extends RpcError{constructor(eo,{method:to}={}){super(eo,{code:MethodNotSupportedRpcError.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${to?` "${to}"`:""} is not implemented.`})}}Object.defineProperty(MethodNotSupportedRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class LimitExceededRpcError extends RpcError{constructor(eo){super(eo,{code:LimitExceededRpcError.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(LimitExceededRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class JsonRpcVersionUnsupportedError extends RpcError{constructor(eo){super(eo,{code:JsonRpcVersionUnsupportedError.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(JsonRpcVersionUnsupportedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});let UserRejectedRequestError$1=class k_ extends ProviderRpcError{constructor(eo){super(eo,{code:k_.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(UserRejectedRequestError$1,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class UnauthorizedProviderError extends ProviderRpcError{constructor(eo){super(eo,{code:UnauthorizedProviderError.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(UnauthorizedProviderError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class UnsupportedProviderMethodError extends ProviderRpcError{constructor(eo,{method:to}={}){super(eo,{code:UnsupportedProviderMethodError.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${to?` " ${to}"`:""}.`})}}Object.defineProperty(UnsupportedProviderMethodError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class ProviderDisconnectedError extends ProviderRpcError{constructor(eo){super(eo,{code:ProviderDisconnectedError.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(ProviderDisconnectedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class ChainDisconnectedError extends ProviderRpcError{constructor(eo){super(eo,{code:ChainDisconnectedError.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(ChainDisconnectedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class SwitchChainError extends ProviderRpcError{constructor(eo){super(eo,{code:SwitchChainError.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(SwitchChainError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class UnknownRpcError extends RpcError{constructor(eo){super(eo,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const EXECUTION_REVERTED_ERROR_CODE=3;function getContractError(Xr,{abi:eo,address:to,args:ro,docsPath:no,functionName:io,sender:oo}){const{code:ao,data:so,message:co,shortMessage:lo}=Xr instanceof RawContractError?Xr:Xr instanceof BaseError?Xr.walk(ho=>"data"in ho)||Xr.walk():{},fo=Xr instanceof AbiDecodingZeroDataError?new ContractFunctionZeroDataError({functionName:io}):[EXECUTION_REVERTED_ERROR_CODE,InternalRpcError.code].includes(ao)&&(so||co||lo)?new ContractFunctionRevertedError({abi:eo,data:typeof so=="object"?so.data:so,functionName:io,message:lo??co}):Xr;return new ContractFunctionExecutionError(fo,{abi:eo,args:ro,contractAddress:to,docsPath:no,functionName:io,sender:oo})}function publicKeyToAddress(Xr){const eo=keccak256(`0x${Xr.substring(4)}`).substring(26);return checksumAddress(`0x${eo}`)}const scriptRel="modulepreload",assetsURL=function(Xr){return"/push-wallet/"+Xr},seen={},__vitePreload=function(eo,to,ro){let no=Promise.resolve();if(to&&to.length>0){document.getElementsByTagName("link");const oo=document.querySelector("meta[property=csp-nonce]"),ao=(oo==null?void 0:oo.nonce)||(oo==null?void 0:oo.getAttribute("nonce"));no=Promise.allSettled(to.map(so=>{if(so=assetsURL(so),so in seen)return;seen[so]=!0;const co=so.endsWith(".css"),lo=co?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${so}"]${lo}`))return;const fo=document.createElement("link");if(fo.rel=co?"stylesheet":scriptRel,co||(fo.as="script"),fo.crossOrigin="",fo.href=so,ao&&fo.setAttribute("nonce",ao),document.head.appendChild(fo),co)return new Promise((ho,go)=>{fo.addEventListener("load",ho),fo.addEventListener("error",()=>go(new Error(`Unable to preload CSS for ${so}`)))})}))}function io(oo){const ao=new Event("vite:preloadError",{cancelable:!0});if(ao.payload=oo,window.dispatchEvent(ao),!ao.defaultPrevented)throw oo}return no.then(oo=>{for(const ao of oo||[])ao.status==="rejected"&&io(ao.reason);return eo().catch(io)})};async function recoverPublicKey({hash:Xr,signature:eo}){const to=isHex$4(Xr)?Xr:toHex$1(Xr),{secp256k1:ro}=await __vitePreload(async()=>{const{secp256k1:oo}=await Promise.resolve().then(()=>secp256k1$3);return{secp256k1:oo}},void 0);return`0x${(()=>{if(typeof eo=="object"&&"r"in eo&&"s"in eo){const{r:co,s:lo,v:fo,yParity:ho}=eo,go=Number(ho??fo),yo=toRecoveryBit(go);return new ro.Signature(hexToBigInt(co),hexToBigInt(lo)).addRecoveryBit(yo)}const oo=isHex$4(eo)?eo:toHex$1(eo),ao=hexToNumber$2(`0x${oo.slice(130)}`),so=toRecoveryBit(ao);return ro.Signature.fromCompact(oo.substring(2,130)).addRecoveryBit(so)})().recoverPublicKey(to.substring(2)).toHex(!1)}`}function toRecoveryBit(Xr){if(Xr===0||Xr===1)return Xr;if(Xr===27)return 0;if(Xr===28)return 1;throw new Error("Invalid yParityOrV value")}async function recoverAddress({hash:Xr,signature:eo}){return publicKeyToAddress(await recoverPublicKey({hash:Xr,signature:eo}))}function toRlp(Xr,eo="hex"){const to=getEncodable(Xr),ro=createCursor(new Uint8Array(to.length));return to.encode(ro),eo==="hex"?bytesToHex$2(ro.bytes):ro.bytes}function getEncodable(Xr){return Array.isArray(Xr)?getEncodableList(Xr.map(eo=>getEncodable(eo))):getEncodableBytes(Xr)}function getEncodableList(Xr){const eo=Xr.reduce((no,io)=>no+io.length,0),to=getSizeOfLength(eo);return{length:eo<=55?1+eo:1+to+eo,encode(no){eo<=55?no.pushByte(192+eo):(no.pushByte(247+to),to===1?no.pushUint8(eo):to===2?no.pushUint16(eo):to===3?no.pushUint24(eo):no.pushUint32(eo));for(const{encode:io}of Xr)io(no)}}}function getEncodableBytes(Xr){const eo=typeof Xr=="string"?hexToBytes$3(Xr):Xr,to=getSizeOfLength(eo.length);return{length:eo.length===1&&eo[0]<128?1:eo.length<=55?1+eo.length:1+to+eo.length,encode(no){eo.length===1&&eo[0]<128?no.pushBytes(eo):eo.length<=55?(no.pushByte(128+eo.length),no.pushBytes(eo)):(no.pushByte(183+to),to===1?no.pushUint8(eo.length):to===2?no.pushUint16(eo.length):to===3?no.pushUint24(eo.length):no.pushUint32(eo.length),no.pushBytes(eo))}}}function getSizeOfLength(Xr){if(Xr<2**8)return 1;if(Xr<2**16)return 2;if(Xr<2**24)return 3;if(Xr<2**32)return 4;throw new BaseError("Length is too large.")}function hashAuthorization(Xr){const{chainId:eo,contractAddress:to,nonce:ro,to:no}=Xr,io=keccak256(concatHex(["0x05",toRlp([eo?numberToHex(eo):"0x",to,ro?numberToHex(ro):"0x"])]));return no==="bytes"?hexToBytes$3(io):io}async function recoverAuthorizationAddress(Xr){const{authorization:eo,signature:to}=Xr;return recoverAddress({hash:hashAuthorization(eo),signature:to??eo})}class EstimateGasExecutionError extends BaseError{constructor(eo,{account:to,docsPath:ro,chain:no,data:io,gas:oo,gasPrice:ao,maxFeePerGas:so,maxPriorityFeePerGas:co,nonce:lo,to:fo,value:ho}){var yo;const go=prettyPrint({from:to==null?void 0:to.address,to:fo,value:typeof ho<"u"&&`${formatEther$1(ho)} ${((yo=no==null?void 0:no.nativeCurrency)==null?void 0:yo.symbol)||"ETH"}`,data:io,gas:oo,gasPrice:typeof ao<"u"&&`${formatGwei(ao)} gwei`,maxFeePerGas:typeof so<"u"&&`${formatGwei(so)} gwei`,maxPriorityFeePerGas:typeof co<"u"&&`${formatGwei(co)} gwei`,nonce:lo});super(eo.shortMessage,{cause:eo,docsPath:ro,metaMessages:[...eo.metaMessages?[...eo.metaMessages," "]:[],"Estimate Gas Arguments:",go].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=eo}}class ExecutionRevertedError extends BaseError{constructor({cause:eo,message:to}={}){var no;const ro=(no=to==null?void 0:to.replace("execution reverted: ",""))==null?void 0:no.replace("execution reverted","");super(`Execution reverted ${ro?`with reason: ${ro}`:"for an unknown reason"}.`,{cause:eo,name:"ExecutionRevertedError"})}}Object.defineProperty(ExecutionRevertedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ExecutionRevertedError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class FeeCapTooHighError extends BaseError{constructor({cause:eo,maxFeePerGas:to}={}){super(`The fee cap (\`maxFeePerGas\`${to?` = ${formatGwei(to)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:eo,name:"FeeCapTooHighError"})}}Object.defineProperty(FeeCapTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class FeeCapTooLowError extends BaseError{constructor({cause:eo,maxFeePerGas:to}={}){super(`The fee cap (\`maxFeePerGas\`${to?` = ${formatGwei(to)}`:""} gwei) cannot be lower than the block base fee.`,{cause:eo,name:"FeeCapTooLowError"})}}Object.defineProperty(FeeCapTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class NonceTooHighError extends BaseError{constructor({cause:eo,nonce:to}={}){super(`Nonce provided for the transaction ${to?`(${to}) `:""}is higher than the next one expected.`,{cause:eo,name:"NonceTooHighError"})}}Object.defineProperty(NonceTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class NonceTooLowError extends BaseError{constructor({cause:eo,nonce:to}={}){super([`Nonce provided for the transaction ${to?`(${to}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(` +`)})}}Object.defineProperty(InvalidInputRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class ResourceNotFoundRpcError extends RpcError{constructor(eo){super(eo,{code:ResourceNotFoundRpcError.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(ResourceNotFoundRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class ResourceUnavailableRpcError extends RpcError{constructor(eo){super(eo,{code:ResourceUnavailableRpcError.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(ResourceUnavailableRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class TransactionRejectedRpcError extends RpcError{constructor(eo){super(eo,{code:TransactionRejectedRpcError.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(TransactionRejectedRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class MethodNotSupportedRpcError extends RpcError{constructor(eo,{method:to}={}){super(eo,{code:MethodNotSupportedRpcError.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${to?` "${to}"`:""} is not implemented.`})}}Object.defineProperty(MethodNotSupportedRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class LimitExceededRpcError extends RpcError{constructor(eo){super(eo,{code:LimitExceededRpcError.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(LimitExceededRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class JsonRpcVersionUnsupportedError extends RpcError{constructor(eo){super(eo,{code:JsonRpcVersionUnsupportedError.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(JsonRpcVersionUnsupportedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});let UserRejectedRequestError$1=class k_ extends ProviderRpcError{constructor(eo){super(eo,{code:k_.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(UserRejectedRequestError$1,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class UnauthorizedProviderError extends ProviderRpcError{constructor(eo){super(eo,{code:UnauthorizedProviderError.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(UnauthorizedProviderError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class UnsupportedProviderMethodError extends ProviderRpcError{constructor(eo,{method:to}={}){super(eo,{code:UnsupportedProviderMethodError.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${to?` " ${to}"`:""}.`})}}Object.defineProperty(UnsupportedProviderMethodError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class ProviderDisconnectedError extends ProviderRpcError{constructor(eo){super(eo,{code:ProviderDisconnectedError.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(ProviderDisconnectedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class ChainDisconnectedError extends ProviderRpcError{constructor(eo){super(eo,{code:ChainDisconnectedError.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(ChainDisconnectedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class SwitchChainError extends ProviderRpcError{constructor(eo){super(eo,{code:SwitchChainError.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(SwitchChainError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class UnknownRpcError extends RpcError{constructor(eo){super(eo,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const EXECUTION_REVERTED_ERROR_CODE=3;function getContractError(Xr,{abi:eo,address:to,args:ro,docsPath:no,functionName:io,sender:oo}){const{code:ao,data:so,message:co,shortMessage:lo}=Xr instanceof RawContractError?Xr:Xr instanceof BaseError?Xr.walk(ho=>"data"in ho)||Xr.walk():{},fo=Xr instanceof AbiDecodingZeroDataError?new ContractFunctionZeroDataError({functionName:io}):[EXECUTION_REVERTED_ERROR_CODE,InternalRpcError.code].includes(ao)&&(so||co||lo)?new ContractFunctionRevertedError({abi:eo,data:typeof so=="object"?so.data:so,functionName:io,message:lo??co}):Xr;return new ContractFunctionExecutionError(fo,{abi:eo,args:ro,contractAddress:to,docsPath:no,functionName:io,sender:oo})}function publicKeyToAddress(Xr){const eo=keccak256(`0x${Xr.substring(4)}`).substring(26);return checksumAddress(`0x${eo}`)}const scriptRel="modulepreload",assetsURL=function(Xr){return"/"+Xr},seen={},__vitePreload=function(eo,to,ro){let no=Promise.resolve();if(to&&to.length>0){document.getElementsByTagName("link");const oo=document.querySelector("meta[property=csp-nonce]"),ao=(oo==null?void 0:oo.nonce)||(oo==null?void 0:oo.getAttribute("nonce"));no=Promise.allSettled(to.map(so=>{if(so=assetsURL(so),so in seen)return;seen[so]=!0;const co=so.endsWith(".css"),lo=co?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${so}"]${lo}`))return;const fo=document.createElement("link");if(fo.rel=co?"stylesheet":scriptRel,co||(fo.as="script"),fo.crossOrigin="",fo.href=so,ao&&fo.setAttribute("nonce",ao),document.head.appendChild(fo),co)return new Promise((ho,go)=>{fo.addEventListener("load",ho),fo.addEventListener("error",()=>go(new Error(`Unable to preload CSS for ${so}`)))})}))}function io(oo){const ao=new Event("vite:preloadError",{cancelable:!0});if(ao.payload=oo,window.dispatchEvent(ao),!ao.defaultPrevented)throw oo}return no.then(oo=>{for(const ao of oo||[])ao.status==="rejected"&&io(ao.reason);return eo().catch(io)})};async function recoverPublicKey({hash:Xr,signature:eo}){const to=isHex$4(Xr)?Xr:toHex$1(Xr),{secp256k1:ro}=await __vitePreload(async()=>{const{secp256k1:oo}=await Promise.resolve().then(()=>secp256k1$3);return{secp256k1:oo}},void 0);return`0x${(()=>{if(typeof eo=="object"&&"r"in eo&&"s"in eo){const{r:co,s:lo,v:fo,yParity:ho}=eo,go=Number(ho??fo),yo=toRecoveryBit(go);return new ro.Signature(hexToBigInt(co),hexToBigInt(lo)).addRecoveryBit(yo)}const oo=isHex$4(eo)?eo:toHex$1(eo),ao=hexToNumber$2(`0x${oo.slice(130)}`),so=toRecoveryBit(ao);return ro.Signature.fromCompact(oo.substring(2,130)).addRecoveryBit(so)})().recoverPublicKey(to.substring(2)).toHex(!1)}`}function toRecoveryBit(Xr){if(Xr===0||Xr===1)return Xr;if(Xr===27)return 0;if(Xr===28)return 1;throw new Error("Invalid yParityOrV value")}async function recoverAddress({hash:Xr,signature:eo}){return publicKeyToAddress(await recoverPublicKey({hash:Xr,signature:eo}))}function toRlp(Xr,eo="hex"){const to=getEncodable(Xr),ro=createCursor(new Uint8Array(to.length));return to.encode(ro),eo==="hex"?bytesToHex$2(ro.bytes):ro.bytes}function getEncodable(Xr){return Array.isArray(Xr)?getEncodableList(Xr.map(eo=>getEncodable(eo))):getEncodableBytes(Xr)}function getEncodableList(Xr){const eo=Xr.reduce((no,io)=>no+io.length,0),to=getSizeOfLength(eo);return{length:eo<=55?1+eo:1+to+eo,encode(no){eo<=55?no.pushByte(192+eo):(no.pushByte(247+to),to===1?no.pushUint8(eo):to===2?no.pushUint16(eo):to===3?no.pushUint24(eo):no.pushUint32(eo));for(const{encode:io}of Xr)io(no)}}}function getEncodableBytes(Xr){const eo=typeof Xr=="string"?hexToBytes$3(Xr):Xr,to=getSizeOfLength(eo.length);return{length:eo.length===1&&eo[0]<128?1:eo.length<=55?1+eo.length:1+to+eo.length,encode(no){eo.length===1&&eo[0]<128?no.pushBytes(eo):eo.length<=55?(no.pushByte(128+eo.length),no.pushBytes(eo)):(no.pushByte(183+to),to===1?no.pushUint8(eo.length):to===2?no.pushUint16(eo.length):to===3?no.pushUint24(eo.length):no.pushUint32(eo.length),no.pushBytes(eo))}}}function getSizeOfLength(Xr){if(Xr<2**8)return 1;if(Xr<2**16)return 2;if(Xr<2**24)return 3;if(Xr<2**32)return 4;throw new BaseError("Length is too large.")}function hashAuthorization(Xr){const{chainId:eo,contractAddress:to,nonce:ro,to:no}=Xr,io=keccak256(concatHex(["0x05",toRlp([eo?numberToHex(eo):"0x",to,ro?numberToHex(ro):"0x"])]));return no==="bytes"?hexToBytes$3(io):io}async function recoverAuthorizationAddress(Xr){const{authorization:eo,signature:to}=Xr;return recoverAddress({hash:hashAuthorization(eo),signature:to??eo})}class EstimateGasExecutionError extends BaseError{constructor(eo,{account:to,docsPath:ro,chain:no,data:io,gas:oo,gasPrice:ao,maxFeePerGas:so,maxPriorityFeePerGas:co,nonce:lo,to:fo,value:ho}){var yo;const go=prettyPrint({from:to==null?void 0:to.address,to:fo,value:typeof ho<"u"&&`${formatEther$1(ho)} ${((yo=no==null?void 0:no.nativeCurrency)==null?void 0:yo.symbol)||"ETH"}`,data:io,gas:oo,gasPrice:typeof ao<"u"&&`${formatGwei(ao)} gwei`,maxFeePerGas:typeof so<"u"&&`${formatGwei(so)} gwei`,maxPriorityFeePerGas:typeof co<"u"&&`${formatGwei(co)} gwei`,nonce:lo});super(eo.shortMessage,{cause:eo,docsPath:ro,metaMessages:[...eo.metaMessages?[...eo.metaMessages," "]:[],"Estimate Gas Arguments:",go].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=eo}}class ExecutionRevertedError extends BaseError{constructor({cause:eo,message:to}={}){var no;const ro=(no=to==null?void 0:to.replace("execution reverted: ",""))==null?void 0:no.replace("execution reverted","");super(`Execution reverted ${ro?`with reason: ${ro}`:"for an unknown reason"}.`,{cause:eo,name:"ExecutionRevertedError"})}}Object.defineProperty(ExecutionRevertedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ExecutionRevertedError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class FeeCapTooHighError extends BaseError{constructor({cause:eo,maxFeePerGas:to}={}){super(`The fee cap (\`maxFeePerGas\`${to?` = ${formatGwei(to)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:eo,name:"FeeCapTooHighError"})}}Object.defineProperty(FeeCapTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class FeeCapTooLowError extends BaseError{constructor({cause:eo,maxFeePerGas:to}={}){super(`The fee cap (\`maxFeePerGas\`${to?` = ${formatGwei(to)}`:""} gwei) cannot be lower than the block base fee.`,{cause:eo,name:"FeeCapTooLowError"})}}Object.defineProperty(FeeCapTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class NonceTooHighError extends BaseError{constructor({cause:eo,nonce:to}={}){super(`Nonce provided for the transaction ${to?`(${to}) `:""}is higher than the next one expected.`,{cause:eo,name:"NonceTooHighError"})}}Object.defineProperty(NonceTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class NonceTooLowError extends BaseError{constructor({cause:eo,nonce:to}={}){super([`Nonce provided for the transaction ${to?`(${to}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(` `),{cause:eo,name:"NonceTooLowError"})}}Object.defineProperty(NonceTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class NonceMaxValueError extends BaseError{constructor({cause:eo,nonce:to}={}){super(`Nonce provided for the transaction ${to?`(${to}) `:""}exceeds the maximum allowed nonce.`,{cause:eo,name:"NonceMaxValueError"})}}Object.defineProperty(NonceMaxValueError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});let InsufficientFundsError$1=class extends BaseError{constructor({cause:eo}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(` `),{cause:eo,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(InsufficientFundsError$1,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class IntrinsicGasTooHighError extends BaseError{constructor({cause:eo,gas:to}={}){super(`The amount of gas ${to?`(${to}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:eo,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(IntrinsicGasTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class IntrinsicGasTooLowError extends BaseError{constructor({cause:eo,gas:to}={}){super(`The amount of gas ${to?`(${to}) `:""}provided for the transaction is too low.`,{cause:eo,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(IntrinsicGasTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class TransactionTypeNotSupportedError extends BaseError{constructor({cause:eo}){super("The transaction type is not supported for this chain.",{cause:eo,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(TransactionTypeNotSupportedError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class TipAboveFeeCapError extends BaseError{constructor({cause:eo,maxPriorityFeePerGas:to,maxFeePerGas:ro}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${to?` = ${formatGwei(to)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${ro?` = ${formatGwei(ro)} gwei`:""}).`].join(` `),{cause:eo,name:"TipAboveFeeCapError"})}}Object.defineProperty(TipAboveFeeCapError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class UnknownNodeError extends BaseError{constructor({cause:eo}){super(`An error occurred while executing: ${eo==null?void 0:eo.shortMessage}`,{cause:eo,name:"UnknownNodeError"})}}function getNodeError(Xr,eo){const to=(Xr.details||"").toLowerCase(),ro=Xr instanceof BaseError?Xr.walk(no=>(no==null?void 0:no.code)===ExecutionRevertedError.code):Xr;return ro instanceof BaseError?new ExecutionRevertedError({cause:Xr,message:ro.details}):ExecutionRevertedError.nodeMessage.test(to)?new ExecutionRevertedError({cause:Xr,message:Xr.details}):FeeCapTooHighError.nodeMessage.test(to)?new FeeCapTooHighError({cause:Xr,maxFeePerGas:eo==null?void 0:eo.maxFeePerGas}):FeeCapTooLowError.nodeMessage.test(to)?new FeeCapTooLowError({cause:Xr,maxFeePerGas:eo==null?void 0:eo.maxFeePerGas}):NonceTooHighError.nodeMessage.test(to)?new NonceTooHighError({cause:Xr,nonce:eo==null?void 0:eo.nonce}):NonceTooLowError.nodeMessage.test(to)?new NonceTooLowError({cause:Xr,nonce:eo==null?void 0:eo.nonce}):NonceMaxValueError.nodeMessage.test(to)?new NonceMaxValueError({cause:Xr,nonce:eo==null?void 0:eo.nonce}):InsufficientFundsError$1.nodeMessage.test(to)?new InsufficientFundsError$1({cause:Xr}):IntrinsicGasTooHighError.nodeMessage.test(to)?new IntrinsicGasTooHighError({cause:Xr,gas:eo==null?void 0:eo.gas}):IntrinsicGasTooLowError.nodeMessage.test(to)?new IntrinsicGasTooLowError({cause:Xr,gas:eo==null?void 0:eo.gas}):TransactionTypeNotSupportedError.nodeMessage.test(to)?new TransactionTypeNotSupportedError({cause:Xr}):TipAboveFeeCapError.nodeMessage.test(to)?new TipAboveFeeCapError({cause:Xr,maxFeePerGas:eo==null?void 0:eo.maxFeePerGas,maxPriorityFeePerGas:eo==null?void 0:eo.maxPriorityFeePerGas}):new UnknownNodeError({cause:Xr})}function getEstimateGasError(Xr,{docsPath:eo,...to}){const ro=(()=>{const no=getNodeError(Xr,to);return no instanceof UnknownNodeError?Xr:no})();return new EstimateGasExecutionError(ro,{docsPath:eo,...to})}function extract(Xr,{format:eo}){if(!eo)return{};const to={};function ro(io){const oo=Object.keys(io);for(const ao of oo)ao in Xr&&(to[ao]=Xr[ao]),io[ao]&&typeof io[ao]=="object"&&!Array.isArray(io[ao])&&ro(io[ao])}const no=eo(Xr||{});return ro(no),to}function defineFormatter(Xr,eo){return({exclude:to,format:ro})=>({exclude:to,format:no=>{const io=eo(no);if(to)for(const oo of to)delete io[oo];return{...io,...ro(no)}},type:Xr})}const rpcTransactionType={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function formatTransactionRequest(Xr){const eo={};return typeof Xr.authorizationList<"u"&&(eo.authorizationList=formatAuthorizationList$1(Xr.authorizationList)),typeof Xr.accessList<"u"&&(eo.accessList=Xr.accessList),typeof Xr.blobVersionedHashes<"u"&&(eo.blobVersionedHashes=Xr.blobVersionedHashes),typeof Xr.blobs<"u"&&(typeof Xr.blobs[0]!="string"?eo.blobs=Xr.blobs.map(to=>bytesToHex$2(to)):eo.blobs=Xr.blobs),typeof Xr.data<"u"&&(eo.data=Xr.data),typeof Xr.from<"u"&&(eo.from=Xr.from),typeof Xr.gas<"u"&&(eo.gas=numberToHex(Xr.gas)),typeof Xr.gasPrice<"u"&&(eo.gasPrice=numberToHex(Xr.gasPrice)),typeof Xr.maxFeePerBlobGas<"u"&&(eo.maxFeePerBlobGas=numberToHex(Xr.maxFeePerBlobGas)),typeof Xr.maxFeePerGas<"u"&&(eo.maxFeePerGas=numberToHex(Xr.maxFeePerGas)),typeof Xr.maxPriorityFeePerGas<"u"&&(eo.maxPriorityFeePerGas=numberToHex(Xr.maxPriorityFeePerGas)),typeof Xr.nonce<"u"&&(eo.nonce=numberToHex(Xr.nonce)),typeof Xr.to<"u"&&(eo.to=Xr.to),typeof Xr.type<"u"&&(eo.type=rpcTransactionType[Xr.type]),typeof Xr.value<"u"&&(eo.value=numberToHex(Xr.value)),eo}const defineTransactionRequest=defineFormatter("transactionRequest",formatTransactionRequest);function formatAuthorizationList$1(Xr){return Xr.map(eo=>({address:eo.contractAddress,r:eo.r,s:eo.s,chainId:numberToHex(eo.chainId),nonce:numberToHex(eo.nonce),...typeof eo.yParity<"u"?{yParity:numberToHex(eo.yParity)}:{},...typeof eo.v<"u"&&typeof eo.yParity>"u"?{v:numberToHex(eo.v)}:{}}))}function serializeStateMapping(Xr){if(!(!Xr||Xr.length===0))return Xr.reduce((eo,{slot:to,value:ro})=>{if(to.length!==66)throw new InvalidBytesLengthError({size:to.length,targetSize:66,type:"hex"});if(ro.length!==66)throw new InvalidBytesLengthError({size:ro.length,targetSize:66,type:"hex"});return eo[to]=ro,eo},{})}function serializeAccountStateOverride(Xr){const{balance:eo,nonce:to,state:ro,stateDiff:no,code:io}=Xr,oo={};if(io!==void 0&&(oo.code=io),eo!==void 0&&(oo.balance=numberToHex(eo)),to!==void 0&&(oo.nonce=numberToHex(to)),ro!==void 0&&(oo.state=serializeStateMapping(ro)),no!==void 0){if(oo.state)throw new StateAssignmentConflictError;oo.stateDiff=serializeStateMapping(no)}return oo}function serializeStateOverride(Xr){if(!Xr)return;const eo={};for(const{address:to,...ro}of Xr){if(!isAddress(to,{strict:!1}))throw new InvalidAddressError({address:to});if(eo[to])throw new AccountStateConflictError({address:to});eo[to]=serializeAccountStateOverride(ro)}return eo}const maxUint16=2n**16n-1n,maxUint256=2n**256n-1n;function assertRequest(Xr){const{account:eo,gasPrice:to,maxFeePerGas:ro,maxPriorityFeePerGas:no,to:io}=Xr,oo=eo?parseAccount(eo):void 0;if(oo&&!isAddress(oo.address))throw new InvalidAddressError({address:oo.address});if(io&&!isAddress(io))throw new InvalidAddressError({address:io});if(typeof to<"u"&&(typeof ro<"u"||typeof no<"u"))throw new FeeConflictError;if(ro&&ro>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:ro});if(no&&ro&&no>ro)throw new TipAboveFeeCapError({maxFeePerGas:ro,maxPriorityFeePerGas:no})}class BaseFeeScalarError extends BaseError{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Eip1559FeesNotSupportedError extends BaseError{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class MaxFeePerGasTooLowError extends BaseError{constructor({maxPriorityFeePerGas:eo}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(eo)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class BlockNotFoundError extends BaseError{constructor({blockHash:eo,blockNumber:to}){let ro="Block";eo&&(ro=`Block at hash "${eo}"`),to&&(ro=`Block at number "${to}"`),super(`${ro} could not be found.`,{name:"BlockNotFoundError"})}}const transactionType={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function formatTransaction(Xr){const eo={...Xr,blockHash:Xr.blockHash?Xr.blockHash:null,blockNumber:Xr.blockNumber?BigInt(Xr.blockNumber):null,chainId:Xr.chainId?hexToNumber$2(Xr.chainId):void 0,gas:Xr.gas?BigInt(Xr.gas):void 0,gasPrice:Xr.gasPrice?BigInt(Xr.gasPrice):void 0,maxFeePerBlobGas:Xr.maxFeePerBlobGas?BigInt(Xr.maxFeePerBlobGas):void 0,maxFeePerGas:Xr.maxFeePerGas?BigInt(Xr.maxFeePerGas):void 0,maxPriorityFeePerGas:Xr.maxPriorityFeePerGas?BigInt(Xr.maxPriorityFeePerGas):void 0,nonce:Xr.nonce?hexToNumber$2(Xr.nonce):void 0,to:Xr.to?Xr.to:null,transactionIndex:Xr.transactionIndex?Number(Xr.transactionIndex):null,type:Xr.type?transactionType[Xr.type]:void 0,typeHex:Xr.type?Xr.type:void 0,value:Xr.value?BigInt(Xr.value):void 0,v:Xr.v?BigInt(Xr.v):void 0};return Xr.authorizationList&&(eo.authorizationList=formatAuthorizationList(Xr.authorizationList)),eo.yParity=(()=>{if(Xr.yParity)return Number(Xr.yParity);if(typeof eo.v=="bigint"){if(eo.v===0n||eo.v===27n)return 0;if(eo.v===1n||eo.v===28n)return 1;if(eo.v>=35n)return eo.v%2n===0n?1:0}})(),eo.type==="legacy"&&(delete eo.accessList,delete eo.maxFeePerBlobGas,delete eo.maxFeePerGas,delete eo.maxPriorityFeePerGas,delete eo.yParity),eo.type==="eip2930"&&(delete eo.maxFeePerBlobGas,delete eo.maxFeePerGas,delete eo.maxPriorityFeePerGas),eo.type==="eip1559"&&delete eo.maxFeePerBlobGas,eo}const defineTransaction=defineFormatter("transaction",formatTransaction);function formatAuthorizationList(Xr){return Xr.map(eo=>({contractAddress:eo.address,chainId:Number(eo.chainId),nonce:Number(eo.nonce),r:eo.r,s:eo.s,yParity:Number(eo.yParity)}))}function formatBlock(Xr){var to;const eo=(to=Xr.transactions)==null?void 0:to.map(ro=>typeof ro=="string"?ro:formatTransaction(ro));return{...Xr,baseFeePerGas:Xr.baseFeePerGas?BigInt(Xr.baseFeePerGas):null,blobGasUsed:Xr.blobGasUsed?BigInt(Xr.blobGasUsed):void 0,difficulty:Xr.difficulty?BigInt(Xr.difficulty):void 0,excessBlobGas:Xr.excessBlobGas?BigInt(Xr.excessBlobGas):void 0,gasLimit:Xr.gasLimit?BigInt(Xr.gasLimit):void 0,gasUsed:Xr.gasUsed?BigInt(Xr.gasUsed):void 0,hash:Xr.hash?Xr.hash:null,logsBloom:Xr.logsBloom?Xr.logsBloom:null,nonce:Xr.nonce?Xr.nonce:null,number:Xr.number?BigInt(Xr.number):null,size:Xr.size?BigInt(Xr.size):void 0,timestamp:Xr.timestamp?BigInt(Xr.timestamp):void 0,transactions:eo,totalDifficulty:Xr.totalDifficulty?BigInt(Xr.totalDifficulty):null}}const defineBlock=defineFormatter("block",formatBlock);async function getBlock$1(Xr,{blockHash:eo,blockNumber:to,blockTag:ro,includeTransactions:no}={}){var lo,fo,ho;const io=ro??"latest",oo=no??!1,ao=to!==void 0?numberToHex(to):void 0;let so=null;if(eo?so=await Xr.request({method:"eth_getBlockByHash",params:[eo,oo]},{dedupe:!0}):so=await Xr.request({method:"eth_getBlockByNumber",params:[ao||io,oo]},{dedupe:!!ao}),!so)throw new BlockNotFoundError({blockHash:eo,blockNumber:to});return(((ho=(fo=(lo=Xr.chain)==null?void 0:lo.formatters)==null?void 0:fo.block)==null?void 0:ho.format)||formatBlock)(so)}async function getGasPrice(Xr){const eo=await Xr.request({method:"eth_gasPrice"});return BigInt(eo)}async function estimateMaxPriorityFeePerGas(Xr,eo){return internal_estimateMaxPriorityFeePerGas(Xr,eo)}async function internal_estimateMaxPriorityFeePerGas(Xr,eo){var io,oo;const{block:to,chain:ro=Xr.chain,request:no}=eo||{};try{const ao=((io=ro==null?void 0:ro.fees)==null?void 0:io.maxPriorityFeePerGas)??((oo=ro==null?void 0:ro.fees)==null?void 0:oo.defaultPriorityFee);if(typeof ao=="function"){const co=to||await getAction(Xr,getBlock$1,"getBlock")({}),lo=await ao({block:co,client:Xr,request:no});if(lo===null)throw new Error;return lo}if(typeof ao<"u")return ao;const so=await Xr.request({method:"eth_maxPriorityFeePerGas"});return hexToBigInt(so)}catch{const[ao,so]=await Promise.all([to?Promise.resolve(to):getAction(Xr,getBlock$1,"getBlock")({}),getAction(Xr,getGasPrice,"getGasPrice")({})]);if(typeof ao.baseFeePerGas!="bigint")throw new Eip1559FeesNotSupportedError;const co=so-ao.baseFeePerGas;return co<0n?0n:co}}async function estimateFeesPerGas$1(Xr,eo){return internal_estimateFeesPerGas(Xr,eo)}async function internal_estimateFeesPerGas(Xr,eo){var ho,go;const{block:to,chain:ro=Xr.chain,request:no,type:io="eip1559"}=eo||{},oo=await(async()=>{var yo,vo;return typeof((yo=ro==null?void 0:ro.fees)==null?void 0:yo.baseFeeMultiplier)=="function"?ro.fees.baseFeeMultiplier({block:to,client:Xr,request:no}):((vo=ro==null?void 0:ro.fees)==null?void 0:vo.baseFeeMultiplier)??1.2})();if(oo<1)throw new BaseFeeScalarError;const so=10**(((ho=oo.toString().split(".")[1])==null?void 0:ho.length)??0),co=yo=>yo*BigInt(Math.ceil(oo*so))/BigInt(so),lo=to||await getAction(Xr,getBlock$1,"getBlock")({});if(typeof((go=ro==null?void 0:ro.fees)==null?void 0:go.estimateFeesPerGas)=="function"){const yo=await ro.fees.estimateFeesPerGas({block:to,client:Xr,multiply:co,request:no,type:io});if(yo!==null)return yo}if(io==="eip1559"){if(typeof lo.baseFeePerGas!="bigint")throw new Eip1559FeesNotSupportedError;const yo=typeof(no==null?void 0:no.maxPriorityFeePerGas)=="bigint"?no.maxPriorityFeePerGas:await internal_estimateMaxPriorityFeePerGas(Xr,{block:lo,chain:ro,request:no}),vo=co(lo.baseFeePerGas);return{maxFeePerGas:(no==null?void 0:no.maxFeePerGas)??vo+yo,maxPriorityFeePerGas:yo}}return{gasPrice:(no==null?void 0:no.gasPrice)??co(await getAction(Xr,getGasPrice,"getGasPrice")({}))}}async function getTransactionCount(Xr,{address:eo,blockTag:to="latest",blockNumber:ro}){const no=await Xr.request({method:"eth_getTransactionCount",params:[eo,ro?numberToHex(ro):to]},{dedupe:!!ro});return hexToNumber$2(no)}function blobsToCommitments(Xr){const{kzg:eo}=Xr,to=Xr.to??(typeof Xr.blobs[0]=="string"?"hex":"bytes"),ro=typeof Xr.blobs[0]=="string"?Xr.blobs.map(io=>hexToBytes$3(io)):Xr.blobs,no=[];for(const io of ro)no.push(Uint8Array.from(eo.blobToKzgCommitment(io)));return to==="bytes"?no:no.map(io=>bytesToHex$2(io))}function blobsToProofs(Xr){const{kzg:eo}=Xr,to=Xr.to??(typeof Xr.blobs[0]=="string"?"hex":"bytes"),ro=typeof Xr.blobs[0]=="string"?Xr.blobs.map(oo=>hexToBytes$3(oo)):Xr.blobs,no=typeof Xr.commitments[0]=="string"?Xr.commitments.map(oo=>hexToBytes$3(oo)):Xr.commitments,io=[];for(let oo=0;oobytesToHex$2(oo))}function sha256$6(Xr,eo){const to=eo||"hex",ro=sha256_1$4(isHex$4(Xr,{strict:!1})?toBytes$1(Xr):Xr);return to==="bytes"?ro:toHex$1(ro)}function commitmentToVersionedHash(Xr){const{commitment:eo,version:to=1}=Xr,ro=Xr.to??(typeof eo=="string"?"hex":"bytes"),no=sha256$6(eo,"bytes");return no.set([to],0),ro==="bytes"?no:bytesToHex$2(no)}function commitmentsToVersionedHashes(Xr){const{commitments:eo,version:to}=Xr,ro=Xr.to??(typeof eo[0]=="string"?"hex":"bytes"),no=[];for(const io of eo)no.push(commitmentToVersionedHash({commitment:io,to:ro,version:to}));return no}const blobsPerTransaction=6,bytesPerFieldElement=32,fieldElementsPerBlob=4096,bytesPerBlob=bytesPerFieldElement*fieldElementsPerBlob,maxBytesPerTransaction=bytesPerBlob*blobsPerTransaction-1-1*fieldElementsPerBlob*blobsPerTransaction,versionedHashVersionKzg=1;class BlobSizeTooLargeError extends BaseError{constructor({maxSize:eo,size:to}){super("Blob size is too large.",{metaMessages:[`Max: ${eo} bytes`,`Given: ${to} bytes`],name:"BlobSizeTooLargeError"})}}class EmptyBlobError extends BaseError{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class InvalidVersionedHashSizeError extends BaseError{constructor({hash:eo,size:to}){super(`Versioned hash "${eo}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${to}`],name:"InvalidVersionedHashSizeError"})}}class InvalidVersionedHashVersionError extends BaseError{constructor({hash:eo,version:to}){super(`Versioned hash "${eo}" version is invalid.`,{metaMessages:[`Expected: ${versionedHashVersionKzg}`,`Received: ${to}`],name:"InvalidVersionedHashVersionError"})}}function toBlobs(Xr){const eo=Xr.to??(typeof Xr.data=="string"?"hex":"bytes"),to=typeof Xr.data=="string"?hexToBytes$3(Xr.data):Xr.data,ro=size$1(to);if(!ro)throw new EmptyBlobError;if(ro>maxBytesPerTransaction)throw new BlobSizeTooLargeError({maxSize:maxBytesPerTransaction,size:ro});const no=[];let io=!0,oo=0;for(;io;){const ao=createCursor(new Uint8Array(bytesPerBlob));let so=0;for(;soao.bytes):no.map(ao=>bytesToHex$2(ao.bytes))}function toBlobSidecars(Xr){const{data:eo,kzg:to,to:ro}=Xr,no=Xr.blobs??toBlobs({data:eo,to:ro}),io=Xr.commitments??blobsToCommitments({blobs:no,kzg:to,to:ro}),oo=Xr.proofs??blobsToProofs({blobs:no,commitments:io,kzg:to,to:ro}),ao=[];for(let so=0;so"u"&&fo)if(so){const Eo=await wo();ho.nonce=await so.consume({address:fo.address,chainId:Eo,client:Xr})}else ho.nonce=await getAction(Xr,getTransactionCount,"getTransactionCount")({address:fo.address,blockTag:"pending"});if((co.includes("fees")||co.includes("type"))&&typeof lo>"u")try{ho.type=getTransactionType(ho)}catch{const Eo=await yo();ho.type=typeof(Eo==null?void 0:Eo.baseFeePerGas)=="bigint"?"eip1559":"legacy"}if(co.includes("fees"))if(ho.type!=="legacy"&&ho.type!=="eip2930"){if(typeof ho.maxFeePerGas>"u"||typeof ho.maxPriorityFeePerGas>"u"){const Eo=await yo(),{maxFeePerGas:ko,maxPriorityFeePerGas:Ao}=await internal_estimateFeesPerGas(Xr,{block:Eo,chain:no,request:ho});if(typeof eo.maxPriorityFeePerGas>"u"&&eo.maxFeePerGas&&eo.maxFeePerGas"u"&&(ho.gas=await getAction(Xr,estimateGas$1,"estimateGas")({...ho,account:fo&&{address:fo.address,type:"json-rpc"}})),assertRequest(ho),delete ho.parameters,ho}async function getBalance(Xr,{address:eo,blockNumber:to,blockTag:ro="latest"}){const no=to?numberToHex(to):void 0,io=await Xr.request({method:"eth_getBalance",params:[eo,no||ro]});return BigInt(io)}async function estimateGas$1(Xr,eo){var no,io,oo;const{account:to=Xr.account}=eo,ro=to?parseAccount(to):void 0;try{let uo=function(bo){const{block:_o,request:$o,rpcStateOverride:Co}=bo;return Xr.request({method:"eth_estimateGas",params:Co?[$o,_o??"latest",Co]:_o?[$o,_o]:[$o]})};const{accessList:ao,authorizationList:so,blobs:co,blobVersionedHashes:lo,blockNumber:fo,blockTag:ho,data:go,gas:yo,gasPrice:vo,maxFeePerBlobGas:wo,maxFeePerGas:Eo,maxPriorityFeePerGas:ko,nonce:Ao,value:Po,stateOverride:jo,...Mo}=await prepareTransactionRequest(Xr,{...eo,parameters:(ro==null?void 0:ro.type)==="local"?void 0:["blobVersionedHashes"]}),Do=(fo?numberToHex(fo):void 0)||ho,Fo=serializeStateOverride(jo),Xo=await(async()=>{if(Mo.to)return Mo.to;if(so&&so.length>0)return await recoverAuthorizationAddress({authorization:so[0]}).catch(()=>{throw new BaseError("`to` is required. Could not infer from `authorizationList`")})})();assertRequest(eo);const Lo=(oo=(io=(no=Xr.chain)==null?void 0:no.formatters)==null?void 0:io.transactionRequest)==null?void 0:oo.format,xo=(Lo||formatTransactionRequest)({...extract(Mo,{format:Lo}),from:ro==null?void 0:ro.address,accessList:ao,authorizationList:so,blobs:co,blobVersionedHashes:lo,data:go,gas:yo,gasPrice:vo,maxFeePerBlobGas:wo,maxFeePerGas:Eo,maxPriorityFeePerGas:ko,nonce:Ao,to:Xo,value:Po});let po=BigInt(await uo({block:Do,request:xo,rpcStateOverride:Fo}));if(so){const bo=await getBalance(Xr,{address:xo.from}),_o=await Promise.all(so.map(async $o=>{const{contractAddress:Co}=$o,Ro=await uo({block:Do,request:{authorizationList:void 0,data:go,from:ro==null?void 0:ro.address,to:Co,value:numberToHex(bo)},rpcStateOverride:Fo}).catch(()=>100000n);return 2n*BigInt(Ro)}));po+=_o.reduce(($o,Co)=>$o+Co,0n)}return po}catch(ao){throw getEstimateGasError(ao,{...eo,account:ro,chain:Xr.chain})}}async function estimateContractGas(Xr,eo){const{abi:to,address:ro,args:no,functionName:io,...oo}=eo,ao=encodeFunctionData({abi:to,args:no,functionName:io});try{return await getAction(Xr,estimateGas$1,"estimateGas")({data:ao,to:ro,...oo})}catch(so){const co=oo.account?parseAccount(oo.account):void 0;throw getContractError(so,{abi:to,address:ro,args:no,docsPath:"/docs/contract/estimateContractGas",functionName:io,sender:co==null?void 0:co.address})}}function isAddressEqual(Xr,eo){if(!isAddress(Xr,{strict:!1}))throw new InvalidAddressError({address:Xr});if(!isAddress(eo,{strict:!1}))throw new InvalidAddressError({address:eo});return Xr.toLowerCase()===eo.toLowerCase()}const docsPath$2="/docs/contract/decodeEventLog";function decodeEventLog(Xr){const{abi:eo,data:to,strict:ro,topics:no}=Xr,io=ro??!0,[oo,...ao]=no;if(!oo)throw new AbiEventSignatureEmptyTopicsError({docsPath:docsPath$2});const so=eo.length===1?eo[0]:eo.find(vo=>vo.type==="event"&&oo===toEventSelector(formatAbiItem(vo)));if(!(so&&"name"in so)||so.type!=="event")throw new AbiEventSignatureNotFoundError(oo,{docsPath:docsPath$2});const{name:co,inputs:lo}=so,fo=lo==null?void 0:lo.some(vo=>!("name"in vo&&vo.name));let ho=fo?[]:{};const go=lo.filter(vo=>"indexed"in vo&&vo.indexed);for(let vo=0;vo!("indexed"in vo&&vo.indexed));if(yo.length>0){if(to&&to!=="0x")try{const vo=decodeAbiParameters(yo,to);if(vo)if(fo)ho=[...ho,...vo];else for(let wo=0;wo0?ho:void 0}}function decodeTopic({param:Xr,value:eo}){return Xr.type==="string"||Xr.type==="bytes"||Xr.type==="tuple"||Xr.type.match(/^(.*)\[(\d+)?\]$/)?eo:(decodeAbiParameters([Xr],eo)||[])[0]}function parseEventLogs(Xr){const{abi:eo,args:to,logs:ro,strict:no=!0}=Xr,io=(()=>{if(Xr.eventName)return Array.isArray(Xr.eventName)?Xr.eventName:[Xr.eventName]})();return ro.map(oo=>{var ao;try{const so=eo.find(lo=>lo.type==="event"&&oo.topics[0]===toEventSelector(lo));if(!so)return null;const co=decodeEventLog({...oo,abi:[so],strict:no});return io&&!io.includes(co.eventName)||!includesArgs({args:co.args,inputs:so.inputs,matchArgs:to})?null:{...co,...oo}}catch(so){let co,lo;if(so instanceof AbiEventSignatureNotFoundError)return null;if(so instanceof DecodeLogDataMismatch||so instanceof DecodeLogTopicsMismatch){if(no)return null;co=so.abiItem.name,lo=(ao=so.abiItem.inputs)==null?void 0:ao.some(fo=>!("name"in fo&&fo.name))}return{...oo,args:lo?[]:{},eventName:co}}}).filter(Boolean)}function includesArgs(Xr){const{args:eo,inputs:to,matchArgs:ro}=Xr;if(!ro)return!0;if(!eo)return!1;function no(io,oo,ao){try{return io.type==="address"?isAddressEqual(oo,ao):io.type==="string"||io.type==="bytes"?keccak256(toBytes$1(oo))===ao:oo===ao}catch{return!1}}return Array.isArray(eo)&&Array.isArray(ro)?ro.every((io,oo)=>{if(io==null)return!0;const ao=to[oo];return ao?(Array.isArray(io)?io:[io]).some(co=>no(ao,co,eo[oo])):!1}):typeof eo=="object"&&!Array.isArray(eo)&&typeof ro=="object"&&!Array.isArray(ro)?Object.entries(ro).every(([io,oo])=>{if(oo==null)return!0;const ao=to.find(co=>co.name===io);return ao?(Array.isArray(oo)?oo:[oo]).some(co=>no(ao,co,eo[io])):!1}):!1}function formatLog(Xr,{args:eo,eventName:to}={}){return{...Xr,blockHash:Xr.blockHash?Xr.blockHash:null,blockNumber:Xr.blockNumber?BigInt(Xr.blockNumber):null,logIndex:Xr.logIndex?Number(Xr.logIndex):null,transactionHash:Xr.transactionHash?Xr.transactionHash:null,transactionIndex:Xr.transactionIndex?Number(Xr.transactionIndex):null,...to?{args:eo,eventName:to}:{}}}async function getLogs(Xr,{address:eo,blockHash:to,fromBlock:ro,toBlock:no,event:io,events:oo,args:ao,strict:so}={}){const co=so??!1,lo=oo??(io?[io]:void 0);let fo=[];lo&&(fo=[lo.flatMap(vo=>encodeEventTopics({abi:[vo],eventName:vo.name,args:oo?void 0:ao}))],io&&(fo=fo[0]));let ho;to?ho=await Xr.request({method:"eth_getLogs",params:[{address:eo,topics:fo,blockHash:to}]}):ho=await Xr.request({method:"eth_getLogs",params:[{address:eo,topics:fo,fromBlock:typeof ro=="bigint"?numberToHex(ro):ro,toBlock:typeof no=="bigint"?numberToHex(no):no}]});const go=ho.map(yo=>formatLog(yo));return lo?parseEventLogs({abi:lo,args:ao,logs:go,strict:co}):go}async function getContractEvents(Xr,eo){const{abi:to,address:ro,args:no,blockHash:io,eventName:oo,fromBlock:ao,toBlock:so,strict:co}=eo,lo=oo?getAbiItem({abi:to,name:oo}):void 0,fo=lo?void 0:to.filter(ho=>ho.type==="event");return getAction(Xr,getLogs,"getLogs")({address:ro,args:no,blockHash:io,event:lo,events:fo,fromBlock:ao,toBlock:so,strict:co})}const docsPath$1="/docs/contract/decodeFunctionResult";function decodeFunctionResult(Xr){const{abi:eo,args:to,functionName:ro,data:no}=Xr;let io=eo[0];if(ro){const ao=getAbiItem({abi:eo,args:to,name:ro});if(!ao)throw new AbiFunctionNotFoundError(ro,{docsPath:docsPath$1});io=ao}if(io.type!=="function")throw new AbiFunctionNotFoundError(void 0,{docsPath:docsPath$1});if(!io.outputs)throw new AbiFunctionOutputsNotFoundError(io.name,{docsPath:docsPath$1});const oo=decodeAbiParameters(io.outputs,no);if(oo&&oo.length>1)return oo;if(oo&&oo.length===1)return oo[0]}const multicall3Abi=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"}],universalResolverErrors=[{inputs:[],name:"ResolverNotFound",type:"error"},{inputs:[],name:"ResolverWildcardNotSupported",type:"error"},{inputs:[],name:"ResolverNotContract",type:"error"},{inputs:[{name:"returnData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{components:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"errors",type:"tuple[]"}],name:"HttpError",type:"error"}],universalResolverResolveAbi=[...universalResolverErrors,{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]},{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],universalResolverReverseAbi=[...universalResolverErrors,{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]},{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]}],textResolverAbi=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],addressResolverAbi=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],universalSignatureValidatorAbi=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],aggregate3Signature="0x82ad56cb",deploylessCallViaBytecodeBytecode="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",deploylessCallViaFactoryBytecode="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",universalSignatureValidatorByteCode="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class ChainDoesNotSupportContract extends BaseError{constructor({blockNumber:eo,chain:to,contract:ro}){super(`Chain "${to.name}" does not support contract "${ro.name}".`,{metaMessages:["This could be due to any of the following:",...eo&&ro.blockCreated&&ro.blockCreated>eo?[`- The contract "${ro.name}" was not deployed until block ${ro.blockCreated} (current block ${eo}).`]:[`- The chain does not have the contract "${ro.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class ChainMismatchError extends BaseError{constructor({chain:eo,currentChainId:to}){super(`The current chain of the wallet (id: ${to}) does not match the target chain for the transaction (id: ${eo.id} – ${eo.name}).`,{metaMessages:[`Current Chain ID: ${to}`,`Expected Chain ID: ${eo.id} – ${eo.name}`],name:"ChainMismatchError"})}}class ChainNotFoundError extends BaseError{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(` -`),{name:"ChainNotFoundError"})}}class ClientChainNotConfiguredError extends BaseError{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class InvalidChainIdError extends BaseError{constructor({chainId:eo}){super(typeof eo=="number"?`Chain ID "${eo}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const docsPath="/docs/contract/encodeDeployData";function encodeDeployData(Xr){const{abi:eo,args:to,bytecode:ro}=Xr;if(!to||to.length===0)return ro;const no=eo.find(oo=>"type"in oo&&oo.type==="constructor");if(!no)throw new AbiConstructorNotFoundError({docsPath});if(!("inputs"in no))throw new AbiConstructorParamsNotFoundError({docsPath});if(!no.inputs||no.inputs.length===0)throw new AbiConstructorParamsNotFoundError({docsPath});const io=encodeAbiParameters(no.inputs,to);return concatHex([ro,io])}function getChainContractAddress({blockNumber:Xr,chain:eo,contract:to}){var no;const ro=(no=eo==null?void 0:eo.contracts)==null?void 0:no[to];if(!ro)throw new ChainDoesNotSupportContract({chain:eo,contract:{name:to}});if(Xr&&ro.blockCreated&&ro.blockCreated>Xr)throw new ChainDoesNotSupportContract({blockNumber:Xr,chain:eo,contract:{name:to,blockCreated:ro.blockCreated}});return ro.address}function getCallError(Xr,{docsPath:eo,...to}){const ro=(()=>{const no=getNodeError(Xr,to);return no instanceof UnknownNodeError?Xr:no})();return new CallExecutionError(ro,{docsPath:eo,...to})}function withResolvers(){let Xr=()=>{},eo=()=>{};return{promise:new Promise((ro,no)=>{Xr=ro,eo=no}),resolve:Xr,reject:eo}}const schedulerCache=new Map;function createBatchScheduler({fn:Xr,id:eo,shouldSplitBatch:to,wait:ro=0,sort:no}){const io=async()=>{const lo=so();oo();const fo=lo.map(({args:ho})=>ho);fo.length!==0&&Xr(fo).then(ho=>{no&&Array.isArray(ho)&&ho.sort(no);for(let go=0;go{for(let go=0;goschedulerCache.delete(eo),ao=()=>so().map(({args:lo})=>lo),so=()=>schedulerCache.get(eo)||[],co=lo=>schedulerCache.set(eo,[...so(),lo]);return{flush:oo,async schedule(lo){const{promise:fo,resolve:ho,reject:go}=withResolvers();return(to==null?void 0:to([...ao(),lo]))&&io(),so().length>0?(co({args:lo,resolve:ho,reject:go}),fo):(co({args:lo,resolve:ho,reject:go}),setTimeout(io,ro),fo)}}}async function call(Xr,eo){var Lo,Bo,xo,uo;const{account:to=Xr.account,batch:ro=!!((Lo=Xr.batch)!=null&&Lo.multicall),blockNumber:no,blockTag:io="latest",accessList:oo,blobs:ao,code:so,data:co,factory:lo,factoryData:fo,gas:ho,gasPrice:go,maxFeePerBlobGas:yo,maxFeePerGas:vo,maxPriorityFeePerGas:wo,nonce:Eo,to:ko,value:Ao,stateOverride:Po,...jo}=eo,Mo=to?parseAccount(to):void 0;if(so&&(lo||fo))throw new BaseError("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(so&&ko)throw new BaseError("Cannot provide both `code` & `to` as parameters.");const No=so&&co,Do=lo&&fo&&ko&&co,Fo=No||Do,Xo=No?toDeploylessCallViaBytecodeData({code:so,data:co}):Do?toDeploylessCallViaFactoryData({data:co,factory:lo,factoryData:fo,to:ko}):co;try{assertRequest(eo);const bo=(no?numberToHex(no):void 0)||io,_o=serializeStateOverride(Po),$o=(uo=(xo=(Bo=Xr.chain)==null?void 0:Bo.formatters)==null?void 0:xo.transactionRequest)==null?void 0:uo.format,Ro=($o||formatTransactionRequest)({...extract(jo,{format:$o}),from:Mo==null?void 0:Mo.address,accessList:oo,blobs:ao,data:Xo,gas:ho,gasPrice:go,maxFeePerBlobGas:yo,maxFeePerGas:vo,maxPriorityFeePerGas:wo,nonce:Eo,to:Fo?void 0:ko,value:Ao});if(ro&&shouldPerformMulticall({request:Ro})&&!_o)try{return await scheduleMulticall(Xr,{...Ro,blockNumber:no,blockTag:io})}catch(mo){if(!(mo instanceof ClientChainNotConfiguredError)&&!(mo instanceof ChainDoesNotSupportContract))throw mo}const So=await Xr.request({method:"eth_call",params:_o?[Ro,bo,_o]:[Ro,bo]});return So==="0x"?{data:void 0}:{data:So}}catch(po){const bo=getRevertErrorData(po),{offchainLookup:_o,offchainLookupSignature:$o}=await __vitePreload(async()=>{const{offchainLookup:Co,offchainLookupSignature:Ro}=await import("./ccip-CiOu7uMi.js");return{offchainLookup:Co,offchainLookupSignature:Ro}},[]);if(Xr.ccipRead!==!1&&(bo==null?void 0:bo.slice(0,10))===$o&&ko)return{data:await _o(Xr,{data:bo,to:ko})};throw Fo&&(bo==null?void 0:bo.slice(0,10))==="0x101bb98d"?new CounterfactualDeploymentFailedError({factory:lo}):getCallError(po,{...eo,account:Mo,chain:Xr.chain})}}function shouldPerformMulticall({request:Xr}){const{data:eo,to,...ro}=Xr;return!(!eo||eo.startsWith(aggregate3Signature)||!to||Object.values(ro).filter(no=>typeof no<"u").length>0)}async function scheduleMulticall(Xr,eo){var vo;const{batchSize:to=1024,wait:ro=0}=typeof((vo=Xr.batch)==null?void 0:vo.multicall)=="object"?Xr.batch.multicall:{},{blockNumber:no,blockTag:io="latest",data:oo,multicallAddress:ao,to:so}=eo;let co=ao;if(!co){if(!Xr.chain)throw new ClientChainNotConfiguredError;co=getChainContractAddress({blockNumber:no,chain:Xr.chain,contract:"multicall3"})}const fo=(no?numberToHex(no):void 0)||io,{schedule:ho}=createBatchScheduler({id:`${Xr.uid}.${fo}`,wait:ro,shouldSplitBatch(wo){return wo.reduce((ko,{data:Ao})=>ko+(Ao.length-2),0)>to*2},fn:async wo=>{const Eo=wo.map(Po=>({allowFailure:!0,callData:Po.data,target:Po.to})),ko=encodeFunctionData({abi:multicall3Abi,args:[Eo],functionName:"aggregate3"}),Ao=await Xr.request({method:"eth_call",params:[{data:ko,to:co},fo]});return decodeFunctionResult({abi:multicall3Abi,args:[Eo],functionName:"aggregate3",data:Ao||"0x"})}}),[{returnData:go,success:yo}]=await ho({data:oo,to:so});if(!yo)throw new RawContractError({data:go});return go==="0x"?{data:void 0}:{data:go}}function toDeploylessCallViaBytecodeData(Xr){const{code:eo,data:to}=Xr;return encodeDeployData({abi:parseAbi(["constructor(bytes, bytes)"]),bytecode:deploylessCallViaBytecodeBytecode,args:[eo,to]})}function toDeploylessCallViaFactoryData(Xr){const{data:eo,factory:to,factoryData:ro,to:no}=Xr;return encodeDeployData({abi:parseAbi(["constructor(address, bytes, address, bytes)"]),bytecode:deploylessCallViaFactoryBytecode,args:[no,eo,to,ro]})}function getRevertErrorData(Xr){var to;if(!(Xr instanceof BaseError))return;const eo=Xr.walk();return typeof(eo==null?void 0:eo.data)=="object"?(to=eo.data)==null?void 0:to.data:eo.data}async function readContract(Xr,eo){const{abi:to,address:ro,args:no,functionName:io,...oo}=eo,ao=encodeFunctionData({abi:to,args:no,functionName:io});try{const{data:so}=await getAction(Xr,call,"call")({...oo,data:ao,to:ro});return decodeFunctionResult({abi:to,args:no,functionName:io,data:so||"0x"})}catch(so){throw getContractError(so,{abi:to,address:ro,args:no,docsPath:"/docs/contract/readContract",functionName:io})}}async function simulateContract(Xr,eo){const{abi:to,address:ro,args:no,dataSuffix:io,functionName:oo,...ao}=eo,so=ao.account?parseAccount(ao.account):Xr.account,co=encodeFunctionData({abi:to,args:no,functionName:oo});try{const{data:lo}=await getAction(Xr,call,"call")({batch:!1,data:`${co}${io?io.replace("0x",""):""}`,to:ro,...ao,account:so}),fo=decodeFunctionResult({abi:to,args:no,functionName:oo,data:lo||"0x"}),ho=to.filter(go=>"name"in go&&go.name===eo.functionName);return{result:fo,request:{abi:ho,address:ro,args:no,dataSuffix:io,functionName:oo,...ao,account:so}}}catch(lo){throw getContractError(lo,{abi:to,address:ro,args:no,docsPath:"/docs/contract/simulateContract",functionName:oo,sender:so==null?void 0:so.address})}}const listenersCache=new Map,cleanupCache=new Map;let callbackCount=0;function observe(Xr,eo,to){const ro=++callbackCount,no=()=>listenersCache.get(Xr)||[],io=()=>{const lo=no();listenersCache.set(Xr,lo.filter(fo=>fo.id!==ro))},oo=()=>{const lo=cleanupCache.get(Xr);no().length===1&&lo&&lo(),io()},ao=no();if(listenersCache.set(Xr,[...ao,{id:ro,fns:eo}]),ao&&ao.length>0)return oo;const so={};for(const lo in eo)so[lo]=(...fo)=>{var go,yo;const ho=no();if(ho.length!==0)for(const vo of ho)(yo=(go=vo.fns)[lo])==null||yo.call(go,...fo)};const co=to(so);return typeof co=="function"&&cleanupCache.set(Xr,co),oo}async function wait$1(Xr){return new Promise(eo=>setTimeout(eo,Xr))}function poll$1(Xr,{emitOnBegin:eo,initialWaitTime:to,interval:ro}){let no=!0;const io=()=>no=!1;return(async()=>{let ao;eo&&(ao=await Xr({unpoll:io}));const so=await(to==null?void 0:to(ao))??ro;await wait$1(so);const co=async()=>{no&&(await Xr({unpoll:io}),await wait$1(ro),co())};co()})(),io}const promiseCache$1=new Map,responseCache=new Map;function getCache$1(Xr){const eo=(no,io)=>({clear:()=>io.delete(no),get:()=>io.get(no),set:oo=>io.set(no,oo)}),to=eo(Xr,promiseCache$1),ro=eo(Xr,responseCache);return{clear:()=>{to.clear(),ro.clear()},promise:to,response:ro}}async function withCache(Xr,{cacheKey:eo,cacheTime:to=Number.POSITIVE_INFINITY}){const ro=getCache$1(eo),no=ro.response.get();if(no&&to>0&&new Date().getTime()-no.created.getTime()`blockNumber.${Xr}`;async function getBlockNumber(Xr,{cacheTime:eo=Xr.cacheTime}={}){const to=await withCache(()=>Xr.request({method:"eth_blockNumber"}),{cacheKey:cacheKey(Xr.uid),cacheTime:eo});return BigInt(to)}async function getFilterChanges(Xr,{filter:eo}){const to="strict"in eo&&eo.strict,ro=await eo.request({method:"eth_getFilterChanges",params:[eo.id]});if(typeof ro[0]=="string")return ro;const no=ro.map(io=>formatLog(io));return!("abi"in eo)||!eo.abi?no:parseEventLogs({abi:eo.abi,logs:no,strict:to})}async function uninstallFilter(Xr,{filter:eo}){return eo.request({method:"eth_uninstallFilter",params:[eo.id]})}function watchContractEvent(Xr,eo){const{abi:to,address:ro,args:no,batch:io=!0,eventName:oo,fromBlock:ao,onError:so,onLogs:co,poll:lo,pollingInterval:fo=Xr.pollingInterval,strict:ho}=eo;return(typeof lo<"u"?lo:typeof ao=="bigint"?!0:!(Xr.transport.type==="webSocket"||Xr.transport.type==="fallback"&&Xr.transport.transports[0].config.type==="webSocket"))?(()=>{const wo=ho??!1,Eo=stringify$4(["watchContractEvent",ro,no,io,Xr.uid,oo,fo,wo,ao]);return observe(Eo,{onLogs:co,onError:so},ko=>{let Ao;ao!==void 0&&(Ao=ao-1n);let Po,jo=!1;const Mo=poll$1(async()=>{var No;if(!jo){try{Po=await getAction(Xr,createContractEventFilter,"createContractEventFilter")({abi:to,address:ro,args:no,eventName:oo,strict:wo,fromBlock:ao})}catch{}jo=!0;return}try{let Do;if(Po)Do=await getAction(Xr,getFilterChanges,"getFilterChanges")({filter:Po});else{const Fo=await getAction(Xr,getBlockNumber,"getBlockNumber")({});Ao&&Ao{Po&&await getAction(Xr,uninstallFilter,"uninstallFilter")({filter:Po}),Mo()}})})():(()=>{const wo=ho??!1,Eo=stringify$4(["watchContractEvent",ro,no,io,Xr.uid,oo,fo,wo]);let ko=!0,Ao=()=>ko=!1;return observe(Eo,{onLogs:co,onError:so},Po=>((async()=>{try{const jo=(()=>{if(Xr.transport.type==="fallback"){const Do=Xr.transport.transports.find(Fo=>Fo.config.type==="webSocket");return Do?Do.value:Xr.transport}return Xr.transport})(),Mo=oo?encodeEventTopics({abi:to,eventName:oo,args:no}):[],{unsubscribe:No}=await jo.subscribe({params:["logs",{address:ro,topics:Mo}],onData(Do){var Xo;if(!ko)return;const Fo=Do.result;try{const{eventName:Lo,args:Bo}=decodeEventLog({abi:to,data:Fo.data,topics:Fo.topics,strict:ho}),xo=formatLog(Fo,{args:Bo,eventName:Lo});Po.onLogs([xo])}catch(Lo){let Bo,xo;if(Lo instanceof DecodeLogDataMismatch||Lo instanceof DecodeLogTopicsMismatch){if(ho)return;Bo=Lo.abiItem.name,xo=(Xo=Lo.abiItem.inputs)==null?void 0:Xo.some(po=>!("name"in po&&po.name))}const uo=formatLog(Fo,{args:xo?[]:{},eventName:Bo});Po.onLogs([uo])}},onError(Do){var Fo;(Fo=Po.onError)==null||Fo.call(Po,Do)}});Ao=No,ko||Ao()}catch(jo){so==null||so(jo)}})(),()=>Ao()))})()}class AccountNotFoundError extends BaseError{constructor({docsPath:eo}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` +`),{name:"ChainNotFoundError"})}}class ClientChainNotConfiguredError extends BaseError{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class InvalidChainIdError extends BaseError{constructor({chainId:eo}){super(typeof eo=="number"?`Chain ID "${eo}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const docsPath="/docs/contract/encodeDeployData";function encodeDeployData(Xr){const{abi:eo,args:to,bytecode:ro}=Xr;if(!to||to.length===0)return ro;const no=eo.find(oo=>"type"in oo&&oo.type==="constructor");if(!no)throw new AbiConstructorNotFoundError({docsPath});if(!("inputs"in no))throw new AbiConstructorParamsNotFoundError({docsPath});if(!no.inputs||no.inputs.length===0)throw new AbiConstructorParamsNotFoundError({docsPath});const io=encodeAbiParameters(no.inputs,to);return concatHex([ro,io])}function getChainContractAddress({blockNumber:Xr,chain:eo,contract:to}){var no;const ro=(no=eo==null?void 0:eo.contracts)==null?void 0:no[to];if(!ro)throw new ChainDoesNotSupportContract({chain:eo,contract:{name:to}});if(Xr&&ro.blockCreated&&ro.blockCreated>Xr)throw new ChainDoesNotSupportContract({blockNumber:Xr,chain:eo,contract:{name:to,blockCreated:ro.blockCreated}});return ro.address}function getCallError(Xr,{docsPath:eo,...to}){const ro=(()=>{const no=getNodeError(Xr,to);return no instanceof UnknownNodeError?Xr:no})();return new CallExecutionError(ro,{docsPath:eo,...to})}function withResolvers(){let Xr=()=>{},eo=()=>{};return{promise:new Promise((ro,no)=>{Xr=ro,eo=no}),resolve:Xr,reject:eo}}const schedulerCache=new Map;function createBatchScheduler({fn:Xr,id:eo,shouldSplitBatch:to,wait:ro=0,sort:no}){const io=async()=>{const lo=so();oo();const fo=lo.map(({args:ho})=>ho);fo.length!==0&&Xr(fo).then(ho=>{no&&Array.isArray(ho)&&ho.sort(no);for(let go=0;go{for(let go=0;goschedulerCache.delete(eo),ao=()=>so().map(({args:lo})=>lo),so=()=>schedulerCache.get(eo)||[],co=lo=>schedulerCache.set(eo,[...so(),lo]);return{flush:oo,async schedule(lo){const{promise:fo,resolve:ho,reject:go}=withResolvers();return(to==null?void 0:to([...ao(),lo]))&&io(),so().length>0?(co({args:lo,resolve:ho,reject:go}),fo):(co({args:lo,resolve:ho,reject:go}),setTimeout(io,ro),fo)}}}async function call(Xr,eo){var Lo,Bo,xo,uo;const{account:to=Xr.account,batch:ro=!!((Lo=Xr.batch)!=null&&Lo.multicall),blockNumber:no,blockTag:io="latest",accessList:oo,blobs:ao,code:so,data:co,factory:lo,factoryData:fo,gas:ho,gasPrice:go,maxFeePerBlobGas:yo,maxFeePerGas:vo,maxPriorityFeePerGas:wo,nonce:Eo,to:ko,value:Ao,stateOverride:Po,...jo}=eo,Mo=to?parseAccount(to):void 0;if(so&&(lo||fo))throw new BaseError("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(so&&ko)throw new BaseError("Cannot provide both `code` & `to` as parameters.");const No=so&&co,Do=lo&&fo&&ko&&co,Fo=No||Do,Xo=No?toDeploylessCallViaBytecodeData({code:so,data:co}):Do?toDeploylessCallViaFactoryData({data:co,factory:lo,factoryData:fo,to:ko}):co;try{assertRequest(eo);const bo=(no?numberToHex(no):void 0)||io,_o=serializeStateOverride(Po),$o=(uo=(xo=(Bo=Xr.chain)==null?void 0:Bo.formatters)==null?void 0:xo.transactionRequest)==null?void 0:uo.format,Ro=($o||formatTransactionRequest)({...extract(jo,{format:$o}),from:Mo==null?void 0:Mo.address,accessList:oo,blobs:ao,data:Xo,gas:ho,gasPrice:go,maxFeePerBlobGas:yo,maxFeePerGas:vo,maxPriorityFeePerGas:wo,nonce:Eo,to:Fo?void 0:ko,value:Ao});if(ro&&shouldPerformMulticall({request:Ro})&&!_o)try{return await scheduleMulticall(Xr,{...Ro,blockNumber:no,blockTag:io})}catch(mo){if(!(mo instanceof ClientChainNotConfiguredError)&&!(mo instanceof ChainDoesNotSupportContract))throw mo}const So=await Xr.request({method:"eth_call",params:_o?[Ro,bo,_o]:[Ro,bo]});return So==="0x"?{data:void 0}:{data:So}}catch(po){const bo=getRevertErrorData(po),{offchainLookup:_o,offchainLookupSignature:$o}=await __vitePreload(async()=>{const{offchainLookup:Co,offchainLookupSignature:Ro}=await import("./ccip-BBxDHENs.js");return{offchainLookup:Co,offchainLookupSignature:Ro}},[]);if(Xr.ccipRead!==!1&&(bo==null?void 0:bo.slice(0,10))===$o&&ko)return{data:await _o(Xr,{data:bo,to:ko})};throw Fo&&(bo==null?void 0:bo.slice(0,10))==="0x101bb98d"?new CounterfactualDeploymentFailedError({factory:lo}):getCallError(po,{...eo,account:Mo,chain:Xr.chain})}}function shouldPerformMulticall({request:Xr}){const{data:eo,to,...ro}=Xr;return!(!eo||eo.startsWith(aggregate3Signature)||!to||Object.values(ro).filter(no=>typeof no<"u").length>0)}async function scheduleMulticall(Xr,eo){var vo;const{batchSize:to=1024,wait:ro=0}=typeof((vo=Xr.batch)==null?void 0:vo.multicall)=="object"?Xr.batch.multicall:{},{blockNumber:no,blockTag:io="latest",data:oo,multicallAddress:ao,to:so}=eo;let co=ao;if(!co){if(!Xr.chain)throw new ClientChainNotConfiguredError;co=getChainContractAddress({blockNumber:no,chain:Xr.chain,contract:"multicall3"})}const fo=(no?numberToHex(no):void 0)||io,{schedule:ho}=createBatchScheduler({id:`${Xr.uid}.${fo}`,wait:ro,shouldSplitBatch(wo){return wo.reduce((ko,{data:Ao})=>ko+(Ao.length-2),0)>to*2},fn:async wo=>{const Eo=wo.map(Po=>({allowFailure:!0,callData:Po.data,target:Po.to})),ko=encodeFunctionData({abi:multicall3Abi,args:[Eo],functionName:"aggregate3"}),Ao=await Xr.request({method:"eth_call",params:[{data:ko,to:co},fo]});return decodeFunctionResult({abi:multicall3Abi,args:[Eo],functionName:"aggregate3",data:Ao||"0x"})}}),[{returnData:go,success:yo}]=await ho({data:oo,to:so});if(!yo)throw new RawContractError({data:go});return go==="0x"?{data:void 0}:{data:go}}function toDeploylessCallViaBytecodeData(Xr){const{code:eo,data:to}=Xr;return encodeDeployData({abi:parseAbi(["constructor(bytes, bytes)"]),bytecode:deploylessCallViaBytecodeBytecode,args:[eo,to]})}function toDeploylessCallViaFactoryData(Xr){const{data:eo,factory:to,factoryData:ro,to:no}=Xr;return encodeDeployData({abi:parseAbi(["constructor(address, bytes, address, bytes)"]),bytecode:deploylessCallViaFactoryBytecode,args:[no,eo,to,ro]})}function getRevertErrorData(Xr){var to;if(!(Xr instanceof BaseError))return;const eo=Xr.walk();return typeof(eo==null?void 0:eo.data)=="object"?(to=eo.data)==null?void 0:to.data:eo.data}async function readContract(Xr,eo){const{abi:to,address:ro,args:no,functionName:io,...oo}=eo,ao=encodeFunctionData({abi:to,args:no,functionName:io});try{const{data:so}=await getAction(Xr,call,"call")({...oo,data:ao,to:ro});return decodeFunctionResult({abi:to,args:no,functionName:io,data:so||"0x"})}catch(so){throw getContractError(so,{abi:to,address:ro,args:no,docsPath:"/docs/contract/readContract",functionName:io})}}async function simulateContract(Xr,eo){const{abi:to,address:ro,args:no,dataSuffix:io,functionName:oo,...ao}=eo,so=ao.account?parseAccount(ao.account):Xr.account,co=encodeFunctionData({abi:to,args:no,functionName:oo});try{const{data:lo}=await getAction(Xr,call,"call")({batch:!1,data:`${co}${io?io.replace("0x",""):""}`,to:ro,...ao,account:so}),fo=decodeFunctionResult({abi:to,args:no,functionName:oo,data:lo||"0x"}),ho=to.filter(go=>"name"in go&&go.name===eo.functionName);return{result:fo,request:{abi:ho,address:ro,args:no,dataSuffix:io,functionName:oo,...ao,account:so}}}catch(lo){throw getContractError(lo,{abi:to,address:ro,args:no,docsPath:"/docs/contract/simulateContract",functionName:oo,sender:so==null?void 0:so.address})}}const listenersCache=new Map,cleanupCache=new Map;let callbackCount=0;function observe(Xr,eo,to){const ro=++callbackCount,no=()=>listenersCache.get(Xr)||[],io=()=>{const lo=no();listenersCache.set(Xr,lo.filter(fo=>fo.id!==ro))},oo=()=>{const lo=cleanupCache.get(Xr);no().length===1&&lo&&lo(),io()},ao=no();if(listenersCache.set(Xr,[...ao,{id:ro,fns:eo}]),ao&&ao.length>0)return oo;const so={};for(const lo in eo)so[lo]=(...fo)=>{var go,yo;const ho=no();if(ho.length!==0)for(const vo of ho)(yo=(go=vo.fns)[lo])==null||yo.call(go,...fo)};const co=to(so);return typeof co=="function"&&cleanupCache.set(Xr,co),oo}async function wait$1(Xr){return new Promise(eo=>setTimeout(eo,Xr))}function poll$1(Xr,{emitOnBegin:eo,initialWaitTime:to,interval:ro}){let no=!0;const io=()=>no=!1;return(async()=>{let ao;eo&&(ao=await Xr({unpoll:io}));const so=await(to==null?void 0:to(ao))??ro;await wait$1(so);const co=async()=>{no&&(await Xr({unpoll:io}),await wait$1(ro),co())};co()})(),io}const promiseCache$1=new Map,responseCache=new Map;function getCache$1(Xr){const eo=(no,io)=>({clear:()=>io.delete(no),get:()=>io.get(no),set:oo=>io.set(no,oo)}),to=eo(Xr,promiseCache$1),ro=eo(Xr,responseCache);return{clear:()=>{to.clear(),ro.clear()},promise:to,response:ro}}async function withCache(Xr,{cacheKey:eo,cacheTime:to=Number.POSITIVE_INFINITY}){const ro=getCache$1(eo),no=ro.response.get();if(no&&to>0&&new Date().getTime()-no.created.getTime()`blockNumber.${Xr}`;async function getBlockNumber(Xr,{cacheTime:eo=Xr.cacheTime}={}){const to=await withCache(()=>Xr.request({method:"eth_blockNumber"}),{cacheKey:cacheKey(Xr.uid),cacheTime:eo});return BigInt(to)}async function getFilterChanges(Xr,{filter:eo}){const to="strict"in eo&&eo.strict,ro=await eo.request({method:"eth_getFilterChanges",params:[eo.id]});if(typeof ro[0]=="string")return ro;const no=ro.map(io=>formatLog(io));return!("abi"in eo)||!eo.abi?no:parseEventLogs({abi:eo.abi,logs:no,strict:to})}async function uninstallFilter(Xr,{filter:eo}){return eo.request({method:"eth_uninstallFilter",params:[eo.id]})}function watchContractEvent(Xr,eo){const{abi:to,address:ro,args:no,batch:io=!0,eventName:oo,fromBlock:ao,onError:so,onLogs:co,poll:lo,pollingInterval:fo=Xr.pollingInterval,strict:ho}=eo;return(typeof lo<"u"?lo:typeof ao=="bigint"?!0:!(Xr.transport.type==="webSocket"||Xr.transport.type==="fallback"&&Xr.transport.transports[0].config.type==="webSocket"))?(()=>{const wo=ho??!1,Eo=stringify$4(["watchContractEvent",ro,no,io,Xr.uid,oo,fo,wo,ao]);return observe(Eo,{onLogs:co,onError:so},ko=>{let Ao;ao!==void 0&&(Ao=ao-1n);let Po,jo=!1;const Mo=poll$1(async()=>{var No;if(!jo){try{Po=await getAction(Xr,createContractEventFilter,"createContractEventFilter")({abi:to,address:ro,args:no,eventName:oo,strict:wo,fromBlock:ao})}catch{}jo=!0;return}try{let Do;if(Po)Do=await getAction(Xr,getFilterChanges,"getFilterChanges")({filter:Po});else{const Fo=await getAction(Xr,getBlockNumber,"getBlockNumber")({});Ao&&Ao{Po&&await getAction(Xr,uninstallFilter,"uninstallFilter")({filter:Po}),Mo()}})})():(()=>{const wo=ho??!1,Eo=stringify$4(["watchContractEvent",ro,no,io,Xr.uid,oo,fo,wo]);let ko=!0,Ao=()=>ko=!1;return observe(Eo,{onLogs:co,onError:so},Po=>((async()=>{try{const jo=(()=>{if(Xr.transport.type==="fallback"){const Do=Xr.transport.transports.find(Fo=>Fo.config.type==="webSocket");return Do?Do.value:Xr.transport}return Xr.transport})(),Mo=oo?encodeEventTopics({abi:to,eventName:oo,args:no}):[],{unsubscribe:No}=await jo.subscribe({params:["logs",{address:ro,topics:Mo}],onData(Do){var Xo;if(!ko)return;const Fo=Do.result;try{const{eventName:Lo,args:Bo}=decodeEventLog({abi:to,data:Fo.data,topics:Fo.topics,strict:ho}),xo=formatLog(Fo,{args:Bo,eventName:Lo});Po.onLogs([xo])}catch(Lo){let Bo,xo;if(Lo instanceof DecodeLogDataMismatch||Lo instanceof DecodeLogTopicsMismatch){if(ho)return;Bo=Lo.abiItem.name,xo=(Xo=Lo.abiItem.inputs)==null?void 0:Xo.some(po=>!("name"in po&&po.name))}const uo=formatLog(Fo,{args:xo?[]:{},eventName:Bo});Po.onLogs([uo])}},onError(Do){var Fo;(Fo=Po.onError)==null||Fo.call(Po,Do)}});Ao=No,ko||Ao()}catch(jo){so==null||so(jo)}})(),()=>Ao()))})()}class AccountNotFoundError extends BaseError{constructor({docsPath:eo}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` `),{docsPath:eo,docsSlug:"account",name:"AccountNotFoundError"})}}class AccountTypeNotSupportedError extends BaseError{constructor({docsPath:eo,metaMessages:to,type:ro}){super(`Account type "${ro}" is not supported.`,{docsPath:eo,metaMessages:to,name:"AccountTypeNotSupportedError"})}}function assertCurrentChain({chain:Xr,currentChainId:eo}){if(!Xr)throw new ChainNotFoundError;if(eo!==Xr.id)throw new ChainMismatchError({chain:Xr,currentChainId:eo})}function getTransactionError(Xr,{docsPath:eo,...to}){const ro=(()=>{const no=getNodeError(Xr,to);return no instanceof UnknownNodeError?Xr:no})();return new TransactionExecutionError(ro,{docsPath:eo,...to})}async function sendRawTransaction(Xr,{serializedTransaction:eo}){return Xr.request({method:"eth_sendRawTransaction",params:[eo]},{retryCount:0})}const supportsWalletNamespace=new LruMap(128);async function sendTransaction$1(Xr,eo){var Eo,ko,Ao,Po;const{account:to=Xr.account,chain:ro=Xr.chain,accessList:no,authorizationList:io,blobs:oo,data:ao,gas:so,gasPrice:co,maxFeePerBlobGas:lo,maxFeePerGas:fo,maxPriorityFeePerGas:ho,nonce:go,value:yo,...vo}=eo;if(typeof to>"u")throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/sendTransaction"});const wo=to?parseAccount(to):null;try{assertRequest(eo);const jo=await(async()=>{if(eo.to)return eo.to;if(io&&io.length>0)return await recoverAuthorizationAddress({authorization:io[0]}).catch(()=>{throw new BaseError("`to` is required. Could not infer from `authorizationList`.")})})();if((wo==null?void 0:wo.type)==="json-rpc"||wo===null){let Mo;ro!==null&&(Mo=await getAction(Xr,getChainId$1,"getChainId")({}),assertCurrentChain({currentChainId:Mo,chain:ro}));const No=(Ao=(ko=(Eo=Xr.chain)==null?void 0:Eo.formatters)==null?void 0:ko.transactionRequest)==null?void 0:Ao.format,Fo=(No||formatTransactionRequest)({...extract(vo,{format:No}),accessList:no,authorizationList:io,blobs:oo,chainId:Mo,data:ao,from:wo==null?void 0:wo.address,gas:so,gasPrice:co,maxFeePerBlobGas:lo,maxFeePerGas:fo,maxPriorityFeePerGas:ho,nonce:go,to:jo,value:yo}),Xo=supportsWalletNamespace.get(Xr.uid)?"wallet_sendTransaction":"eth_sendTransaction";try{return await Xr.request({method:Xo,params:[Fo]},{retryCount:0})}catch(Lo){const Bo=Lo;if(Bo.name==="InvalidInputRpcError"||Bo.name==="InvalidParamsRpcError"||Bo.name==="MethodNotFoundRpcError"||Bo.name==="MethodNotSupportedRpcError")return await Xr.request({method:"wallet_sendTransaction",params:[Fo]},{retryCount:0}).then(xo=>(supportsWalletNamespace.set(Xr.uid,!0),xo));throw Bo}}if((wo==null?void 0:wo.type)==="local"){const Mo=await getAction(Xr,prepareTransactionRequest,"prepareTransactionRequest")({account:wo,accessList:no,authorizationList:io,blobs:oo,chain:ro,data:ao,gas:so,gasPrice:co,maxFeePerBlobGas:lo,maxFeePerGas:fo,maxPriorityFeePerGas:ho,nonce:go,nonceManager:wo.nonceManager,parameters:[...defaultParameters,"sidecars"],value:yo,...vo,to:jo}),No=(Po=ro==null?void 0:ro.serializers)==null?void 0:Po.transaction,Do=await wo.signTransaction(Mo,{serializer:No});return await getAction(Xr,sendRawTransaction,"sendRawTransaction")({serializedTransaction:Do})}throw(wo==null?void 0:wo.type)==="smart"?new AccountTypeNotSupportedError({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new AccountTypeNotSupportedError({docsPath:"/docs/actions/wallet/sendTransaction",type:wo==null?void 0:wo.type})}catch(jo){throw jo instanceof AccountTypeNotSupportedError?jo:getTransactionError(jo,{...eo,account:wo,chain:eo.chain||void 0})}}async function writeContract(Xr,eo){const{abi:to,account:ro=Xr.account,address:no,args:io,dataSuffix:oo,functionName:ao,...so}=eo;if(typeof ro>"u")throw new AccountNotFoundError({docsPath:"/docs/contract/writeContract"});const co=ro?parseAccount(ro):null,lo=encodeFunctionData({abi:to,args:io,functionName:ao});try{return await getAction(Xr,sendTransaction$1,"sendTransaction")({data:`${lo}${oo?oo.replace("0x",""):""}`,to:no,account:co,...so})}catch(fo){throw getContractError(fo,{abi:to,address:no,args:io,docsPath:"/docs/contract/writeContract",functionName:ao,sender:co==null?void 0:co.address})}}function getContract({abi:Xr,address:eo,client:to}){const ro=to,[no,io]=ro?"public"in ro&&"wallet"in ro?[ro.public,ro.wallet]:"public"in ro?[ro.public,void 0]:"wallet"in ro?[void 0,ro.wallet]:[ro,ro]:[void 0,void 0],oo=no!=null,ao=io!=null,so={};let co=!1,lo=!1,fo=!1;for(const ho of Xr)if(ho.type==="function"?ho.stateMutability==="view"||ho.stateMutability==="pure"?co=!0:lo=!0:ho.type==="event"&&(fo=!0),co&&lo&&fo)break;return oo&&(co&&(so.read=new Proxy({},{get(ho,go){return(...yo)=>{const{args:vo,options:wo}=getFunctionParameters(yo);return getAction(no,readContract,"readContract")({abi:Xr,address:eo,functionName:go,args:vo,...wo})}}})),lo&&(so.simulate=new Proxy({},{get(ho,go){return(...yo)=>{const{args:vo,options:wo}=getFunctionParameters(yo);return getAction(no,simulateContract,"simulateContract")({abi:Xr,address:eo,functionName:go,args:vo,...wo})}}})),fo&&(so.createEventFilter=new Proxy({},{get(ho,go){return(...yo)=>{const vo=Xr.find(ko=>ko.type==="event"&&ko.name===go),{args:wo,options:Eo}=getEventParameters(yo,vo);return getAction(no,createContractEventFilter,"createContractEventFilter")({abi:Xr,address:eo,eventName:go,args:wo,...Eo})}}}),so.getEvents=new Proxy({},{get(ho,go){return(...yo)=>{const vo=Xr.find(ko=>ko.type==="event"&&ko.name===go),{args:wo,options:Eo}=getEventParameters(yo,vo);return getAction(no,getContractEvents,"getContractEvents")({abi:Xr,address:eo,eventName:go,args:wo,...Eo})}}}),so.watchEvent=new Proxy({},{get(ho,go){return(...yo)=>{const vo=Xr.find(ko=>ko.type==="event"&&ko.name===go),{args:wo,options:Eo}=getEventParameters(yo,vo);return getAction(no,watchContractEvent,"watchContractEvent")({abi:Xr,address:eo,eventName:go,args:wo,...Eo})}}}))),ao&&lo&&(so.write=new Proxy({},{get(ho,go){return(...yo)=>{const{args:vo,options:wo}=getFunctionParameters(yo);return getAction(io,writeContract,"writeContract")({abi:Xr,address:eo,functionName:go,args:vo,...wo})}}})),(oo||ao)&&lo&&(so.estimateGas=new Proxy({},{get(ho,go){return(...yo)=>{const{args:vo,options:wo}=getFunctionParameters(yo);return getAction(no??io,estimateContractGas,"estimateContractGas")({abi:Xr,address:eo,functionName:go,args:vo,...wo,account:wo.account??io.account})}}})),so.address=eo,so.abi=Xr,so}function getFunctionParameters(Xr){const eo=Xr.length&&Array.isArray(Xr[0]),to=eo?Xr[0]:[],ro=(eo?Xr[1]:Xr[0])??{};return{args:to,options:ro}}function getEventParameters(Xr,eo){let to=!1;Array.isArray(Xr[0])?to=!0:Xr.length===1?to=eo.inputs.some(io=>io.indexed):Xr.length===2&&(to=!0);const ro=to?Xr[0]:void 0,no=(to?Xr[1]:Xr[0])??{};return{args:ro,options:no}}class Eip712DomainNotFoundError extends BaseError{constructor({address:eo}){super(`No EIP-712 domain found on contract "${eo}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${eo}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function getEip712Domain$1(Xr,eo){const{address:to,factory:ro,factoryData:no}=eo;try{const[io,oo,ao,so,co,lo,fo]=await getAction(Xr,readContract,"readContract")({abi:abi$2,address:to,functionName:"eip712Domain",factory:ro,factoryData:no});return{domain:{name:oo,version:ao,chainId:Number(so),verifyingContract:co,salt:lo},extensions:fo,fields:io}}catch(io){const oo=io;throw oo.name==="ContractFunctionExecutionError"&&oo.cause.name==="ContractFunctionZeroDataError"?new Eip712DomainNotFoundError({address:to}):oo}}const abi$2=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];async function addChain(Xr,{chain:eo}){const{id:to,name:ro,nativeCurrency:no,rpcUrls:io,blockExplorers:oo}=eo;await Xr.request({method:"wallet_addEthereumChain",params:[{chainId:numberToHex(to),chainName:ro,nativeCurrency:no,rpcUrls:io.default.http,blockExplorerUrls:oo?Object.values(oo).map(({url:ao})=>ao):void 0}]},{dedupe:!0,retryCount:0})}const size=256;let index$1=size,buffer$1;function uid$1(Xr=11){if(!buffer$1||index$1+Xr>size*2){buffer$1="",index$1=0;for(let eo=0;eo{const ko=Eo(wo);for(const Po in yo)delete ko[Po];const Ao={...wo,...ko};return Object.assign(Ao,{extend:vo(Ao)})}}return Object.assign(yo,{extend:vo(yo)})}const promiseCache=new LruMap(8192);function withDedupe(Xr,{enabled:eo=!0,id:to}){if(!eo||!to)return Xr();if(promiseCache.get(to))return promiseCache.get(to);const ro=Xr().finally(()=>promiseCache.delete(to));return promiseCache.set(to,ro),ro}function withRetry(Xr,{delay:eo=100,retryCount:to=2,shouldRetry:ro=()=>!0}={}){return new Promise((no,io)=>{const oo=async({count:ao=0}={})=>{const so=async({error:co})=>{const lo=typeof eo=="function"?eo({count:ao,error:co}):eo;lo&&await wait$1(lo),oo({count:ao+1})};try{const co=await Xr();no(co)}catch(co){if(ao{const{dedupe:no=!1,retryDelay:io=150,retryCount:oo=3,uid:ao}={...eo,...ro},so=no?keccak256(stringToHex(`${ao}.${stringify$4(to)}`)):void 0;return withDedupe(()=>withRetry(async()=>{try{return await Xr(to)}catch(co){const lo=co;switch(lo.code){case ParseRpcError.code:throw new ParseRpcError(lo);case InvalidRequestRpcError.code:throw new InvalidRequestRpcError(lo);case MethodNotFoundRpcError.code:throw new MethodNotFoundRpcError(lo,{method:to.method});case InvalidParamsRpcError.code:throw new InvalidParamsRpcError(lo);case InternalRpcError.code:throw new InternalRpcError(lo);case InvalidInputRpcError.code:throw new InvalidInputRpcError(lo);case ResourceNotFoundRpcError.code:throw new ResourceNotFoundRpcError(lo);case ResourceUnavailableRpcError.code:throw new ResourceUnavailableRpcError(lo);case TransactionRejectedRpcError.code:throw new TransactionRejectedRpcError(lo);case MethodNotSupportedRpcError.code:throw new MethodNotSupportedRpcError(lo,{method:to.method});case LimitExceededRpcError.code:throw new LimitExceededRpcError(lo);case JsonRpcVersionUnsupportedError.code:throw new JsonRpcVersionUnsupportedError(lo);case UserRejectedRequestError$1.code:throw new UserRejectedRequestError$1(lo);case UnauthorizedProviderError.code:throw new UnauthorizedProviderError(lo);case UnsupportedProviderMethodError.code:throw new UnsupportedProviderMethodError(lo);case ProviderDisconnectedError.code:throw new ProviderDisconnectedError(lo);case ChainDisconnectedError.code:throw new ChainDisconnectedError(lo);case SwitchChainError.code:throw new SwitchChainError(lo);case 5e3:throw new UserRejectedRequestError$1(lo);default:throw co instanceof BaseError?co:new UnknownRpcError(lo)}}},{delay:({count:co,error:lo})=>{var fo;if(lo&&lo instanceof HttpRequestError){const ho=(fo=lo==null?void 0:lo.headers)==null?void 0:fo.get("Retry-After");if(ho!=null&&ho.match(/\d/))return Number.parseInt(ho)*1e3}return~~(1<shouldRetry(co)}),{enabled:no,id:so})}}function shouldRetry(Xr){return"code"in Xr&&typeof Xr.code=="number"?Xr.code===-1||Xr.code===LimitExceededRpcError.code||Xr.code===InternalRpcError.code:Xr instanceof HttpRequestError&&Xr.status?Xr.status===403||Xr.status===408||Xr.status===413||Xr.status===429||Xr.status===500||Xr.status===502||Xr.status===503||Xr.status===504:!0}function createTransport({key:Xr,name:eo,request:to,retryCount:ro=3,retryDelay:no=150,timeout:io,type:oo},ao){const so=uid$1();return{config:{key:Xr,name:eo,request:to,retryCount:ro,retryDelay:no,timeout:io,type:oo},request:buildRequest(to,{retryCount:ro,retryDelay:no,uid:so}),value:ao}}function custom$1(Xr,eo={}){const{key:to="custom",name:ro="Custom Provider",retryDelay:no}=eo;return({retryCount:io})=>createTransport({key:to,name:ro,request:Xr.request.bind(Xr),retryCount:eo.retryCount??io,retryDelay:no,type:"custom"})}class UrlRequiredError extends BaseError{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function withTimeout(Xr,{errorInstance:eo=new Error("timed out"),timeout:to,signal:ro}){return new Promise((no,io)=>{(async()=>{let oo;try{const ao=new AbortController;to>0&&(oo=setTimeout(()=>{ro?ao.abort():io(eo)},to)),no(await Xr({signal:(ao==null?void 0:ao.signal)||null}))}catch(ao){(ao==null?void 0:ao.name)==="AbortError"&&io(eo),io(ao)}finally{clearTimeout(oo)}})()})}function createIdStore(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const idCache=createIdStore();function getHttpRpcClient(Xr,eo={}){return{async request(to){var fo;const{body:ro,onRequest:no=eo.onRequest,onResponse:io=eo.onResponse,timeout:oo=eo.timeout??1e4}=to,ao={...eo.fetchOptions??{},...to.fetchOptions??{}},{headers:so,method:co,signal:lo}=ao;try{const ho=await withTimeout(async({signal:yo})=>{const vo={...ao,body:Array.isArray(ro)?stringify$4(ro.map(Ao=>({jsonrpc:"2.0",id:Ao.id??idCache.take(),...Ao}))):stringify$4({jsonrpc:"2.0",id:ro.id??idCache.take(),...ro}),headers:{"Content-Type":"application/json",...so},method:co||"POST",signal:lo||(oo>0?yo:null)},wo=new Request(Xr,vo),Eo=await(no==null?void 0:no(wo,vo))??{...vo,url:Xr};return await fetch(Eo.url??Xr,Eo)},{errorInstance:new TimeoutError({body:ro,url:Xr}),timeout:oo,signal:!0});io&&await io(ho);let go;if((fo=ho.headers.get("Content-Type"))!=null&&fo.startsWith("application/json"))go=await ho.json();else{go=await ho.text();try{go=JSON.parse(go||"{}")}catch(yo){if(ho.ok)throw yo;go={error:go}}}if(!ho.ok)throw new HttpRequestError({body:ro,details:stringify$4(go.error)||ho.statusText,headers:ho.headers,status:ho.status,url:Xr});return go}catch(ho){throw ho instanceof HttpRequestError||ho instanceof TimeoutError?ho:new HttpRequestError({body:ro,cause:ho,url:Xr})}}}}function http(Xr,eo={}){const{batch:to,fetchOptions:ro,key:no="http",name:io="HTTP JSON-RPC",onFetchRequest:oo,onFetchResponse:ao,retryDelay:so}=eo;return({chain:co,retryCount:lo,timeout:fo})=>{const{batchSize:ho=1e3,wait:go=0}=typeof to=="object"?to:{},yo=eo.retryCount??lo,vo=fo??eo.timeout??1e4,wo=Xr||(co==null?void 0:co.rpcUrls.default.http[0]);if(!wo)throw new UrlRequiredError;const Eo=getHttpRpcClient(wo,{fetchOptions:ro,onRequest:oo,onResponse:ao,timeout:vo});return createTransport({key:no,name:io,async request({method:ko,params:Ao}){const Po={method:ko,params:Ao},{schedule:jo}=createBatchScheduler({id:wo,wait:go,shouldSplitBatch(Fo){return Fo.length>ho},fn:Fo=>Eo.request({body:Fo}),sort:(Fo,Xo)=>Fo.id-Xo.id}),Mo=async Fo=>to?jo(Fo):[await Eo.request({body:Fo})],[{error:No,result:Do}]=await Mo(Po);if(No)throw new RpcRequestError({body:Po,error:No,url:wo});return Do},retryCount:yo,retryDelay:so,timeout:vo,type:"http"},{fetchOptions:ro,url:wo})}}function isNullUniversalResolverError(Xr,eo){var ro,no,io,oo,ao,so;if(!(Xr instanceof BaseError))return!1;const to=Xr.walk(co=>co instanceof ContractFunctionRevertedError);return to instanceof ContractFunctionRevertedError?!!(((ro=to.data)==null?void 0:ro.errorName)==="ResolverNotFound"||((no=to.data)==null?void 0:no.errorName)==="ResolverWildcardNotSupported"||((io=to.data)==null?void 0:io.errorName)==="ResolverNotContract"||((oo=to.data)==null?void 0:oo.errorName)==="ResolverError"||((ao=to.data)==null?void 0:ao.errorName)==="HttpError"||(so=to.reason)!=null&&so.includes("Wildcard on non-extended resolvers is not supported")||eo==="reverse"&&to.reason===panicReasons[50]):!1}function encodedLabelToLabelhash(Xr){if(Xr.length!==66||Xr.indexOf("[")!==0||Xr.indexOf("]")!==65)return null;const eo=`0x${Xr.slice(1,65)}`;return isHex$4(eo)?eo:null}function namehash(Xr){let eo=new Uint8Array(32).fill(0);if(!Xr)return bytesToHex$2(eo);const to=Xr.split(".");for(let ro=to.length-1;ro>=0;ro-=1){const no=encodedLabelToLabelhash(to[ro]),io=no?toBytes$1(no):keccak256(stringToBytes$1(to[ro]),"bytes");eo=keccak256(concat$1([eo,io]),"bytes")}return bytesToHex$2(eo)}function encodeLabelhash(Xr){return`[${Xr.slice(2)}]`}function labelhash(Xr){const eo=new Uint8Array(32).fill(0);return Xr?encodedLabelToLabelhash(Xr)||keccak256(stringToBytes$1(Xr)):bytesToHex$2(eo)}function packetToBytes(Xr){const eo=Xr.replace(/^\.|\.$/gm,"");if(eo.length===0)return new Uint8Array(1);const to=new Uint8Array(stringToBytes$1(eo).byteLength+2);let ro=0;const no=eo.split(".");for(let io=0;io255&&(oo=stringToBytes$1(encodeLabelhash(labelhash(no[io])))),to[ro]=oo.length,to.set(oo,ro+1),ro+=oo.length+1}return to.byteLength!==ro+1?to.slice(0,ro+1):to}async function getEnsAddress(Xr,{blockNumber:eo,blockTag:to,coinType:ro,name:no,gatewayUrls:io,strict:oo,universalResolverAddress:ao}){let so=ao;if(!so){if(!Xr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");so=getChainContractAddress({blockNumber:eo,chain:Xr.chain,contract:"ensUniversalResolver"})}try{const co=encodeFunctionData({abi:addressResolverAbi,functionName:"addr",...ro!=null?{args:[namehash(no),BigInt(ro)]}:{args:[namehash(no)]}}),lo={address:so,abi:universalResolverResolveAbi,functionName:"resolve",args:[toHex$1(packetToBytes(no)),co],blockNumber:eo,blockTag:to},fo=getAction(Xr,readContract,"readContract"),ho=io?await fo({...lo,args:[...lo.args,io]}):await fo(lo);if(ho[0]==="0x")return null;const go=decodeFunctionResult({abi:addressResolverAbi,args:ro!=null?[namehash(no),BigInt(ro)]:void 0,functionName:"addr",data:ho[0]});return go==="0x"||trim$1(go)==="0x00"?null:go}catch(co){if(oo)throw co;if(isNullUniversalResolverError(co,"resolve"))return null;throw co}}class EnsAvatarInvalidMetadataError extends BaseError{constructor({data:eo}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(eo)}`],name:"EnsAvatarInvalidMetadataError"})}}class EnsAvatarInvalidNftUriError extends BaseError{constructor({reason:eo}){super(`ENS NFT avatar URI is invalid. ${eo}`,{name:"EnsAvatarInvalidNftUriError"})}}class EnsAvatarUriResolutionError extends BaseError{constructor({uri:eo}){super(`Unable to resolve ENS avatar URI "${eo}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class EnsAvatarUnsupportedNamespaceError extends BaseError{constructor({namespace:eo}){super(`ENS NFT avatar namespace "${eo}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const networkRegex=/(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/,ipfsHashRegex=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/,base64Regex=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dataURIRegex=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function isImageUri(Xr){try{const eo=await fetch(Xr,{method:"HEAD"});if(eo.status===200){const to=eo.headers.get("content-type");return to==null?void 0:to.startsWith("image/")}return!1}catch(eo){return typeof eo=="object"&&typeof eo.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(to=>{const ro=new Image;ro.onload=()=>{to(!0)},ro.onerror=()=>{to(!1)},ro.src=Xr})}}function getGateway(Xr,eo){return Xr?Xr.endsWith("/")?Xr.slice(0,-1):Xr:eo}function resolveAvatarUri({uri:Xr,gatewayUrls:eo}){const to=base64Regex.test(Xr);if(to)return{uri:Xr,isOnChain:!0,isEncoded:to};const ro=getGateway(eo==null?void 0:eo.ipfs,"https://ipfs.io"),no=getGateway(eo==null?void 0:eo.arweave,"https://arweave.net"),io=Xr.match(networkRegex),{protocol:oo,subpath:ao,target:so,subtarget:co=""}=(io==null?void 0:io.groups)||{},lo=oo==="ipns:/"||ao==="ipns/",fo=oo==="ipfs:/"||ao==="ipfs/"||ipfsHashRegex.test(Xr);if(Xr.startsWith("http")&&!lo&&!fo){let go=Xr;return eo!=null&&eo.arweave&&(go=Xr.replace(/https:\/\/arweave.net/g,eo==null?void 0:eo.arweave)),{uri:go,isOnChain:!1,isEncoded:!1}}if((lo||fo)&&so)return{uri:`${ro}/${lo?"ipns":"ipfs"}/${so}${co}`,isOnChain:!1,isEncoded:!1};if(oo==="ar:/"&&so)return{uri:`${no}/${so}${co||""}`,isOnChain:!1,isEncoded:!1};let ho=Xr.replace(dataURIRegex,"");if(ho.startsWith("no.json());return await parseAvatarUri({gatewayUrls:Xr,uri:getJsonImage(to)})}catch{throw new EnsAvatarUriResolutionError({uri:eo})}}async function parseAvatarUri({gatewayUrls:Xr,uri:eo}){const{uri:to,isOnChain:ro}=resolveAvatarUri({uri:eo,gatewayUrls:Xr});if(ro||await isImageUri(to))return to;throw new EnsAvatarUriResolutionError({uri:eo})}function parseNftUri(Xr){let eo=Xr;eo.startsWith("did:nft:")&&(eo=eo.replace("did:nft:","").replace(/_/g,"/"));const[to,ro,no]=eo.split("/"),[io,oo]=to.split(":"),[ao,so]=ro.split(":");if(!io||io.toLowerCase()!=="eip155")throw new EnsAvatarInvalidNftUriError({reason:"Only EIP-155 supported"});if(!oo)throw new EnsAvatarInvalidNftUriError({reason:"Chain ID not found"});if(!so)throw new EnsAvatarInvalidNftUriError({reason:"Contract address not found"});if(!no)throw new EnsAvatarInvalidNftUriError({reason:"Token ID not found"});if(!ao)throw new EnsAvatarInvalidNftUriError({reason:"ERC namespace not found"});return{chainID:Number.parseInt(oo),namespace:ao.toLowerCase(),contractAddress:so,tokenID:no}}async function getNftTokenUri(Xr,{nft:eo}){if(eo.namespace==="erc721")return readContract(Xr,{address:eo.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(eo.tokenID)]});if(eo.namespace==="erc1155")return readContract(Xr,{address:eo.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(eo.tokenID)]});throw new EnsAvatarUnsupportedNamespaceError({namespace:eo.namespace})}async function parseAvatarRecord(Xr,{gatewayUrls:eo,record:to}){return/eip155:/i.test(to)?parseNftAvatarUri(Xr,{gatewayUrls:eo,record:to}):parseAvatarUri({uri:to,gatewayUrls:eo})}async function parseNftAvatarUri(Xr,{gatewayUrls:eo,record:to}){const ro=parseNftUri(to),no=await getNftTokenUri(Xr,{nft:ro}),{uri:io,isOnChain:oo,isEncoded:ao}=resolveAvatarUri({uri:no,gatewayUrls:eo});if(oo&&(io.includes("data:application/json;base64,")||io.startsWith("{"))){const co=ao?atob(io.replace("data:application/json;base64,","")):io,lo=JSON.parse(co);return parseAvatarUri({uri:getJsonImage(lo),gatewayUrls:eo})}let so=ro.tokenID;return ro.namespace==="erc1155"&&(so=so.replace("0x","").padStart(64,"0")),getMetadataAvatarUri({gatewayUrls:eo,uri:io.replace(/(?:0x)?{id}/,so)})}async function getEnsText(Xr,{blockNumber:eo,blockTag:to,name:ro,key:no,gatewayUrls:io,strict:oo,universalResolverAddress:ao}){let so=ao;if(!so){if(!Xr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");so=getChainContractAddress({blockNumber:eo,chain:Xr.chain,contract:"ensUniversalResolver"})}try{const co={address:so,abi:universalResolverResolveAbi,functionName:"resolve",args:[toHex$1(packetToBytes(ro)),encodeFunctionData({abi:textResolverAbi,functionName:"text",args:[namehash(ro),no]})],blockNumber:eo,blockTag:to},lo=getAction(Xr,readContract,"readContract"),fo=io?await lo({...co,args:[...co.args,io]}):await lo(co);if(fo[0]==="0x")return null;const ho=decodeFunctionResult({abi:textResolverAbi,functionName:"text",data:fo[0]});return ho===""?null:ho}catch(co){if(oo)throw co;if(isNullUniversalResolverError(co,"resolve"))return null;throw co}}async function getEnsAvatar(Xr,{blockNumber:eo,blockTag:to,assetGatewayUrls:ro,name:no,gatewayUrls:io,strict:oo,universalResolverAddress:ao}){const so=await getAction(Xr,getEnsText,"getEnsText")({blockNumber:eo,blockTag:to,key:"avatar",name:no,universalResolverAddress:ao,gatewayUrls:io,strict:oo});if(!so)return null;try{return await parseAvatarRecord(Xr,{record:so,gatewayUrls:ro})}catch{return null}}async function getEnsName(Xr,{address:eo,blockNumber:to,blockTag:ro,gatewayUrls:no,strict:io,universalResolverAddress:oo}){let ao=oo;if(!ao){if(!Xr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");ao=getChainContractAddress({blockNumber:to,chain:Xr.chain,contract:"ensUniversalResolver"})}const so=`${eo.toLowerCase().substring(2)}.addr.reverse`;try{const co={address:ao,abi:universalResolverReverseAbi,functionName:"reverse",args:[toHex$1(packetToBytes(so))],blockNumber:to,blockTag:ro},lo=getAction(Xr,readContract,"readContract"),[fo,ho]=no?await lo({...co,args:[...co.args,no]}):await lo(co);return eo.toLowerCase()!==ho.toLowerCase()?null:fo}catch(co){if(io)throw co;if(isNullUniversalResolverError(co,"reverse"))return null;throw co}}async function getEnsResolver(Xr,{blockNumber:eo,blockTag:to,name:ro,universalResolverAddress:no}){let io=no;if(!io){if(!Xr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");io=getChainContractAddress({blockNumber:eo,chain:Xr.chain,contract:"ensUniversalResolver"})}const[oo]=await getAction(Xr,readContract,"readContract")({address:io,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[toHex$1(packetToBytes(ro))],blockNumber:eo,blockTag:to});return oo}async function createBlockFilter(Xr){const eo=createFilterRequestScope(Xr,{method:"eth_newBlockFilter"}),to=await Xr.request({method:"eth_newBlockFilter"});return{id:to,request:eo(to),type:"block"}}async function createEventFilter(Xr,{address:eo,args:to,event:ro,events:no,fromBlock:io,strict:oo,toBlock:ao}={}){const so=no??(ro?[ro]:void 0),co=createFilterRequestScope(Xr,{method:"eth_newFilter"});let lo=[];so&&(lo=[so.flatMap(go=>encodeEventTopics({abi:[go],eventName:go.name,args:to}))],ro&&(lo=lo[0]));const fo=await Xr.request({method:"eth_newFilter",params:[{address:eo,fromBlock:typeof io=="bigint"?numberToHex(io):io,toBlock:typeof ao=="bigint"?numberToHex(ao):ao,...lo.length?{topics:lo}:{}}]});return{abi:so,args:to,eventName:ro?ro.name:void 0,fromBlock:io,id:fo,request:co(fo),strict:!!oo,toBlock:ao,type:"event"}}async function createPendingTransactionFilter(Xr){const eo=createFilterRequestScope(Xr,{method:"eth_newPendingTransactionFilter"}),to=await Xr.request({method:"eth_newPendingTransactionFilter"});return{id:to,request:eo(to),type:"transaction"}}async function getBlobBaseFee(Xr){const eo=await Xr.request({method:"eth_blobBaseFee"});return BigInt(eo)}async function getBlockTransactionCount(Xr,{blockHash:eo,blockNumber:to,blockTag:ro="latest"}={}){const no=to!==void 0?numberToHex(to):void 0;let io;return eo?io=await Xr.request({method:"eth_getBlockTransactionCountByHash",params:[eo]},{dedupe:!0}):io=await Xr.request({method:"eth_getBlockTransactionCountByNumber",params:[no||ro]},{dedupe:!!no}),hexToNumber$2(io)}async function getCode$1(Xr,{address:eo,blockNumber:to,blockTag:ro="latest"}){const no=to!==void 0?numberToHex(to):void 0,io=await Xr.request({method:"eth_getCode",params:[eo,no||ro]},{dedupe:!!no});if(io!=="0x")return io}function formatFeeHistory(Xr){var eo;return{baseFeePerGas:Xr.baseFeePerGas.map(to=>BigInt(to)),gasUsedRatio:Xr.gasUsedRatio,oldestBlock:BigInt(Xr.oldestBlock),reward:(eo=Xr.reward)==null?void 0:eo.map(to=>to.map(ro=>BigInt(ro)))}}async function getFeeHistory(Xr,{blockCount:eo,blockNumber:to,blockTag:ro="latest",rewardPercentiles:no}){const io=to?numberToHex(to):void 0,oo=await Xr.request({method:"eth_feeHistory",params:[numberToHex(eo),io||ro,no]},{dedupe:!!io});return formatFeeHistory(oo)}async function getFilterLogs(Xr,{filter:eo}){const to=eo.strict??!1,no=(await eo.request({method:"eth_getFilterLogs",params:[eo.id]})).map(io=>formatLog(io));return eo.abi?parseEventLogs({abi:eo.abi,logs:no,strict:to}):no}function defineChain(Xr){return{formatters:void 0,fees:void 0,serializers:void 0,...Xr}}const arrayRegex=/^(.*)\[([0-9]*)\]$/,bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,integerRegex=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;class InvalidPrimaryTypeError extends BaseError{constructor({primaryType:eo,types:to}){super(`Invalid primary type \`${eo}\` must be one of \`${JSON.stringify(Object.keys(to))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class InvalidStructTypeError extends BaseError{constructor({type:eo}){super(`Struct type "${eo}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function hashTypedData(Xr){const{domain:eo={},message:to,primaryType:ro}=Xr,no={EIP712Domain:getTypesForEIP712Domain({domain:eo}),...Xr.types};validateTypedData$1({domain:eo,message:to,primaryType:ro,types:no});const io=["0x1901"];return eo&&io.push(hashDomain({domain:eo,types:no})),ro!=="EIP712Domain"&&io.push(hashStruct({data:to,primaryType:ro,types:no})),keccak256(concat$1(io))}function hashDomain({domain:Xr,types:eo}){return hashStruct({data:Xr,primaryType:"EIP712Domain",types:eo})}function hashStruct({data:Xr,primaryType:eo,types:to}){const ro=encodeData$3({data:Xr,primaryType:eo,types:to});return keccak256(ro)}function encodeData$3({data:Xr,primaryType:eo,types:to}){const ro=[{type:"bytes32"}],no=[hashType({primaryType:eo,types:to})];for(const io of to[eo]){const[oo,ao]=encodeField({types:to,name:io.name,type:io.type,value:Xr[io.name]});ro.push(oo),no.push(ao)}return encodeAbiParameters(ro,no)}function hashType({primaryType:Xr,types:eo}){const to=toHex$1(encodeType$1({primaryType:Xr,types:eo}));return keccak256(to)}function encodeType$1({primaryType:Xr,types:eo}){let to="";const ro=findTypeDependencies({primaryType:Xr,types:eo});ro.delete(Xr);const no=[Xr,...Array.from(ro).sort()];for(const io of no)to+=`${io}(${eo[io].map(({name:oo,type:ao})=>`${ao} ${oo}`).join(",")})`;return to}function findTypeDependencies({primaryType:Xr,types:eo},to=new Set){const ro=Xr.match(/^\w*/u),no=ro==null?void 0:ro[0];if(to.has(no)||eo[no]===void 0)return to;to.add(no);for(const io of eo[no])findTypeDependencies({primaryType:io.type,types:eo},to);return to}function encodeField({types:Xr,name:eo,type:to,value:ro}){if(Xr[to]!==void 0)return[{type:"bytes32"},keccak256(encodeData$3({data:ro,primaryType:to,types:Xr}))];if(to==="bytes")return ro=`0x${(ro.length%2?"0":"")+ro.slice(2)}`,[{type:"bytes32"},keccak256(ro)];if(to==="string")return[{type:"bytes32"},keccak256(toHex$1(ro))];if(to.lastIndexOf("]")===to.length-1){const no=to.slice(0,to.lastIndexOf("[")),io=ro.map(oo=>encodeField({name:eo,type:no,types:Xr,value:oo}));return[{type:"bytes32"},keccak256(encodeAbiParameters(io.map(([oo])=>oo),io.map(([,oo])=>oo)))]}return[{type:to},ro]}function serializeTypedData(Xr){const{domain:eo,message:to,primaryType:ro,types:no}=Xr,io=(so,co)=>{const lo={...co};for(const fo of so){const{name:ho,type:go}=fo;go==="address"&&(lo[ho]=lo[ho].toLowerCase())}return lo},oo=no.EIP712Domain?eo?io(no.EIP712Domain,eo):{}:{},ao=(()=>{if(ro!=="EIP712Domain")return io(no[ro],to)})();return stringify$4({domain:oo,message:ao,primaryType:ro,types:no})}function validateTypedData$1(Xr){const{domain:eo,message:to,primaryType:ro,types:no}=Xr,io=(oo,ao)=>{for(const so of oo){const{name:co,type:lo}=so,fo=ao[co],ho=lo.match(integerRegex);if(ho&&(typeof fo=="number"||typeof fo=="bigint")){const[vo,wo,Eo]=ho;numberToHex(fo,{signed:wo==="int",size:Number.parseInt(Eo)/8})}if(lo==="address"&&typeof fo=="string"&&!isAddress(fo))throw new InvalidAddressError({address:fo});const go=lo.match(bytesRegex);if(go){const[vo,wo]=go;if(wo&&size$1(fo)!==Number.parseInt(wo))throw new BytesSizeMismatchError({expectedSize:Number.parseInt(wo),givenSize:size$1(fo)})}const yo=no[lo];yo&&(validateReference(lo),io(yo,fo))}};if(no.EIP712Domain&&eo&&io(no.EIP712Domain,eo),ro!=="EIP712Domain")if(no[ro])io(no[ro],to);else throw new InvalidPrimaryTypeError({primaryType:ro,types:no})}function getTypesForEIP712Domain({domain:Xr}){return[typeof(Xr==null?void 0:Xr.name)=="string"&&{name:"name",type:"string"},(Xr==null?void 0:Xr.version)&&{name:"version",type:"string"},typeof(Xr==null?void 0:Xr.chainId)=="number"&&{name:"chainId",type:"uint256"},(Xr==null?void 0:Xr.verifyingContract)&&{name:"verifyingContract",type:"address"},(Xr==null?void 0:Xr.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function validateReference(Xr){if(Xr==="address"||Xr==="bool"||Xr==="string"||Xr.startsWith("bytes")||Xr.startsWith("uint")||Xr.startsWith("int"))throw new InvalidStructTypeError({type:Xr})}function encodePacked(Xr,eo){if(Xr.length!==eo.length)throw new AbiEncodingLengthMismatchError({expectedLength:Xr.length,givenLength:eo.length});const to=[];for(let ro=0;roformatLog(to)):null,to:Xr.to?Xr.to:null,transactionIndex:Xr.transactionIndex?hexToNumber$2(Xr.transactionIndex):null,status:Xr.status?receiptStatuses[Xr.status]:null,type:Xr.type?transactionType[Xr.type]||Xr.type:null};return Xr.blobGasPrice&&(eo.blobGasPrice=BigInt(Xr.blobGasPrice)),Xr.blobGasUsed&&(eo.blobGasUsed=BigInt(Xr.blobGasUsed)),eo}const defineTransactionReceipt=defineFormatter("transactionReceipt",formatTransactionReceipt),presignMessagePrefix=`Ethereum Signed Message: `;function toPrefixedMessage(Xr){const eo=typeof Xr=="string"?stringToHex(Xr):typeof Xr.raw=="string"?Xr.raw:bytesToHex$2(Xr.raw),to=stringToHex(`${presignMessagePrefix}${size$1(eo)}`);return concat$1([to,eo])}function hashMessage(Xr,eo){return keccak256(toPrefixedMessage(Xr),eo)}const erc6492MagicBytes="0x6492649264926492649264926492649264926492649264926492649264926492";function isErc6492Signature(Xr){return sliceHex(Xr,-32)===erc6492MagicBytes}function serializeErc6492Signature(Xr){const{address:eo,data:to,signature:ro,to:no="hex"}=Xr,io=concatHex([encodeAbiParameters([{type:"address"},{type:"bytes"},{type:"bytes"}],[eo,to,ro]),erc6492MagicBytes]);return no==="hex"?io:hexToBytes$3(io)}function assertTransactionEIP7702(Xr){const{authorizationList:eo}=Xr;if(eo)for(const to of eo){const{contractAddress:ro,chainId:no}=to;if(!isAddress(ro))throw new InvalidAddressError({address:ro});if(no<0)throw new InvalidChainIdError({chainId:no})}assertTransactionEIP1559(Xr)}function assertTransactionEIP4844(Xr){const{blobVersionedHashes:eo}=Xr;if(eo){if(eo.length===0)throw new EmptyBlobError;for(const to of eo){const ro=size$1(to),no=hexToNumber$2(slice(to,0,1));if(ro!==32)throw new InvalidVersionedHashSizeError({hash:to,size:ro});if(no!==versionedHashVersionKzg)throw new InvalidVersionedHashVersionError({hash:to,version:no})}}assertTransactionEIP1559(Xr)}function assertTransactionEIP1559(Xr){const{chainId:eo,maxPriorityFeePerGas:to,maxFeePerGas:ro,to:no}=Xr;if(eo<=0)throw new InvalidChainIdError({chainId:eo});if(no&&!isAddress(no))throw new InvalidAddressError({address:no});if(ro&&ro>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:ro});if(to&&ro&&to>ro)throw new TipAboveFeeCapError({maxFeePerGas:ro,maxPriorityFeePerGas:to})}function assertTransactionEIP2930(Xr){const{chainId:eo,maxPriorityFeePerGas:to,gasPrice:ro,maxFeePerGas:no,to:io}=Xr;if(eo<=0)throw new InvalidChainIdError({chainId:eo});if(io&&!isAddress(io))throw new InvalidAddressError({address:io});if(to||no)throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(ro&&ro>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:ro})}function assertTransactionLegacy(Xr){const{chainId:eo,maxPriorityFeePerGas:to,gasPrice:ro,maxFeePerGas:no,to:io}=Xr;if(io&&!isAddress(io))throw new InvalidAddressError({address:io});if(typeof eo<"u"&&eo<=0)throw new InvalidChainIdError({chainId:eo});if(to||no)throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(ro&&ro>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:ro})}function serializeAuthorizationList(Xr){if(!Xr||Xr.length===0)return[];const eo=[];for(const to of Xr){const{contractAddress:ro,chainId:no,nonce:io,...oo}=to;eo.push([no?toHex$1(no):"0x",ro,io?toHex$1(io):"0x",...toYParitySignatureArray({},oo)])}return eo}function serializeAccessList(Xr){if(!Xr||Xr.length===0)return[];const eo=[];for(let to=0;to"u"||typeof go>"u")){const Ao=typeof Xr.blobs[0]=="string"?Xr.blobs:Xr.blobs.map(Mo=>bytesToHex$2(Mo)),Po=Xr.kzg,jo=blobsToCommitments({blobs:Ao,kzg:Po});if(typeof ho>"u"&&(ho=commitmentsToVersionedHashes({commitments:jo})),typeof go>"u"){const Mo=blobsToProofs({blobs:Ao,commitments:jo,kzg:Po});go=toBlobSidecars({blobs:Ao,commitments:jo,proofs:Mo})}}const yo=serializeAccessList(lo),vo=[toHex$1(to),no?toHex$1(no):"0x",co?toHex$1(co):"0x",so?toHex$1(so):"0x",ro?toHex$1(ro):"0x",io??"0x",oo?toHex$1(oo):"0x",fo??"0x",yo,ao?toHex$1(ao):"0x",ho??[],...toYParitySignatureArray(Xr,eo)],wo=[],Eo=[],ko=[];if(go)for(let Ao=0;Ao{if(eo.v>=35n)return(eo.v-35n)/2n>0?eo.v:27n+(eo.v===35n?0n:1n);if(to>0)return BigInt(to*2)+BigInt(35n+eo.v-27n);const go=27n+(eo.v===27n?0n:1n);if(eo.v!==go)throw new InvalidLegacyVError({v:eo.v});return go})(),fo=trim$1(eo.r),ho=trim$1(eo.s);co=[...co,toHex$1(lo),fo==="0x00"?"0x":fo,ho==="0x00"?"0x":ho]}else to>0&&(co=[...co,toHex$1(to),"0x","0x"]);return toRlp(co)}function toYParitySignatureArray(Xr,eo){const to=eo??Xr,{v:ro,yParity:no}=to;if(typeof to.r>"u")return[];if(typeof to.s>"u")return[];if(typeof ro>"u"&&typeof no>"u")return[];const io=trim$1(to.r),oo=trim$1(to.s);return[typeof no=="number"?no?toHex$1(1):"0x":ro===0n?"0x":ro===1n?toHex$1(1):ro===27n?"0x":toHex$1(1),io==="0x00"?"0x":io,oo==="0x00"?"0x":oo]}class InvalidDecimalNumberError extends BaseError{constructor({value:eo}){super(`Number \`${eo}\` is not a valid decimal number.`,{name:"InvalidDecimalNumberError"})}}function parseUnits(Xr,eo){if(!/^(-?)([0-9]*)\.?([0-9]*)$/.test(Xr))throw new InvalidDecimalNumberError({value:Xr});let[to,ro="0"]=Xr.split(".");const no=to.startsWith("-");if(no&&(to=to.slice(1)),ro=ro.replace(/(0+)$/,""),eo===0)Math.round(+`.${ro}`)===1&&(to=`${BigInt(to)+1n}`),ro="";else if(ro.length>eo){const[io,oo,ao]=[ro.slice(0,eo-1),ro.slice(eo-1,eo),ro.slice(eo)],so=Math.round(+`${oo}.${ao}`);so>9?ro=`${BigInt(io)+BigInt(1)}0`.padStart(io.length+1,"0"):ro=`${io}${so}`,ro.length>eo&&(ro=ro.slice(1),to=`${BigInt(to)+1n}`),ro=ro.slice(0,eo)}else ro=ro.padEnd(eo,"0");return BigInt(`${no?"-":""}${to}${ro}`)}function parseEther$1(Xr,eo="wei"){return parseUnits(Xr,etherUnits[eo])}function formatStorageProof(Xr){return Xr.map(eo=>({...eo,value:BigInt(eo.value)}))}function formatProof(Xr){return{...Xr,balance:Xr.balance?BigInt(Xr.balance):void 0,nonce:Xr.nonce?hexToNumber$2(Xr.nonce):void 0,storageProof:Xr.storageProof?formatStorageProof(Xr.storageProof):void 0}}async function getProof(Xr,{address:eo,blockNumber:to,blockTag:ro,storageKeys:no}){const io=ro??"latest",oo=to!==void 0?numberToHex(to):void 0,ao=await Xr.request({method:"eth_getProof",params:[eo,no,oo||io]});return formatProof(ao)}async function getStorageAt(Xr,{address:eo,blockNumber:to,blockTag:ro="latest",slot:no}){const io=to!==void 0?numberToHex(to):void 0;return await Xr.request({method:"eth_getStorageAt",params:[eo,no,io||ro]})}async function getTransaction(Xr,{blockHash:eo,blockNumber:to,blockTag:ro,hash:no,index:io}){var lo,fo,ho;const oo=ro||"latest",ao=to!==void 0?numberToHex(to):void 0;let so=null;if(no?so=await Xr.request({method:"eth_getTransactionByHash",params:[no]},{dedupe:!0}):eo?so=await Xr.request({method:"eth_getTransactionByBlockHashAndIndex",params:[eo,numberToHex(io)]},{dedupe:!0}):(ao||oo)&&(so=await Xr.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[ao||oo,numberToHex(io)]},{dedupe:!!ao})),!so)throw new TransactionNotFoundError({blockHash:eo,blockNumber:to,blockTag:oo,hash:no,index:io});return(((ho=(fo=(lo=Xr.chain)==null?void 0:lo.formatters)==null?void 0:fo.transaction)==null?void 0:ho.format)||formatTransaction)(so)}async function getTransactionConfirmations(Xr,{hash:eo,transactionReceipt:to}){const[ro,no]=await Promise.all([getAction(Xr,getBlockNumber,"getBlockNumber")({}),eo?getAction(Xr,getTransaction,"getTransaction")({hash:eo}):void 0]),io=(to==null?void 0:to.blockNumber)||(no==null?void 0:no.blockNumber);return io?ro-io+1n:0n}async function getTransactionReceipt(Xr,{hash:eo}){var no,io,oo;const to=await Xr.request({method:"eth_getTransactionReceipt",params:[eo]},{dedupe:!0});if(!to)throw new TransactionReceiptNotFoundError({hash:eo});return(((oo=(io=(no=Xr.chain)==null?void 0:no.formatters)==null?void 0:io.transactionReceipt)==null?void 0:oo.format)||formatTransactionReceipt)(to)}async function multicall(Xr,eo){var wo;const{allowFailure:to=!0,batchSize:ro,blockNumber:no,blockTag:io,multicallAddress:oo,stateOverride:ao}=eo,so=eo.contracts,co=ro??(typeof((wo=Xr.batch)==null?void 0:wo.multicall)=="object"&&Xr.batch.multicall.batchSize||1024);let lo=oo;if(!lo){if(!Xr.chain)throw new Error("client chain not configured. multicallAddress is required.");lo=getChainContractAddress({blockNumber:no,chain:Xr.chain,contract:"multicall3"})}const fo=[[]];let ho=0,go=0;for(let Eo=0;Eo0&&go>co&&fo[ho].length>0&&(ho++,go=(Mo.length-2)/2,fo[ho]=[]),fo[ho]=[...fo[ho],{allowFailure:!0,callData:Mo,target:Ao}]}catch(Mo){const No=getContractError(Mo,{abi:ko,address:Ao,args:Po,docsPath:"/docs/contract/multicall",functionName:jo});if(!to)throw No;fo[ho]=[...fo[ho],{allowFailure:!0,callData:"0x",target:Ao}]}}const yo=await Promise.allSettled(fo.map(Eo=>getAction(Xr,readContract,"readContract")({abi:multicall3Abi,address:lo,args:[Eo],blockNumber:no,blockTag:io,functionName:"aggregate3",stateOverride:ao}))),vo=[];for(let Eo=0;Eo{if(no===0||no===1)return no;if(ro&&(ro===27n||ro===28n||ro>=35n))return ro%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),oo=`0x${new secp256k1$2.Signature(hexToBigInt(Xr),hexToBigInt(eo)).toCompactHex()}${io===0?"1b":"1c"}`;return to==="hex"?oo:hexToBytes$3(oo)}async function verifyHash(Xr,eo){var fo,ho,go;const{address:to,factory:ro,factoryData:no,hash:io,signature:oo,universalSignatureVerifierAddress:ao=(go=(ho=(fo=Xr.chain)==null?void 0:fo.contracts)==null?void 0:ho.universalSignatureVerifier)==null?void 0:go.address,...so}=eo,co=isHex$4(oo)?oo:typeof oo=="object"&&"r"in oo&&"s"in oo?serializeSignature(oo):bytesToHex$2(oo),lo=await(async()=>!ro&&!no||isErc6492Signature(co)?co:serializeErc6492Signature({address:ro,data:no,signature:co}))();try{const yo=ao?{to:ao,data:encodeFunctionData({abi:universalSignatureValidatorAbi,functionName:"isValidSig",args:[to,io,lo]}),...so}:{data:encodeDeployData({abi:universalSignatureValidatorAbi,args:[to,io,lo],bytecode:universalSignatureValidatorByteCode}),...so},{data:vo}=await getAction(Xr,call,"call")(yo);return hexToBool(vo??"0x0")}catch(yo){try{if(isAddressEqual(getAddress$1(to),await recoverAddress({hash:io,signature:oo})))return!0}catch{}if(yo instanceof CallExecutionError)return!1;throw yo}}async function verifyMessage(Xr,{address:eo,message:to,factory:ro,factoryData:no,signature:io,...oo}){const ao=hashMessage(to);return verifyHash(Xr,{address:eo,factory:ro,factoryData:no,hash:ao,signature:io,...oo})}async function verifyTypedData(Xr,eo){const{address:to,factory:ro,factoryData:no,signature:io,message:oo,primaryType:ao,types:so,domain:co,...lo}=eo,fo=hashTypedData({message:oo,primaryType:ao,types:so,domain:co});return verifyHash(Xr,{address:to,factory:ro,factoryData:no,hash:fo,signature:io,...lo})}function watchBlockNumber(Xr,{emitOnBegin:eo=!1,emitMissed:to=!1,onBlockNumber:ro,onError:no,poll:io,pollingInterval:oo=Xr.pollingInterval}){const ao=typeof io<"u"?io:!(Xr.transport.type==="webSocket"||Xr.transport.type==="fallback"&&Xr.transport.transports[0].config.type==="webSocket");let so;return ao?(()=>{const fo=stringify$4(["watchBlockNumber",Xr.uid,eo,to,oo]);return observe(fo,{onBlockNumber:ro,onError:no},ho=>poll$1(async()=>{var go;try{const yo=await getAction(Xr,getBlockNumber,"getBlockNumber")({cacheTime:0});if(so){if(yo===so)return;if(yo-so>1&&to)for(let vo=so+1n;voso)&&(ho.onBlockNumber(yo,so),so=yo)}catch(yo){(go=ho.onError)==null||go.call(ho,yo)}},{emitOnBegin:eo,interval:oo}))})():(()=>{const fo=stringify$4(["watchBlockNumber",Xr.uid,eo,to]);return observe(fo,{onBlockNumber:ro,onError:no},ho=>{let go=!0,yo=()=>go=!1;return(async()=>{try{const vo=(()=>{if(Xr.transport.type==="fallback"){const Eo=Xr.transport.transports.find(ko=>ko.config.type==="webSocket");return Eo?Eo.value:Xr.transport}return Xr.transport})(),{unsubscribe:wo}=await vo.subscribe({params:["newHeads"],onData(Eo){var Ao;if(!go)return;const ko=hexToBigInt((Ao=Eo.result)==null?void 0:Ao.number);ho.onBlockNumber(ko,so),so=ko},onError(Eo){var ko;(ko=ho.onError)==null||ko.call(ho,Eo)}});yo=wo,go||yo()}catch(vo){no==null||no(vo)}})(),()=>yo()})})()}async function waitForTransactionReceipt(Xr,{confirmations:eo=1,hash:to,onReplaced:ro,pollingInterval:no=Xr.pollingInterval,retryCount:io=6,retryDelay:oo=({count:so})=>~~(1<vo(new WaitForTransactionReceiptTimeoutError({hash:to})),ao):void 0,Eo=observe(so,{onReplaced:ro,resolve:yo,reject:vo},ko=>{const Ao=getAction(Xr,watchBlockNumber,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:no,async onBlockNumber(Po){const jo=No=>{clearTimeout(wo),Ao(),No(),Eo()};let Mo=Po;if(!ho)try{if(fo){if(eo>1&&(!fo.blockNumber||Mo-fo.blockNumber+1nko.resolve(fo));return}if(co||(ho=!0,await withRetry(async()=>{co=await getAction(Xr,getTransaction,"getTransaction")({hash:to}),co.blockNumber&&(Mo=co.blockNumber)},{delay:oo,retryCount:io}),ho=!1),fo=await getAction(Xr,getTransactionReceipt,"getTransactionReceipt")({hash:to}),eo>1&&(!fo.blockNumber||Mo-fo.blockNumber+1nko.resolve(fo))}catch(No){if(No instanceof TransactionNotFoundError||No instanceof TransactionReceiptNotFoundError){if(!co){ho=!1;return}try{lo=co,ho=!0;const Do=await withRetry(()=>getAction(Xr,getBlock$1,"getBlock")({blockNumber:Mo,includeTransactions:!0}),{delay:oo,retryCount:io,shouldRetry:({error:Lo})=>Lo instanceof BlockNotFoundError});ho=!1;const Fo=Do.transactions.find(({from:Lo,nonce:Bo})=>Lo===lo.from&&Bo===lo.nonce);if(!Fo||(fo=await getAction(Xr,getTransactionReceipt,"getTransactionReceipt")({hash:Fo.hash}),eo>1&&(!fo.blockNumber||Mo-fo.blockNumber+1n{var Lo;(Lo=ko.onReplaced)==null||Lo.call(ko,{reason:Xo,replacedTransaction:lo,transaction:Fo,transactionReceipt:fo}),ko.resolve(fo)})}catch(Do){jo(()=>ko.reject(Do))}}else jo(()=>ko.reject(No))}}})});return go}function watchBlocks(Xr,{blockTag:eo="latest",emitMissed:to=!1,emitOnBegin:ro=!1,onBlock:no,onError:io,includeTransactions:oo,poll:ao,pollingInterval:so=Xr.pollingInterval}){const co=typeof ao<"u"?ao:!(Xr.transport.type==="webSocket"||Xr.transport.type==="fallback"&&Xr.transport.transports[0].config.type==="webSocket"),lo=oo??!1;let fo;return co?(()=>{const yo=stringify$4(["watchBlocks",Xr.uid,eo,to,ro,lo,so]);return observe(yo,{onBlock:no,onError:io},vo=>poll$1(async()=>{var wo;try{const Eo=await getAction(Xr,getBlock$1,"getBlock")({blockTag:eo,includeTransactions:lo});if(Eo.number&&(fo!=null&&fo.number)){if(Eo.number===fo.number)return;if(Eo.number-fo.number>1&&to)for(let ko=(fo==null?void 0:fo.number)+1n;kofo.number)&&(vo.onBlock(Eo,fo),fo=Eo)}catch(Eo){(wo=vo.onError)==null||wo.call(vo,Eo)}},{emitOnBegin:ro,interval:so}))})():(()=>{let yo=!0,vo=!0,wo=()=>yo=!1;return(async()=>{try{ro&&getAction(Xr,getBlock$1,"getBlock")({blockTag:eo,includeTransactions:lo}).then(Ao=>{yo&&vo&&(no(Ao,void 0),vo=!1)});const Eo=(()=>{if(Xr.transport.type==="fallback"){const Ao=Xr.transport.transports.find(Po=>Po.config.type==="webSocket");return Ao?Ao.value:Xr.transport}return Xr.transport})(),{unsubscribe:ko}=await Eo.subscribe({params:["newHeads"],onData(Ao){var Mo,No,Do;if(!yo)return;const jo=(((Do=(No=(Mo=Xr.chain)==null?void 0:Mo.formatters)==null?void 0:No.block)==null?void 0:Do.format)||formatBlock)(Ao.result);no(jo,fo),vo=!1,fo=jo},onError(Ao){io==null||io(Ao)}});wo=ko,yo||wo()}catch(Eo){io==null||io(Eo)}})(),()=>wo()})()}function watchEvent(Xr,{address:eo,args:to,batch:ro=!0,event:no,events:io,fromBlock:oo,onError:ao,onLogs:so,poll:co,pollingInterval:lo=Xr.pollingInterval,strict:fo}){const ho=typeof co<"u"?co:typeof oo=="bigint"?!0:!(Xr.transport.type==="webSocket"||Xr.transport.type==="fallback"&&Xr.transport.transports[0].config.type==="webSocket"),go=fo??!1;return ho?(()=>{const wo=stringify$4(["watchEvent",eo,to,ro,Xr.uid,no,lo,oo]);return observe(wo,{onLogs:so,onError:ao},Eo=>{let ko;oo!==void 0&&(ko=oo-1n);let Ao,Po=!1;const jo=poll$1(async()=>{var Mo;if(!Po){try{Ao=await getAction(Xr,createEventFilter,"createEventFilter")({address:eo,args:to,event:no,events:io,strict:go,fromBlock:oo})}catch{}Po=!0;return}try{let No;if(Ao)No=await getAction(Xr,getFilterChanges,"getFilterChanges")({filter:Ao});else{const Do=await getAction(Xr,getBlockNumber,"getBlockNumber")({});ko&&ko!==Do?No=await getAction(Xr,getLogs,"getLogs")({address:eo,args:to,event:no,events:io,fromBlock:ko+1n,toBlock:Do}):No=[],ko=Do}if(No.length===0)return;if(ro)Eo.onLogs(No);else for(const Do of No)Eo.onLogs([Do])}catch(No){Ao&&No instanceof InvalidInputRpcError&&(Po=!1),(Mo=Eo.onError)==null||Mo.call(Eo,No)}},{emitOnBegin:!0,interval:lo});return async()=>{Ao&&await getAction(Xr,uninstallFilter,"uninstallFilter")({filter:Ao}),jo()}})})():(()=>{let wo=!0,Eo=()=>wo=!1;return(async()=>{try{const ko=(()=>{if(Xr.transport.type==="fallback"){const Mo=Xr.transport.transports.find(No=>No.config.type==="webSocket");return Mo?Mo.value:Xr.transport}return Xr.transport})(),Ao=io??(no?[no]:void 0);let Po=[];Ao&&(Po=[Ao.flatMap(No=>encodeEventTopics({abi:[No],eventName:No.name,args:to}))],no&&(Po=Po[0]));const{unsubscribe:jo}=await ko.subscribe({params:["logs",{address:eo,topics:Po}],onData(Mo){var Do;if(!wo)return;const No=Mo.result;try{const{eventName:Fo,args:Xo}=decodeEventLog({abi:Ao??[],data:No.data,topics:No.topics,strict:go}),Lo=formatLog(No,{args:Xo,eventName:Fo});so([Lo])}catch(Fo){let Xo,Lo;if(Fo instanceof DecodeLogDataMismatch||Fo instanceof DecodeLogTopicsMismatch){if(fo)return;Xo=Fo.abiItem.name,Lo=(Do=Fo.abiItem.inputs)==null?void 0:Do.some(xo=>!("name"in xo&&xo.name))}const Bo=formatLog(No,{args:Lo?[]:{},eventName:Xo});so([Bo])}},onError(Mo){ao==null||ao(Mo)}});Eo=jo,wo||Eo()}catch(ko){ao==null||ao(ko)}})(),()=>Eo()})()}function watchPendingTransactions(Xr,{batch:eo=!0,onError:to,onTransactions:ro,poll:no,pollingInterval:io=Xr.pollingInterval}){return(typeof no<"u"?no:Xr.transport.type!=="webSocket")?(()=>{const co=stringify$4(["watchPendingTransactions",Xr.uid,eo,io]);return observe(co,{onTransactions:ro,onError:to},lo=>{let fo;const ho=poll$1(async()=>{var go;try{if(!fo)try{fo=await getAction(Xr,createPendingTransactionFilter,"createPendingTransactionFilter")({});return}catch(vo){throw ho(),vo}const yo=await getAction(Xr,getFilterChanges,"getFilterChanges")({filter:fo});if(yo.length===0)return;if(eo)lo.onTransactions(yo);else for(const vo of yo)lo.onTransactions([vo])}catch(yo){(go=lo.onError)==null||go.call(lo,yo)}},{emitOnBegin:!0,interval:io});return async()=>{fo&&await getAction(Xr,uninstallFilter,"uninstallFilter")({filter:fo}),ho()}})})():(()=>{let co=!0,lo=()=>co=!1;return(async()=>{try{const{unsubscribe:fo}=await Xr.transport.subscribe({params:["newPendingTransactions"],onData(ho){if(!co)return;const go=ho.result;ro([go])},onError(ho){to==null||to(ho)}});lo=fo,co||lo()}catch(fo){to==null||to(fo)}})(),()=>lo()})()}function parseSiweMessage(Xr){var fo,ho,go;const{scheme:eo,statement:to,...ro}=((fo=Xr.match(prefixRegex))==null?void 0:fo.groups)??{},{chainId:no,expirationTime:io,issuedAt:oo,notBefore:ao,requestId:so,...co}=((ho=Xr.match(suffixRegex))==null?void 0:ho.groups)??{},lo=(go=Xr.split("Resources:")[1])==null?void 0:go.split(` - `).slice(1);return{...ro,...co,...no?{chainId:Number(no)}:{},...io?{expirationTime:new Date(io)}:{},...oo?{issuedAt:new Date(oo)}:{},...ao?{notBefore:new Date(ao)}:{},...so?{requestId:so}:{},...lo?{resources:lo}:{},...eo?{scheme:eo}:{},...to?{statement:to}:{}}}const prefixRegex=/^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/,suffixRegex=/(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/;function validateSiweMessage(Xr){const{address:eo,domain:to,message:ro,nonce:no,scheme:io,time:oo=new Date}=Xr;if(to&&ro.domain!==to||no&&ro.nonce!==no||io&&ro.scheme!==io||ro.expirationTime&&oo>=ro.expirationTime||ro.notBefore&&oocall(Xr,eo),createBlockFilter:()=>createBlockFilter(Xr),createContractEventFilter:eo=>createContractEventFilter(Xr,eo),createEventFilter:eo=>createEventFilter(Xr,eo),createPendingTransactionFilter:()=>createPendingTransactionFilter(Xr),estimateContractGas:eo=>estimateContractGas(Xr,eo),estimateGas:eo=>estimateGas$1(Xr,eo),getBalance:eo=>getBalance(Xr,eo),getBlobBaseFee:()=>getBlobBaseFee(Xr),getBlock:eo=>getBlock$1(Xr,eo),getBlockNumber:eo=>getBlockNumber(Xr,eo),getBlockTransactionCount:eo=>getBlockTransactionCount(Xr,eo),getBytecode:eo=>getCode$1(Xr,eo),getChainId:()=>getChainId$1(Xr),getCode:eo=>getCode$1(Xr,eo),getContractEvents:eo=>getContractEvents(Xr,eo),getEip712Domain:eo=>getEip712Domain$1(Xr,eo),getEnsAddress:eo=>getEnsAddress(Xr,eo),getEnsAvatar:eo=>getEnsAvatar(Xr,eo),getEnsName:eo=>getEnsName(Xr,eo),getEnsResolver:eo=>getEnsResolver(Xr,eo),getEnsText:eo=>getEnsText(Xr,eo),getFeeHistory:eo=>getFeeHistory(Xr,eo),estimateFeesPerGas:eo=>estimateFeesPerGas$1(Xr,eo),getFilterChanges:eo=>getFilterChanges(Xr,eo),getFilterLogs:eo=>getFilterLogs(Xr,eo),getGasPrice:()=>getGasPrice(Xr),getLogs:eo=>getLogs(Xr,eo),getProof:eo=>getProof(Xr,eo),estimateMaxPriorityFeePerGas:eo=>estimateMaxPriorityFeePerGas(Xr,eo),getStorageAt:eo=>getStorageAt(Xr,eo),getTransaction:eo=>getTransaction(Xr,eo),getTransactionConfirmations:eo=>getTransactionConfirmations(Xr,eo),getTransactionCount:eo=>getTransactionCount(Xr,eo),getTransactionReceipt:eo=>getTransactionReceipt(Xr,eo),multicall:eo=>multicall(Xr,eo),prepareTransactionRequest:eo=>prepareTransactionRequest(Xr,eo),readContract:eo=>readContract(Xr,eo),sendRawTransaction:eo=>sendRawTransaction(Xr,eo),simulateContract:eo=>simulateContract(Xr,eo),verifyMessage:eo=>verifyMessage(Xr,eo),verifySiweMessage:eo=>verifySiweMessage(Xr,eo),verifyTypedData:eo=>verifyTypedData(Xr,eo),uninstallFilter:eo=>uninstallFilter(Xr,eo),waitForTransactionReceipt:eo=>waitForTransactionReceipt(Xr,eo),watchBlocks:eo=>watchBlocks(Xr,eo),watchBlockNumber:eo=>watchBlockNumber(Xr,eo),watchContractEvent:eo=>watchContractEvent(Xr,eo),watchEvent:eo=>watchEvent(Xr,eo),watchPendingTransactions:eo=>watchPendingTransactions(Xr,eo)}}function createPublicClient(Xr){const{key:eo="public",name:to="Public Client"}=Xr;return createClient({...Xr,key:eo,name:to,type:"publicClient"}).extend(publicActions)}function deployContract(Xr,eo){const{abi:to,args:ro,bytecode:no,...io}=eo,oo=encodeDeployData({abi:to,args:ro,bytecode:no});return sendTransaction$1(Xr,{...io,data:oo})}async function getAddresses(Xr){var to;return((to=Xr.account)==null?void 0:to.type)==="local"?[Xr.account.address]:(await Xr.request({method:"eth_accounts"},{dedupe:!0})).map(ro=>checksumAddress(ro))}async function getPermissions(Xr){return await Xr.request({method:"wallet_getPermissions"},{dedupe:!0})}async function requestAddresses(Xr){return(await Xr.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(to=>getAddress$1(to))}async function requestPermissions(Xr,eo){return Xr.request({method:"wallet_requestPermissions",params:[eo]},{retryCount:0})}async function signMessage$3(Xr,{account:eo=Xr.account,message:to}){if(!eo)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signMessage"});const ro=parseAccount(eo);if(ro.signMessage)return ro.signMessage({message:to});const no=typeof to=="string"?stringToHex(to):to.raw instanceof Uint8Array?toHex$1(to.raw):to.raw;return Xr.request({method:"personal_sign",params:[no,ro.address]},{retryCount:0})}async function signTransaction$3(Xr,eo){var co,lo,fo,ho;const{account:to=Xr.account,chain:ro=Xr.chain,...no}=eo;if(!to)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signTransaction"});const io=parseAccount(to);assertRequest({account:io,...eo});const oo=await getAction(Xr,getChainId$1,"getChainId")({});ro!==null&&assertCurrentChain({currentChainId:oo,chain:ro});const ao=(ro==null?void 0:ro.formatters)||((co=Xr.chain)==null?void 0:co.formatters),so=((lo=ao==null?void 0:ao.transactionRequest)==null?void 0:lo.format)||formatTransactionRequest;return io.signTransaction?io.signTransaction({...no,chainId:oo},{serializer:(ho=(fo=Xr.chain)==null?void 0:fo.serializers)==null?void 0:ho.transaction}):await Xr.request({method:"eth_signTransaction",params:[{...so(no),chainId:numberToHex(oo),from:io.address}]},{retryCount:0})}async function signTypedData$2(Xr,eo){const{account:to=Xr.account,domain:ro,message:no,primaryType:io}=eo;if(!to)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signTypedData"});const oo=parseAccount(to),ao={EIP712Domain:getTypesForEIP712Domain({domain:ro}),...eo.types};if(validateTypedData$1({domain:ro,message:no,primaryType:io,types:ao}),oo.signTypedData)return oo.signTypedData({domain:ro,message:no,primaryType:io,types:ao});const so=serializeTypedData({domain:ro,message:no,primaryType:io,types:ao});return Xr.request({method:"eth_signTypedData_v4",params:[oo.address,so]},{retryCount:0})}async function switchChain(Xr,{id:eo}){await Xr.request({method:"wallet_switchEthereumChain",params:[{chainId:numberToHex(eo)}]},{retryCount:0})}async function watchAsset(Xr,eo){return await Xr.request({method:"wallet_watchAsset",params:eo},{retryCount:0})}function walletActions(Xr){return{addChain:eo=>addChain(Xr,eo),deployContract:eo=>deployContract(Xr,eo),getAddresses:()=>getAddresses(Xr),getChainId:()=>getChainId$1(Xr),getPermissions:()=>getPermissions(Xr),prepareTransactionRequest:eo=>prepareTransactionRequest(Xr,eo),requestAddresses:()=>requestAddresses(Xr),requestPermissions:eo=>requestPermissions(Xr,eo),sendRawTransaction:eo=>sendRawTransaction(Xr,eo),sendTransaction:eo=>sendTransaction$1(Xr,eo),signMessage:eo=>signMessage$3(Xr,eo),signTransaction:eo=>signTransaction$3(Xr,eo),signTypedData:eo=>signTypedData$2(Xr,eo),switchChain:eo=>switchChain(Xr,eo),watchAsset:eo=>watchAsset(Xr,eo),writeContract:eo=>writeContract(Xr,eo)}}function createWalletClient(Xr){const{key:eo="wallet",name:to="Wallet Client",transport:ro}=Xr;return createClient({...Xr,key:eo,name:to,transport:ro,type:"walletClient"}).extend(walletActions)}var ENV$1=(Xr=>(Xr.PROD="prod",Xr.STAGING="staging",Xr.DEV="dev",Xr.LOCAL="local",Xr))(ENV$1||{});const gasPerPubdataDefault=50000n,maxBytecodeSize=maxUint16*32n,formatters$2={block:defineBlock({format(Xr){var to;const eo=(to=Xr.transactions)==null?void 0:to.map(ro=>{var io;if(typeof ro=="string")return ro;const no=(io=formatters$2.transaction)==null?void 0:io.format(ro);return no.typeHex==="0x71"?no.type="eip712":no.typeHex==="0xff"&&(no.type="priority"),no});return{l1BatchNumber:Xr.l1BatchNumber?hexToBigInt(Xr.l1BatchNumber):null,l1BatchTimestamp:Xr.l1BatchTimestamp?hexToBigInt(Xr.l1BatchTimestamp):null,transactions:eo}}}),transaction:defineTransaction({format(Xr){const eo={};return Xr.type==="0x71"?eo.type="eip712":Xr.type==="0xff"&&(eo.type="priority"),{...eo,l1BatchNumber:Xr.l1BatchNumber?hexToBigInt(Xr.l1BatchNumber):null,l1BatchTxIndex:Xr.l1BatchTxIndex?hexToBigInt(Xr.l1BatchTxIndex):null}}}),transactionReceipt:defineTransactionReceipt({format(Xr){return{l1BatchNumber:Xr.l1BatchNumber?hexToBigInt(Xr.l1BatchNumber):null,l1BatchTxIndex:Xr.l1BatchTxIndex?hexToBigInt(Xr.l1BatchTxIndex):null,logs:Xr.logs.map(eo=>({...formatLog(eo),l1BatchNumber:eo.l1BatchNumber?hexToBigInt(eo.l1BatchNumber):null,transactionLogIndex:hexToNumber$2(eo.transactionLogIndex),logType:eo.logType})),l2ToL1Logs:Xr.l2ToL1Logs.map(eo=>({blockNumber:hexToBigInt(eo.blockHash),blockHash:eo.blockHash,l1BatchNumber:hexToBigInt(eo.l1BatchNumber),transactionIndex:hexToBigInt(eo.transactionIndex),shardId:hexToBigInt(eo.shardId),isService:eo.isService,sender:eo.sender,key:eo.key,value:eo.value,transactionHash:eo.transactionHash,logIndex:hexToBigInt(eo.logIndex)}))}}}),transactionRequest:defineTransactionRequest({exclude:["customSignature","factoryDeps","gasPerPubdata","paymaster","paymasterInput"],format(Xr){return Xr.gasPerPubdata||Xr.paymaster&&Xr.paymasterInput||Xr.factoryDeps||Xr.customSignature?{eip712Meta:{...Xr.gasPerPubdata?{gasPerPubdata:toHex$1(Xr.gasPerPubdata)}:{gasPerPubdata:toHex$1(gasPerPubdataDefault)},...Xr.paymaster&&Xr.paymasterInput?{paymasterParams:{paymaster:Xr.paymaster,paymasterInput:Array.from(hexToBytes$3(Xr.paymasterInput))}}:{},...Xr.factoryDeps?{factoryDeps:Xr.factoryDeps.map(eo=>Array.from(hexToBytes$3(eo)))}:{},...Xr.customSignature?{customSignature:Array.from(hexToBytes$3(Xr.customSignature))}:{}},type:"0x71"}:{}}})};class InvalidEip712TransactionError extends BaseError{constructor(){super(["Transaction is not an EIP712 transaction.","","Transaction must:",' - include `type: "eip712"`'," - include one of the following: `customSignature`, `paymaster`, `paymasterInput`, `gasPerPubdata`, `factoryDeps`"].join(` @@ -2214,7 +2214,7 @@ Minimum version required to store current data is: `+io+`. `),lo=()=>__awaiter$j(void 0,void 0,void 0,function*(){eo(!1),yield oo()});return jsxRuntimeExports.jsxs("div",{className:"mfa-display-backup-codes-view__body","data-testid":"mfa-display-backup-codes-view",children:[jsxRuntimeExports.jsx(Typography,{className:"mfa-display-backup-codes-view__copy",variant:"body_normal",weight:"regular",color:"secondary",children:no("dyn_mfa.display_backup_codes_view.body")}),jsxRuntimeExports.jsx(Alert,{variant:"warning",copykey:"dyn_mfa.display_backup_codes_view.warning",className:"mfa-display-backup-codes-view__warning",children:no("dyn_mfa.display_backup_codes_view.warning")}),so?jsxRuntimeExports.jsx(Spinner$1,{className:"mfa-display-backup-codes-view__loading-spinner"}):jsxRuntimeExports.jsxs("div",{className:"mfa-display-backup-codes-view__codes",children:[ao==null?void 0:ao.map((fo,ho)=>jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"mfa-display-backup-codes-view__code",children:fo},ho)),jsxRuntimeExports.jsxs("div",{className:"mfa-display-backup-codes-view__actions",children:[jsxRuntimeExports.jsx(CopyButton,{variant:"button",textToCopy:co,copykey:"dyn_mfa.display_backup_codes_view.copy_all",startSlot:jsxRuntimeExports.jsx(Icon,{size:"mini",color:"text-tertiary",children:jsxRuntimeExports.jsx(SvgCopy,{})}),children:no("dyn_mfa.display_backup_codes_view.copy_all")}),jsxRuntimeExports.jsx(TypographyButton,{dataTestId:"download-button",buttonPadding:"small",buttonVariant:"primary",onClick:fo=>{fo.preventDefault(),downloadFile("mfa-backup-codes.txt",co)},startSlot:jsxRuntimeExports.jsx(SvgDownload,{}),expanded:!0,copykey:"dyn_mfa.display_backup_codes_view.download",children:no("dyn_mfa.display_backup_codes_view.download")})]})]}),jsxRuntimeExports.jsxs("div",{className:"mfa-display-backup-codes-view__complete",children:[jsxRuntimeExports.jsx(TypographyButton,{buttonClassName:"mfa-display-backup-codes-view__acknowledgement",dataTestId:"ack-button",buttonPadding:"small",buttonVariant:"primary",onClick:()=>ro(!to),startSlot:jsxRuntimeExports.jsx(Checkbox,{checked:to,onChange:()=>{ro(!to)},className:"mfa-display-backup-codes-view__acknowledgement__checkbox"}),expanded:!0,typographyProps:{color:"secondary"},copykey:"dyn_mfa.display_backup_codes_view.checkbox",children:no("dyn_mfa.display_backup_codes_view.checkbox")}),jsxRuntimeExports.jsx(TypographyButton,{dataTestId:"complete-button",buttonPadding:"large",buttonVariant:"brand-primary",typographyProps:{color:"inherit"},disabled:!to,expanded:!0,copykey:"dyn_mfa.display_backup_codes_view.complete",onClick:lo,children:no("dyn_mfa.display_backup_codes_view.complete")})]})]})},isValidMfaRecoveryCode=Xr=>/^[a-zA-Z0-9]{10}$/.test(Xr);var _path$8,_excluded$c=["title","titleId"];function _extends$e(){return _extends$e=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$c(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgMfaRecoveryIcon=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$c(eo,_excluded$c);return reactExports.createElement("svg",_extends$e({width:65,height:64,viewBox:"0 0 65 64",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_path$8||(_path$8=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32.5 64c17.673 0 32-14.327 32-32 0-17.673-14.327-32-32-32C14.827 0 .5 14.327.5 32c0 17.673 14.327 32 32 32Zm-9.322-18.117a1.828 1.828 0 1 0 3.613.568l1.152-7.457h7.144l-1.1 6.89a1.828 1.828 0 1 0 3.612.567l1.153-7.457h3.504a1.691 1.691 0 0 0 0-3.383h-2.948l1.16-7.222h3.597a1.691 1.691 0 0 0 0-3.383h-3.087l1.1-6.89a1.829 1.829 0 1 0-3.612-.567l-1.153 7.457H30.17l1.1-6.89a1.828 1.828 0 1 0-3.613-.567l-1.152 7.457h-3.458a1.691 1.691 0 0 0 0 3.383h2.901l-1.16 7.222h-3.597a1.691 1.691 0 0 0 0 3.383h3.087l-1.1 6.89Zm12.42-10.272H28.5l1.16-7.222h7.097l-1.16 7.222Z",fill:"#4779FF"})))};const MfaRecoveryScreenIcon=Xr=>jsxRuntimeExports.jsx(Icon,{color:"brand-primary",children:jsxRuntimeExports.jsx(SvgMfaRecoveryIcon,Object.assign({},Xr,{"data-testid":"mfa-recovery-icon"}))}),MfaRecoveryView=()=>{var Xr;const{t:eo}=useTranslation(),{projectSettings:to}=useInternalDynamicContext(),{authRecoveryCode:ro}=useMfa(),[no,io]=reactExports.useState(""),[oo,ao]=reactExports.useState(!1),[so,co]=reactExports.useState(""),lo=(Xr=to==null?void 0:to.general)===null||Xr===void 0?void 0:Xr.supportEmail,fo=()=>__awaiter$j(void 0,void 0,void 0,function*(){if(no)try{ao(!0),yield ro(no)}catch(go){co(go.message||"Something went wrong")}finally{ao(!1)}}),ho=go=>{const yo=go.target.value;io(yo),co("")};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[so&&jsxRuntimeExports.jsx(ErrorContainer,{children:so}),jsxRuntimeExports.jsxs("div",{className:"mfa-recovery-view",children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:MfaRecoveryScreenIcon,isSpinning:oo,iconSize:96}),jsxRuntimeExports.jsx("div",{className:"mfa-recovery-view__body",children:jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",children:eo("dyn_mfa.recovery_view.body")})}),jsxRuntimeExports.jsxs("div",{className:"mfa-recovery-view__actions",children:[jsxRuntimeExports.jsx(Input,{id:"mfa-recovery-input","data-testid":"mfa-recovery-input",label:eo("dyn_mfa.recovery_view.input_label"),onChange:ho,value:no}),jsxRuntimeExports.jsx(Button,{expanded:!0,buttonVariant:"brand-primary",disabled:oo||!isValidMfaRecoveryCode(no),onClick:fo,dataTestId:"mfa-recovery-submit",children:jsxRuntimeExports.jsx(Typography,{children:eo("dyn_mfa.recovery_view.button_label")})})]}),lo&&jsxRuntimeExports.jsxs("div",{className:"mfa-recovery-view__get-help",children:[jsxRuntimeExports.jsx(Typography,{variant:"body_small",color:"secondary",children:eo("dyn_mfa.recovery_view.get_help.description")}),jsxRuntimeExports.jsx(Typography,{variant:"body_small",color:"link",children:jsxRuntimeExports.jsx("a",{href:`mailto:${lo}`,children:eo("dyn_mfa.recovery_view.get_help.button_label")})})]})]})]})},MfaSecureDeviceHelper=({uri:Xr,secret:eo})=>{const{t:to}=useTranslation();return jsxRuntimeExports.jsx("div",{className:"mfa-qrcode-help-content__container",children:jsxRuntimeExports.jsx(EnterTileAnimation,{delay:"300ms",children:jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__setup-container",children:[jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__step",children:[jsxRuntimeExports.jsx("div",{className:"mfa-qrcode-help-content__step__number",children:"1"}),jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__step__instructions",children:[jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"primary",className:"mfa-qrcode-help-content__step__title",children:to("dyn_mfa.secure_device_view.helper.step1.title")}),jsxRuntimeExports.jsx(Typography,{variant:"body_small",className:"mfa-qrcode-help-content__step__subtext",children:to("dyn_mfa.secure_device_view.helper.step1.description")})]})]}),jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__vertical-container",children:[jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__step",children:[jsxRuntimeExports.jsx("div",{className:"mfa-qrcode-help-content__step__number",children:"2"}),jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__step__instructions",children:[jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"primary",className:"mfa-qrcode-help-content__step__title",children:to("dyn_mfa.secure_device_view.helper.step2.title")}),jsxRuntimeExports.jsx(Typography,{variant:"body_small",className:"mfa-qrcode-help-content__step__subtext",children:to("dyn_mfa.secure_device_view.helper.step2.description")})]})]}),jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__step__nocopy-box",children:[jsxRuntimeExports.jsx(Typography,{className:"mfa-qrcode-help-content__step__nocopy-text",variant:"body_small",children:eo}),jsxRuntimeExports.jsx(CopyButton,{textToCopy:eo,children:jsxRuntimeExports.jsx(SvgCopy,{"data-testid":"copy-secret",onClick:ro=>{ro.preventDefault()}})})]})]}),jsxRuntimeExports.jsx(Divider,{text:"OR"}),jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__vertical-container",children:[jsxRuntimeExports.jsx("div",{className:"mfa-qrcode-help-content__step",children:jsxRuntimeExports.jsxs("div",{className:"uri-section",children:[jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"primary",className:"mfa-qrcode-help-content__step__title",children:to("dyn_mfa.secure_device_view.helper.uri.title")}),jsxRuntimeExports.jsx(Typography,{className:"uri-subtext",variant:"body_small",children:to("dyn_mfa.secure_device_view.helper.uri.description")})]})}),jsxRuntimeExports.jsxs("div",{className:"mfa-qrcode-help-content__step__nocopy-box",children:[jsxRuntimeExports.jsx(Typography,{className:"mfa-qrcode-help-content__step__nocopy-text",variant:"body_small",children:Xr}),jsxRuntimeExports.jsx(CopyButton,{textToCopy:Xr,children:jsxRuntimeExports.jsx(SvgCopy,{"data-testid":"copy-uri",onClick:ro=>{ro.preventDefault()}})})]})]})]})})})},MfaSecureDeviceView=({type:Xr,isInitialSetup:eo=!1})=>{const{t:to}=useTranslation(),{handleLogOut:ro}=useDynamicContext(),{setView:no}=useViewContext(),{addDevice:io}=useMfa(),{data:oo,isLoading:ao}=usePromise(()=>io(Xr)),so=()=>{const lo=()=>{no("mfa-secure-device",{type:Xr})};no("mfa-verification",{deviceId:oo==null?void 0:oo.id,isInitialSetup:eo,showBackButton:!0,type:Xr},{onBackClick:lo})},co=({secret:lo,uri:fo})=>{no("mfa-secure-device-help",{secret:lo,uri:fo},{onBackClick:()=>{no("mfa-secure-device",{isInitialSetup:eo,type:Xr})}})};return jsxRuntimeExports.jsxs("div",{className:"mfa-secure-device-view__body","data-testid":"mfa-secure-device-view",children:[jsxRuntimeExports.jsx(Typography,{className:"mfa-secure-device-view__copy",variant:"body_normal",weight:"regular",color:"secondary",children:to("dyn_mfa.secure_device_view.body")}),ao&&jsxRuntimeExports.jsx(Spinner$1,{className:"mfa-secure-device-view__loading-spinner"}),oo&&jsxRuntimeExports.jsxs("div",{className:"mfa-secure-device-view__qrcode",children:[jsxRuntimeExports.jsx(QRCode,{Icon:jsxRuntimeExports.jsx(SvgPasswordHero,{}),value:oo.uri,logoSize:50}),jsxRuntimeExports.jsx("div",{className:"button-container",children:jsxRuntimeExports.jsx("button",{onClick:()=>co({secret:oo.secret,uri:oo.uri}),children:jsxRuntimeExports.jsx(Typography,{variant:"body_small",weight:"medium",color:"secondary",children:to("dyn_mfa.secure_device_view.helper.button")})})})]}),jsxRuntimeExports.jsx(TypographyButton,{className:"mfa-secure-device-view__button",expanded:!0,onClick:so,children:to("dyn_mfa.secure_device_view.continue")}),jsxRuntimeExports.jsx(TextButton,{className:"mfa-secure-device-view__logout-button",onClick:ro,copykey:"dyn_mfa.choose_device_view.logout",children:to("dyn_mfa.secure_device_view.logout")})]})},MfaVerificationView=({type:Xr,isInitialSetup:eo=!1,showBackButton:to=!1,deviceId:ro})=>{const{t:no}=useTranslation(),{setView:io}=useViewContext(),{authDevice:oo}=useMfa(),[ao,so]=reactExports.useState(""),[co,lo]=reactExports.useState(),[fo,ho]=reactExports.useState(!1),{data:go,isLoading:yo}=usePromise(()=>oo(ao,Xr,ro),{deps:[ao],enabled:(ao==null?void 0:ao.length)===6,initialData:!1,onReject:ko=>{ko instanceof MfaRateLimitedError?(ho(!0),lo(new DynamicError(no("dyn_mfa.otp_verification_view.rate_limit_error")))):lo(new DynamicError(no("dyn_mfa.otp_verification_view.error")))},onResolve:()=>__awaiter$j(void 0,void 0,void 0,function*(){const ko=getUser();(ko==null?void 0:ko.mfaBackupCodeAcknowledgement)!==MfaBackupCodeAcknowledgement.Complete&&io("mfa-display-backup-codes")})}),vo=ko=>{lo(void 0),so(ko)},wo=ko=>{so(ko)},Eo=()=>{if(!eo){io("mfa-choose-device",{isInitialSetup:eo});return}io("mfa-secure-device",{isInitialSetup:eo,type:Xr})};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(OTPVerificationView,{MainIcon:SvgPasswordHero,error:co,isLoading:yo,onPinComplete:wo,isValid:!!go,onPinChange:vo,description:no("dyn_mfa.otp_verification_view.body"),onClickBack:to?Eo:void 0,disabled:fo}),!eo&&jsxRuntimeExports.jsx("div",{className:"mfa-verification-view__choose-another-method",children:jsxRuntimeExports.jsx(TextButton,{className:"mfa-verification-view__choose-another-method-button",onClick:()=>io("mfa-choose-device",{isInitialSetup:eo}),copykey:"dyn_mfa.otp_verification_view.choose_another_method",children:no("dyn_mfa.otp_verification_view.choose_another_method")})})]})},MobileWalletRedirectView=({onRetry:Xr})=>{const{selectedWalletConnector:eo}=useInternalDynamicContext(),{walletBook:to}=useWalletBookContext(),{t:ro}=useTranslation(),{storeName:no,walletLink:io}=reactExports.useMemo(()=>{const so=eo&&getWalletLinks(to,eo.key);return so&&isIOS$1()?{storeName:"App Store",walletLink:so==null?void 0:so.ios}:so&&(isAndroid$1()||isSamsungBrowser())?{storeName:"Play Store",walletLink:so==null?void 0:so.android}:{storeName:void 0,walletLink:void 0}},[eo,to]),oo=()=>io&&window.open(io,"_blank","noopener,noreferrer"),ao=so=>jsxRuntimeExports.jsx(WalletIcon,{walletKey:eo==null?void 0:eo.key,style:{height:pixelToRem(so),width:pixelToRem(so)}});return jsxRuntimeExports.jsxs("div",{className:"mobile-wallet-redirect",children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:ao(94*iconRatio),iconSize:94,isSpinning:!0,className:"mobile-wallet-redirect__icon-with-spinner"}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",className:"mobile-wallet-redirect__copy-text",copykey:"dyn_login.mobile_wallet_redirect.prompt",children:ro("dyn_login.mobile_wallet_redirect.prompt")}),jsxRuntimeExports.jsxs(TypographyButton,{buttonVariant:"brand-primary",typographyProps:{color:"white",variant:"button_secondary"},onClick:Xr,buttonPadding:"small",children:[ro("dyn_login.mobile_wallet_redirect.open_prompt")," ",eo==null?void 0:eo.name]}),jsxRuntimeExports.jsx(Alert,{variant:"info",className:"mobile-wallet-redirect__alert",icon:jsxRuntimeExports.jsx(SvgFooterInfoIcon,{}),children:ro("dyn_login.mobile_wallet_redirect.redirect_fail_message",{walletName:eo==null?void 0:eo.name})}),no&&jsxRuntimeExports.jsxs("div",{className:"mobile-wallet-redirect__wallet-app",onClick:oo,children:[jsxRuntimeExports.jsxs("div",{className:"mobile-wallet-redirect__wallet-app__group",children:[ao(26),jsxRuntimeExports.jsxs(Typography,{variant:"body_small",weight:"bold",children:[ro("dyn_login.mobile_wallet_redirect.get_app_prompt")," ",eo==null?void 0:eo.name]})]}),jsxRuntimeExports.jsxs("div",{className:"mobile-wallet-redirect__wallet-app__group",children:[jsxRuntimeExports.jsx(Typography,{className:"mobile-wallet-redirect__wallet-app__group__app-store",variant:"body_small",weight:"bold",color:"secondary",children:no}),jsxRuntimeExports.jsx(Icon,{color:"text-secondary",size:"small",children:jsxRuntimeExports.jsx(SvgExternalLink,{})})]})]})]})},useWalletConnectorEvent=(Xr,eo,to)=>{const ro=reactExports.useRef(to);ro.current=to,reactExports.useEffect(()=>{if(!Xr)return;const no=Array.isArray(Xr)?Xr:[Xr];no.forEach(ao=>ao.initEventListener());const oo=Array.from(new Set(no)).map(ao=>{const so=(...co)=>{ro.current(...co,ao)};return ao.on(eo,so),()=>ao.off(eo,so)});return()=>oo.forEach(ao=>ao())},[Xr,eo])},useWalletConnectorNetwork=(Xr,{onChange:eo}={onChange:()=>{}})=>{const[to,ro]=reactExports.useState(),{isLoading:no}=usePromise(()=>Xr==null?void 0:Xr.getNetwork(),{deps:[Xr],onResolve:io=>{ro(io)}});return useWalletConnectorEvent(Xr||void 0,"chainChange",({chain:io})=>{const oo=(Xr==null?void 0:Xr.connectedChain)==="STARK"?io:parseInt(io);ro(oo),eo==null||eo(oo)}),useWalletConnectorEvent(Xr||void 0,"disconnect",()=>__awaiter$j(void 0,void 0,void 0,function*(){if((Xr==null?void 0:Xr.key)!=="argentx")return;const io=yield Xr.getNetwork();ro(io),eo==null||eo(io)})),{isLoading:no,network:to}},useNetworkNotSupported=()=>{const{selectedWalletConnector:Xr,setShowAuthFlow:eo,bridgeChainsToConnect:to,bridgeOnboardingCompleted:ro,isBridgeFlow:no,user:io,authMode:oo}=useInternalDynamicContext(),ao=useConnectAndSign({shouldCallCallback:!1,shouldUpdateWallets:!!(to!=null&&to.length)}),{network:so}=useWalletConnectorNetwork(Xr,{onChange:co=>{!Xr||!isSupportedNetwork({network:co,walletConnector:Xr})||ao({walletConnector:Xr}).then(()=>{!io&&oo==="connect-and-sign"||(!no||ro||!(to!=null&&to.length))&&eo(!1)})}});return{currentNetwork:so}},UserAddress=({userProfile:Xr,walletConnector:eo})=>{var to;const ro=(to=Xr==null?void 0:Xr.verifiedCredentials.find(oo=>oo.id===Xr.lastVerifiedCredentialId))===null||to===void 0?void 0:to.address,no=useFetchNameService(ro),{data:io}=usePromise(()=>eo==null?void 0:eo.getAddress(),{enabled:!Xr&&!!eo});return jsxRuntimeExports.jsxs("div",{className:"user-address__container",children:[jsxRuntimeExports.jsx(StatusDot,{variant:"green",containerClassName:"user-address__status-dot"}),no!=null&&no.name?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Typography,{variant:"numbers_big",color:"primary",className:"user-address",children:no.name}),jsxRuntimeExports.jsx("div",{className:"dynamic-widget-wallet-header__seperator"}),jsxRuntimeExports.jsx(Typography,{variant:"numbers_medium",color:"secondary",className:"user-address",children:shortenWalletAddress(ro,3,3)})]}):jsxRuntimeExports.jsx(Typography,{variant:"numbers_big",color:"primary",className:"user-address",children:shortenWalletAddress(ro||io,4,4)})]})},SelectNetworkButton=({networkId:Xr,networkName:eo,networkIconUrl:to,onClick:ro})=>{const no=jsxRuntimeExports.jsx("img",{alt:eo,className:"select-network-button__icon",src:to});return jsxRuntimeExports.jsxs(TypographyButton,{dataTestId:"SelectNetworkButton",onClick:()=>ro(Xr),expanded:!0,className:"select-network-button",children:["Select",no,eo," network"]})},NetworkNotSupported=()=>{const{onboardingImageUrl:Xr,selectedWalletConnector:eo}=useInternalDynamicContext(),{t:to}=useTranslation(),{currentNetwork:ro}=useNetworkNotSupported(),[no,io]=reactExports.useState(!1);if(!eo)return null;const oo=co=>__awaiter$j(void 0,void 0,void 0,function*(){try{yield eo.switchNetwork({networkChainId:co})}catch(lo){logger$8.debug(lo)}}),ao=eo.evmNetworks||[],so=isSupportedNetwork({network:ro,walletConnector:eo});return jsxRuntimeExports.jsxs("div",{className:"network-not-supported","data-testid":"network-not-supported",children:[Xr&&jsxRuntimeExports.jsx("img",{className:"network-not-supported__main-img",src:Xr,alt:"onboarding"}),!so&&jsxRuntimeExports.jsx(ErrorContainer,{variant:"info",withIcon:!1,className:"network-not-supported__error--not-supported",copykey:"dyn_network_not_supported.warning_message",children:to("dyn_network_not_supported.warning_message")}),jsxRuntimeExports.jsxs("div",{className:classNames("network-not-supported__content-container",{"network-not-supported__content-container--error":!so}),children:[jsxRuntimeExports.jsx("div",{className:"network-not-supported__img-container",children:jsxRuntimeExports.jsx(WalletIcon,{style:{height:64,width:64},walletKey:eo.key})}),jsxRuntimeExports.jsx(UserAddress,{walletConnector:eo}),jsxRuntimeExports.jsx("div",{className:"network-not-supported__network-container",children:ao.length>1&&jsxRuntimeExports.jsx(NetworkPicker,{currentNetwork:ro,evmNetworks:ao,connector:eo,isNetworkPickerOpen:no,setIsNetworkPickerOpen:io,showNetworkName:!0,buttonClassName:"network-not-supported__network-picker-button",mainClassName:"network-not-supported__network-picker"})}),jsxRuntimeExports.jsx("div",{className:"network-not-supported__welcome-container",children:jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",copykey:"dyn_network_not_supported.subtitle",children:to("dyn_network_not_supported.subtitle")})}),ao.length===1&&jsxRuntimeExports.jsx(SelectNetworkButton,{onClick:oo,networkId:ao[0].networkId,networkName:ao[0].vanityName||ao[0].name,networkIconUrl:ao[0].iconUrls[0]})]})]})},NetworkNotSupportedSwitchManual=()=>{const{selectedWalletConnector:Xr}=useInternalDynamicContext();useNetworkNotSupported();const{t:eo}=useTranslation(),to=80,ro=jsxRuntimeExports.jsx(WalletIcon,{walletKey:Xr==null?void 0:Xr.key,style:{height:pixelToRem(to*iconRatio),width:pixelToRem(to*iconRatio)}}),no=getWalletConnectorNetworks(Xr),io=()=>(Xr==null?void 0:Xr.key)==="metamaskstarknet"?"dyn_network_not_supported_manual_switch.subtitle_network_defined_metamaskstarknet":no.length?"dyn_network_not_supported_manual_switch.subtitle_network_defined":"dyn_network_not_supported_manual_switch.subtitle_no_network_defined",oo=()=>(Xr==null?void 0:Xr.key)==="metamaskstarknet"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[eo("dyn_network_not_supported_manual_switch.subtitle_network_defined_metamaskstarknet",{network:no[0].name}),jsxRuntimeExports.jsxs("a",{href:"https://snaps.consensys.io/starknet",target:"_blank",rel:"noreferrer",children:[" ",eo("dyn_network_not_supported_manual_switch.subtitle_network_defined_metamaskstarknet_companion_app")," ",jsxRuntimeExports.jsx(SvgExternalLink,{style:{display:"inline-block"}})]})]}):no.length?eo("dyn_network_not_supported_manual_switch.subtitle_network_defined",{network:no[0].name}):eo("dyn_network_not_supported_manual_switch.subtitle_no_network_defined");return jsxRuntimeExports.jsxs("div",{"data-testid":"network-not-supported",className:"network-not-supported-switch-manual",children:[jsxRuntimeExports.jsx("div",{className:"network-not-supported-switch-manual__img-container",children:jsxRuntimeExports.jsx("div",{className:"network-not-supported-switch-manual__network-container",children:jsxRuntimeExports.jsx(IconWithSpinner,{Icon:ro,iconSize:to,isSpinning:!0})})}),jsxRuntimeExports.jsxs("div",{className:"network-not-supported-switch-manual__content",children:[jsxRuntimeExports.jsx(Typography,{className:"network-not-supported-switch-manual__title",weight:"medium",variant:"title",color:"primary",copykey:"dyn_network_not_supported_manual_switch.title",children:eo("dyn_network_not_supported_manual_switch.title")}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"secondary",copykey:io(),children:oo()})]})]})},socialNetworkIconMap={discord:DiscordIcon,helpdesk:HelpdeskIcon,slack:SlackIcon,twitter:TwitterIcon},getSocialNetworkIcon=Xr=>socialNetworkIconMap[Xr],useNoAccessText=()=>{const{socialMediaLinkText:Xr,socialMediaUrl:eo,accessDeniedMessagePrimary:to,accessDeniedMessageSecondary:ro}=useInternalDynamicContext(),{view:no}=useViewContext(),{t:io}=useTranslation(),oo=no.type==="chainalysis-blocked-wallet",ao=no.type==="gate-blocked-wallet",so=no.type==="no-access",co=()=>{if(oo)return io(textData.chainalysis._socialMediaLinkText);if(!ao)return Xr},lo=()=>{if(oo)return io(textData.chainalysis._socialMediaUrl);if(!ao)return eo},fo=()=>oo?io(textData.chainalysis.title):ao?io(textData.gate.title):to||io(textData.default.title),ho=()=>oo?io(textData.chainalysis.subtitle):ao?io(textData.gate.subtitle):ro||io(textData.default.subtitle),go=()=>io(oo?textData.chainalysis.buttonTitle:ao?textData.gate.buttonTitle:textData.default.buttonTitle);return{_socialMediaLinkText:co(),_socialMediaUrl:lo(),buttonTitle:go(),isAccessListView:so,isChainalysisView:oo,isGateBlockedView:ao,subtitle:ho(),title:fo()}},textData={chainalysis:{_socialMediaLinkText:"dyn_no_access.chainalysis.social_media_link_text",_socialMediaUrl:"dyn_no_access.chainalysis.social_media_link_url",buttonTitle:"dyn_no_access.chainalysis.button_text",subtitle:"dyn_no_access.chainalysis.description",title:"dyn_no_access.chainalysis.title"},default:{buttonTitle:"dyn_no_access.default.button_text",subtitle:"dyn_no_access.default.description",title:"dyn_no_access.default.title"},gate:{_socialMediaLinkText:void 0,_socialMediaUrl:void 0,buttonTitle:"dyn_no_access.gate.button_text",subtitle:"dyn_no_access.gate.description",title:"dyn_no_access.gate.title"}},NoAccess=()=>{const{deniedAddress:Xr,setDeniedAddress:eo,setDeniedOauthProvider:to,deniedOauthProvider:ro,deniedOauthUsername:no}=useAccessDeniedContext(),{t:io}=useTranslation(),oo=ro?findSocialIcon(ro):void 0,{selectedWalletConnector:ao,socialMediaIconUrl:so,notInTheListImageUrl:co,accessDeniedButton:lo}=useInternalDynamicContext(),{displayedDestination:fo}=useVerification(),{goToInitialView:ho}=useViewContext(),{_socialMediaLinkText:go,_socialMediaUrl:yo,isAccessListView:vo,isGateBlockedView:wo,subtitle:Eo,title:ko,buttonTitle:Ao}=useNoAccessText(),Po=()=>{ho(),eo(""),to(void 0),ao==null||ao.endSession()},jo=!so||typeof so=="string"?null:getSocialNetworkIcon(Object.keys(so)[0]),Mo=reactExports.useMemo(()=>ao?jsxRuntimeExports.jsx(AuthProviderIcon,{}):jsxRuntimeExports.jsx(IconWithStatus,{containerClassName:"wallet-no-access__icon--verified",Icon:oo??SignInWithEmailIcon,iconSize:50,InnerIcon:SvgError,variant:"red"}),[oo,ao]),No=shortenWalletAddress(Xr,6,4),Do=(lo==null?void 0:lo.title)||Ao,Fo=(lo==null?void 0:lo.action)||Po,Lo=ro===void 0?fo??No:no,Bo=!!co&&(vo||wo),xo=jo&&(vo||wo);return jsxRuntimeExports.jsxs("div",{className:"wallet-no-access__container",children:[Bo&&jsxRuntimeExports.jsx("img",{src:co,alt:io("dyn_no_access.not_in_the_list_image_alt"),className:"wallet-no-access__image",copykey:"dyn_no_access.not_in_the_list_image_alt"}),jsxRuntimeExports.jsxs("div",{className:"wallet-no-access__main",children:[jsxRuntimeExports.jsxs("div",{className:"wallet-no-access__user-info-container",children:[Mo,jsxRuntimeExports.jsxs("div",{"data-testid":"walletAddress",className:"wallet-no-access__wallet-address-container",children:[ao&&jsxRuntimeExports.jsx(StatusDot,{variant:"red",containerClassName:"user-info__status-dot"}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"primary",weight:"medium",className:"wallet-no-access__wallet-address",children:Lo})]})]}),jsxRuntimeExports.jsxs("div",{className:"wallet-no-access__content",children:[jsxRuntimeExports.jsx(Typography,{variant:"title",color:"primary",className:"wallet-no-access__content--primary",children:ko}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"wallet-no-access__content--secondary",children:Eo})]}),jsxRuntimeExports.jsx(TypographyButton,{onClick:Fo,className:"wallet-no-access__button--primary",expanded:!0,buttonPadding:"large",children:Do}),yo&&go&&jsxRuntimeExports.jsxs("div",{className:"wallet-no-access__social-info-container",children:[jsxRuntimeExports.jsxs("a",{href:yo,className:"wallet-no-access__waitlist-link",children:[jsxRuntimeExports.jsx(Typography,{variant:"button_primary",color:"primary",children:go}),xo&&jsxRuntimeExports.jsx(jo,{className:"wallet-no-access__social-icon",style:{height:pixelToRem(24),width:pixelToRem(24)}})]}),typeof so=="string"&&jsxRuntimeExports.jsx("img",{alt:"social media",src:so,style:{height:"1.5rem",width:"1.5rem"}})]})]})]})},capitalize=Xr=>Xr[0].toUpperCase()+Xr.slice(1),WalletHelpLink=({name:Xr,link:eo,Icon:to})=>{const{t:ro}=useTranslation();return jsxRuntimeExports.jsx("div",{className:"wallet-help-link",children:jsxRuntimeExports.jsxs("a",{className:"wallet-help-link__anchor",href:eo,target:"_blank",rel:"noreferrer",children:[jsxRuntimeExports.jsx(to,{style:{height:"1.5rem",width:"1.5rem"}}),jsxRuntimeExports.jsx(Typography,{variant:"button_primary",weight:"medium",copykey:"dyn_qr_code.wallet_not_installed.browser_install",children:ro("dyn_qr_code.wallet_not_installed.browser_install",{browser:capitalize(Xr)})})]})})},NoQrNotInstalledView=()=>{const{selectedWalletConnector:Xr}=useInternalDynamicContext(),{walletBook:eo}=useWalletBookContext(),{t:to}=useTranslation();if(!Xr)return null;const ro=Object.entries(getWalletLinks(eo,Xr.key)).filter(([,no])=>no!=="").filter(([no])=>no!=="ios"&&no!=="android").map(([no,io])=>jsxRuntimeExports.jsx(WalletHelpLink,{name:no,link:io,Icon:getBrowserIcon(no)},no));return jsxRuntimeExports.jsxs("div",{className:"no-qr-code-installed__container","data-testid":"no-qr-code-installed",children:[jsxRuntimeExports.jsx("div",{className:"no-qr-code-installed__img",children:jsxRuntimeExports.jsx(WalletIcon,{walletKey:Xr.key,style:{height:pixelToRem(64),width:pixelToRem(64)}})}),jsxRuntimeExports.jsx(Typography,{className:"no-qr-code-installed__typography--title",variant:"title",copykey:"dyn_qr_code.wallet_not_installed.install",children:to("dyn_qr_code.wallet_not_installed.install",{wallet:getWalletBookWallet(eo,Xr.key).name})}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",className:"no-qr-code-installed__typography",color:"secondary",copykey:"dyn_qr_code.wallet_not_installed.select",children:to("dyn_qr_code.wallet_not_installed.select")}),jsxRuntimeExports.jsx("div",{className:"no-qr-code-installed__links-section",children:ro}),jsxRuntimeExports.jsx(Typography,{variant:"body_mini",className:"no-qr-code-installed__typography",weight:"medium",color:"secondary",copykey:"dyn_qr_code.wallet_not_installed.refresh",children:to("dyn_qr_code.wallet_not_installed.refresh")})]})};var _g$4,_defs$4,_excluded$b=["title","titleId"];function _extends$d(){return _extends$d=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$b(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgPasskeyIntro2=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$b(eo,_excluded$b);return reactExports.createElement("svg",_extends$d({width:327,height:112,viewBox:"0 0 327 112",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_g$4||(_g$4=reactExports.createElement("g",{clipPath:"url(#passkey-intro2_svg__a)"},reactExports.createElement("circle",{cx:164,cy:114,r:114,fill:"url(#passkey-intro2_svg__b)",fillOpacity:.12}),reactExports.createElement("g",{clipPath:"url(#passkey-intro2_svg__c)",fill:"#4779FF"},reactExports.createElement("path",{d:"M106.009 34.681a2.666 2.666 0 0 1 3.266 1.886l-15.454 4.141a5.319 5.319 0 0 0-3.339 2.666 5.335 5.335 0 0 1 3.936-5.587l11.591-3.106ZM117.785 42.57a5.333 5.333 0 0 0-6.532-3.772l-15.455 4.141a5.333 5.333 0 0 0-3.771 6.532l2.76 10.303a5.333 5.333 0 0 0 6.533 3.771l15.454-4.14a5.333 5.333 0 0 0 3.772-6.533l-2.761-10.303Z"})),reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m207.67 19.875-.767 2.862a9.86 9.86 0 0 0-5.861 6.61c-1.412 5.269 1.715 10.684 6.984 12.096 5.268 1.412 10.684-1.715 12.096-6.984a9.862 9.862 0 0 0-1.771-8.655l.767-2.861a5.926 5.926 0 0 0-11.448-3.068Zm9.321 2.498-.444 1.655a9.844 9.844 0 0 0-3.409-1.665 9.847 9.847 0 0 0-3.785-.262l.444-1.656a3.723 3.723 0 1 1 7.194 1.928Zm-3.445 8.52a2.57 2.57 0 0 1-2.019 1.862l-.539 2.011a1.1 1.1 0 1 1-2.127-.57l.539-2.01a2.569 2.569 0 1 1 4.146-1.294ZM164.943 32.064a6.216 6.216 0 0 0-1.779 0c-.681.098-1.314.337-1.816.527l-.135.05-16.68 6.256-.407.152c-1.922.718-3.61 1.348-4.909 2.493a9.325 9.325 0 0 0-2.553 3.683c-.616 1.62-.613 3.421-.61 5.473V66.01c0 8.793 4.783 16.125 9.953 21.51 5.204 5.422 11.159 9.252 14.307 11.089l.128.075c.574.337 1.32.775 2.307.987a6.619 6.619 0 0 0 2.609 0c.987-.212 1.732-.65 2.307-.987l.128-.075c3.148-1.837 9.103-5.667 14.307-11.088 5.17-5.386 9.953-12.718 9.953-21.511V50.698c.003-2.052.006-3.854-.611-5.473a9.333 9.333 0 0 0-2.552-3.683c-1.3-1.145-2.987-1.775-4.909-2.493l-.407-.152-16.68-6.255-.135-.05c-.503-.19-1.136-.43-1.816-.528Zm-1.34 14.592a15.89 15.89 0 0 0-7.978 2.135 1.772 1.772 0 0 0 1.775 3.069 12.347 12.347 0 0 1 6.203-1.66c6.853 0 12.408 5.556 12.408 12.409a44.34 44.34 0 0 1-1.688 12.156 1.772 1.772 0 1 0 3.41.97 47.883 47.883 0 0 0 1.823-13.126c0-8.81-7.142-15.953-15.953-15.953Zm-10.749 9.75a1.772 1.772 0 1 0-3.069-1.775 15.891 15.891 0 0 0-2.135 7.978c0 2.499-.573 4.86-1.594 6.96a1.772 1.772 0 1 0 3.189 1.55 19.43 19.43 0 0 0 1.95-8.51c0-2.263.604-4.38 1.659-6.203Zm10.749-2.66a8.863 8.863 0 0 0-8.863 8.863c0 4.516-1.29 8.704-3.518 12.246l1.5.944-1.5-.944-.121.196a1.774 1.774 0 0 0 3.049 1.81 26.434 26.434 0 0 0 4.135-14.253 5.318 5.318 0 0 1 10.636 0c0 1.723-.118 3.418-.345 5.078a1.773 1.773 0 0 0 3.513.48 41.12 41.12 0 0 0 .377-5.557 8.863 8.863 0 0 0-8.863-8.863Zm1.772 8.863a1.772 1.772 0 1 0-3.545 0c0 5.89-1.688 11.381-4.607 16.021a1.773 1.773 0 0 0 3.001 1.888 33.528 33.528 0 0 0 5.151-17.91Zm5.554 11.117a1.773 1.773 0 0 0-3.411-.965 37.01 37.01 0 0 1-2.523 6.502 1.771 1.771 0 1 0 3.169 1.588 40.517 40.517 0 0 0 2.765-7.124Z",fill:"#4779FF"}))),_defs$4||(_defs$4=reactExports.createElement("defs",null,reactExports.createElement("clipPath",{id:"passkey-intro2_svg__a"},reactExports.createElement("rect",{width:327,height:112,rx:12,fill:"#fff"})),reactExports.createElement("clipPath",{id:"passkey-intro2_svg__c"},reactExports.createElement("path",{fill:"#fff",transform:"rotate(-15 184.593 -307.976)",d:"M0 0h32v32H0z"})),reactExports.createElement("linearGradient",{id:"passkey-intro2_svg__b",x1:164,y1:0,x2:164,y2:93.5,gradientUnits:"userSpaceOnUse"},reactExports.createElement("stop",{stopColor:"#4779FF"}),reactExports.createElement("stop",{offset:1,stopColor:"#4779FF",stopOpacity:0})))))},_path$7,_path2,_path3,_excluded$a=["title","titleId"];function _extends$c(){return _extends$c=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$a(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgAndroidFaceId=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$a(eo,_excluded$a);return reactExports.createElement("svg",_extends$c({width:64,height:64,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_path$7||(_path$7=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32 57.887c14.297 0 25.887-11.59 25.887-25.887S46.297 6.113 32 6.113 6.113 17.703 6.113 32 17.703 57.887 32 57.887ZM32 60c15.464 0 28-12.536 28-28S47.464 4 32 4 4 16.536 4 32s12.536 28 28 28Z",fill:"#1A73E8"})),_path2||(_path2=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M36.752 46.831c.27.582.018 1.274-.565 1.544-2.69 1.25-5.356 1.479-7.54.476-2.215-1.017-3.66-3.173-4.134-6.099l2.295-.372c.383 2.364 1.466 3.742 2.809 4.359 1.374.63 3.299.592 5.591-.472a1.162 1.162 0 0 1 1.544.564ZM33.585 35.17v-4.755h2.113v6.868h-5.811V35.17h3.698Z",fill:"#1A73E8"})),_path3||(_path3=reactExports.createElement("path",{d:"M46.792 25.132a2.113 2.113 0 1 1-4.226 0 2.113 2.113 0 0 1 4.226 0ZM21.434 25.132a2.113 2.113 0 1 1-4.227 0 2.113 2.113 0 0 1 4.227 0Z",fill:"#1A73E8"})))},_path$6,_excluded$9=["title","titleId"];function _extends$b(){return _extends$b=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$9(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgAndroidTouchId=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$9(eo,_excluded$9);return reactExports.createElement("svg",_extends$b({width:64,height:64,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_path$6||(_path$6=reactExports.createElement("path",{d:"M47.493 11.92c-.213 0-.426-.053-.613-.16C41.76 9.12 37.333 8 32.027 8c-5.28 0-10.294 1.253-14.854 3.76-.64.347-1.44.107-1.813-.533a1.35 1.35 0 0 1 .533-1.814c4.96-2.693 10.4-4.08 16.134-4.08 5.68 0 10.64 1.254 16.08 4.054.666.346.906 1.146.56 1.786-.24.48-.694.747-1.174.747Zm-38.16 14a1.33 1.33 0 0 1-1.093-2.107c2.64-3.733 6-6.666 10-8.72 8.373-4.32 19.093-4.346 27.493-.026 4 2.053 7.36 4.96 10 8.666.427.587.294 1.44-.32 1.867a1.33 1.33 0 0 1-1.866-.32c-2.4-3.36-5.44-6-9.04-7.84-7.654-3.92-17.44-3.92-25.067.027-3.627 1.866-6.667 4.533-9.067 7.893-.213.373-.613.56-1.04.56ZM26 58.107c-.347 0-.693-.134-.933-.4-2.32-2.32-3.574-3.814-5.36-7.04-1.84-3.28-2.8-7.28-2.8-11.574 0-7.92 6.773-14.373 15.093-14.373s15.093 6.453 15.093 14.373a1.32 1.32 0 0 1-1.333 1.334 1.32 1.32 0 0 1-1.333-1.334c0-6.453-5.574-11.706-12.427-11.706S19.573 32.64 19.573 39.093c0 3.84.854 7.387 2.48 10.267 1.707 3.067 2.88 4.373 4.934 6.453a1.37 1.37 0 0 1 0 1.894c-.294.266-.64.4-.987.4Zm19.12-4.934c-3.173 0-5.973-.8-8.267-2.373-3.973-2.693-6.346-7.067-6.346-11.707a1.32 1.32 0 0 1 1.333-1.333 1.32 1.32 0 0 1 1.333 1.333c0 3.76 1.92 7.307 5.174 9.494 1.893 1.28 4.106 1.893 6.773 1.893.64 0 1.707-.08 2.773-.267a1.33 1.33 0 0 1 1.547 1.094 1.33 1.33 0 0 1-1.093 1.546c-1.52.294-2.854.32-3.227.32Zm-5.36 5.494a1.56 1.56 0 0 1-.347-.054c-4.24-1.173-7.013-2.746-9.92-5.6-3.733-3.706-5.786-8.64-5.786-13.92 0-4.32 3.68-7.84 8.213-7.84 4.533 0 8.213 3.52 8.213 7.84 0 2.854 2.48 5.174 5.547 5.174 3.067 0 5.547-2.32 5.547-5.174 0-10.053-8.667-18.213-19.334-18.213-7.573 0-14.506 4.213-17.626 10.747-1.04 2.16-1.574 4.693-1.574 7.466 0 2.08.187 5.36 1.787 9.627a1.301 1.301 0 0 1-.773 1.707A1.323 1.323 0 0 1 12 49.653c-1.307-3.493-1.947-6.96-1.947-10.56 0-3.2.614-6.106 1.814-8.64 3.546-7.44 11.413-12.266 20.026-12.266 12.134 0 22 9.36 22 20.88 0 4.32-3.68 7.84-8.213 7.84-4.533 0-8.213-3.52-8.213-7.84 0-2.854-2.48-5.174-5.547-5.174-3.067 0-5.547 2.32-5.547 5.174 0 4.56 1.76 8.826 4.987 12.026 2.533 2.507 4.96 3.894 8.72 4.934.72.186 1.12.933.933 1.626a1.301 1.301 0 0 1-1.253 1.014Z",fill:"#1A73E8"})))},_path$5,_excluded$8=["title","titleId"];function _extends$a(){return _extends$a=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$8(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgFaceId=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$8(eo,_excluded$8);return reactExports.createElement("svg",_extends$a({width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_path$5||(_path$5=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M18.055 2.4A3.548 3.548 0 0 1 21.6 5.945v2.013a1.095 1.095 0 0 1-2.19 0V5.945c0-.747-.608-1.355-1.355-1.355h-2.012a1.095 1.095 0 1 1 0-2.19h2.012Zm-10.098 0a1.095 1.095 0 0 1 0 2.19H5.945c-.747 0-1.355.608-1.355 1.355v2.013a1.095 1.095 0 0 1-2.19 0V5.945A3.548 3.548 0 0 1 5.945 2.4h2.012Zm7.692 5.083c.6 0 1.086.486 1.086 1.086v1.347a1.086 1.086 0 1 1-2.172 0V8.57c0-.6.486-1.086 1.086-1.086Zm-4.121 0c.614 0 1.112.498 1.112 1.112v2.982h.008a1.113 1.113 0 0 1 0 2.226h-.386a1.849 1.849 0 0 1-1.847-1.848v-3.36c0-.614.498-1.112 1.113-1.112Zm-3.282 0c.6 0 1.086.486 1.086 1.086v1.347a1.086 1.086 0 0 1-2.172 0V8.57c0-.6.486-1.086 1.086-1.086Zm12.259 7.465c.605 0 1.095.49 1.095 1.095v2.012a3.548 3.548 0 0 1-3.545 3.545h-2.012a1.095 1.095 0 1 1 0-2.19h2.012c.747 0 1.355-.608 1.355-1.355v-2.012c0-.605.49-1.095 1.095-1.095Zm-17.01 0c.605 0 1.095.49 1.095 1.095v2.012c0 .747.608 1.355 1.355 1.355h2.012a1.095 1.095 0 0 1 0 2.19H5.945A3.548 3.548 0 0 1 2.4 18.055v-2.012c0-.605.49-1.095 1.095-1.095Zm5.365 1.337a.473.473 0 0 0 0 0l-.434.47a1.113 1.113 0 0 1 1.51-1.634c.563.52 1.296.806 2.064.806s1.5-.286 2.065-.807a1.113 1.113 0 0 1 1.51 1.634A5.255 5.255 0 0 1 12 18.153a5.255 5.255 0 0 1-3.574-1.397l.434-.47a4.615 4.615 0 0 1 0 0Zm5.947.28a4.694 4.694 0 0 1 0 0Z",fill:"#ABACB2"})))},_g$3,_defs$3,_excluded$7=["title","titleId"];function _extends$9(){return _extends$9=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$7(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgIphoneTouchId=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$7(eo,_excluded$7);return reactExports.createElement("svg",_extends$9({width:64,height:64,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_g$3||(_g$3=reactExports.createElement("g",{clipPath:"url(#iphone-touch-id_svg__a)",fill:"#000"},reactExports.createElement("path",{d:"M38.635.943c-4.483-1.118-9.2-1.278-13.79-.287a.657.657 0 0 0 .277 1.285c4.396-.95 8.924-.793 13.232.287 10.3 2.582 18.875 10.327 22.14 20.444 1.264 3.912 1.8 8.078 1.908 12.445a.657.657 0 0 0 1.313-.033c-.108-4.426-.651-8.7-1.945-12.74C58.378 11.75 49.417 3.632 38.635.943ZM21.51 2.932a.657.657 0 1 0-.35-1.267c-4.801 1.324-11.554 5.9-15.728 12.014a.754.754 0 0 0-.004.007C1.763 19.208-.534 26.148.108 32.883l.001.019c.154 1.23.412 2.457.67 3.686.544 2.588 1.09 5.183.665 7.818a.657.657 0 1 0 1.297.21c.445-2.755-.107-5.443-.66-8.13-.254-1.244-.51-2.487-.666-3.737-.604-6.364 1.57-13.002 5.105-18.333 4.015-5.879 10.516-10.25 14.99-11.484Z"}),reactExports.createElement("path",{d:"M30.133 4.4c8.25-.504 16.499 2.863 22.039 9.314a.657.657 0 1 1-.997.856c-5.268-6.134-13.118-9.339-20.966-8.858H30.2c-9.925.48-19.22 7.214-22.638 16.648a.657.657 0 1 1-1.236-.447C9.928 11.973 19.688 4.907 30.133 4.4ZM54.174 16.585a.657.657 0 0 0-1.091.733c3.07 4.572 4.34 9.548 4.843 15.454a.657.657 0 0 0 1.31-.112c-.514-6.034-1.823-11.252-5.062-16.075ZM58.796 35.45a.657.657 0 0 1 .697.615c.247 3.963.25 8.446-.189 11.76a.657.657 0 1 1-1.303-.173c.423-3.193.425-7.582.18-11.505a.657.657 0 0 1 .615-.697ZM6.57 25.543a.657.657 0 1 0-1.278-.308 26.58 26.58 0 0 0-.743 6.104c-.01 2.117.385 4.184.78 6.25.323 1.692.646 3.384.747 5.104.134 2.26-.341 4.523-1.163 6.677a.657.657 0 1 0 1.228.469c.868-2.277 1.395-4.73 1.247-7.223-.1-1.709-.424-3.39-.747-5.072-.394-2.051-.788-4.102-.778-6.199.01-1.952.248-3.902.706-5.802Z"}),reactExports.createElement("path",{d:"M23.813 10.94a.657.657 0 0 1-.365.855c-6.813 2.736-11.93 8.91-12.973 16.19-.436 3.042.035 6.055.506 9.067.265 1.696.53 3.392.634 5.093.223 3.688-.197 7.739-2.597 11.425a.657.657 0 0 1-1.101-.718c2.186-3.358 2.6-7.088 2.386-10.627-.105-1.726-.368-3.442-.632-5.156-.472-3.077-.944-6.15-.497-9.27 1.115-7.774 6.563-14.324 13.784-17.224a.657.657 0 0 1 .855.365ZM46.882 14.681c-5.374-5.034-13.164-6.79-20.244-5.238a.657.657 0 1 0 .282 1.284c6.704-1.47 14.039.207 19.064 4.914 4.235 3.967 6.695 9.739 7.339 16.037a.657.657 0 0 0 1.307-.134c-.668-6.54-3.232-12.633-7.748-16.863ZM54.493 34.674a.657.657 0 0 1 .72.586c.625 6.077.356 12.64-.587 18.99a.657.657 0 0 1-1.3-.193c.93-6.261 1.191-12.713.58-18.662a.657.657 0 0 1 .587-.721Z"}),reactExports.createElement("path",{d:"M31.582 13.355c-10.07 0-18.252 8.034-18.252 17.967 0 1.06.094 2.1.274 3.111a.657.657 0 0 0 1.294-.23 16.469 16.469 0 0 1-.254-2.881c0-9.187 7.574-16.652 16.938-16.652 4.232 0 8.098 1.525 11.066 4.045a.657.657 0 0 0 .85-1.002 18.353 18.353 0 0 0-11.916-4.358ZM44.971 20.163a.657.657 0 0 1 .93.02c2.9 3.024 3.828 7.777 4.442 11.766.692 4.494.798 8.877.798 10.91a.657.657 0 0 1-1.315 0c0-2-.104-6.31-.782-10.71-.57-3.703-1.392-8.24-4.092-11.056a.657.657 0 0 1 .02-.93ZM50.974 46.622a.657.657 0 0 0-1.31-.105c-.323 4.048-.745 8.092-1.6 11.827a.657.657 0 1 0 1.28.293c.879-3.833 1.306-7.956 1.63-12.015ZM14.662 36.852a.657.657 0 0 1 .771.518c1.39 7.056.43 13.466-3.25 19.08a.657.657 0 0 1-1.099-.72c3.462-5.283 4.394-11.331 3.06-18.106a.657.657 0 0 1 .518-.772Z"}),reactExports.createElement("path",{d:"M31.582 17.631c-6.537 0-12.95 5.06-13.604 11.42-.287 2.784.116 5.526.519 8.27.351 2.395.703 4.791.596 7.217-.244 5.552-1.873 10.135-4.672 13.91a.657.657 0 1 0 1.056.782c2.968-4.003 4.674-8.844 4.93-14.634.106-2.415-.247-4.804-.6-7.19-.403-2.73-.806-5.459-.521-8.221.574-5.587 6.325-10.24 12.296-10.24 2.785 0 9.991 1.508 12.283 8.976 1.437 4.679 1.828 11.012 1.48 17.164-.347 6.151-1.43 12.035-2.885 15.808a.657.657 0 0 0 1.227.473c1.522-3.947 2.619-9.98 2.97-16.207.353-6.226-.034-12.734-1.535-17.624-2.545-8.289-10.52-9.904-13.54-9.904Z"}),reactExports.createElement("path",{d:"M21.47 56.451c.303.198.389.606.19.91-.407.624-.765 1.278-1.124 1.932-.359.654-.717 1.307-1.125 1.932a.657.657 0 1 1-1.1-.718c.407-.624.765-1.278 1.124-1.932.359-.654.717-1.308 1.125-1.932a.657.657 0 0 1 .91-.192ZM27.096 24.453a.657.657 0 1 0-.73-1.093c-2.603 1.74-4.2 4.134-4.2 7.64 0 2.088.37 3.795.75 5.545.567 2.62.953 5.233.883 7.923-.084 3.267-.723 6.252-1.952 9.096a.657.657 0 1 0 1.207.521c1.299-3.007 1.971-6.158 2.06-9.583.071-2.796-.325-5.513-.913-8.235-.38-1.758-.72-3.328-.72-5.267 0-3.004 1.321-5.013 3.615-6.547ZM29.66 22.144c2.728-.556 5.662.13 7.822 1.879 3.858 3.122 4.371 8.817 4.787 13.432l.021.235c.538 5.949-.077 11.726-1.316 17.529a.657.657 0 1 1-1.286-.275c1.22-5.715 1.815-11.355 1.293-17.136l-.052-.582v-.002c-.37-4.17-.832-9.394-4.274-12.18-1.846-1.494-4.379-2.092-6.732-1.613a.657.657 0 1 1-.262-1.287ZM40.045 58.489a.657.657 0 1 0-1.274-.325 15.88 15.88 0 0 1-1.785 4.266.657.657 0 1 0 1.127.675 17.188 17.188 0 0 0 1.932-4.616ZM36.831 48.952c.36.043.618.37.576.73-.62 5.245-2.022 9.922-4.27 13.98a.657.657 0 0 1-1.15-.638c2.152-3.882 3.51-8.39 4.115-13.496a.657.657 0 0 1 .73-.576Z"}),reactExports.createElement("path",{d:"M36.696 30.656c-.456-2.435-2.545-4.297-5.081-4.297-3.435 0-5.845 3.462-4.996 6.683 1.437 5.686 1.673 11.166.7 16.444v.003c-.845 4.739-2.465 9.002-4.677 12.614a.657.657 0 0 0 1.121.686c2.302-3.76 3.978-8.178 4.85-13.067 1.01-5.482.759-11.154-.72-17.005l-.002-.007c-.637-2.41 1.138-5.037 3.724-5.037 1.865 0 3.44 1.373 3.788 3.22.957 5.548 1.455 10.693 1.1 15.123a.657.657 0 1 0 1.31.105c.368-4.592-.151-9.863-1.115-15.456l-.002-.01ZM29.654 59.117c.323.166.45.562.284.885l-1.741 3.389a.657.657 0 1 1-1.17-.601L28.77 59.4a.657.657 0 0 1 .885-.284Z"}),reactExports.createElement("path",{d:"M32.103 31.29a.657.657 0 1 0-1.28.3c2.217 9.433 1.913 17.717-.787 24.773a.657.657 0 1 0 1.228.47c2.814-7.358 3.1-15.919.84-25.544Z"}))),_defs$3||(_defs$3=reactExports.createElement("defs",null,reactExports.createElement("clipPath",{id:"iphone-touch-id_svg__a"},reactExports.createElement("path",{fill:"#fff",d:"M0 0h64v64H0z"})))))};const PasskeyDeviceIcon=({defaultIcon:Xr,className:eo,size:to="small"})=>{let ro=Xr||null;if(isIPhone()&&(isIPhone8OrEarlier()?ro=jsxRuntimeExports.jsx(SvgIphoneTouchId,{"data-testid":"iphone-8-icon"}):ro=jsxRuntimeExports.jsx(SvgFaceId,{"data-testid":"iphone-icon"})),isAndroid$1()){const no=getAndroidVersion();no&&no>=9?ro=jsxRuntimeExports.jsx(SvgAndroidTouchId,{"data-testid":"android-9-icon"}):ro=jsxRuntimeExports.jsx(SvgAndroidFaceId,{"data-testid":"android-icon"})}return ro?jsxRuntimeExports.jsx(Icon,{className:eo,size:to,children:ro}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{})},AuthChoiceInfo=({choice:Xr,variant:eo="default"})=>{const{t:to}=useTranslation(),ro={passkey:{default:[{description:"dyn_embedded_authenticator.passkey.auth_info.convinience.description",title:"dyn_embedded_authenticator.passkey.auth_info.convinience.title"},{description:"dyn_embedded_authenticator.passkey.auth_info.security.description",title:"dyn_embedded_authenticator.passkey.auth_info.security.title"}],noEmailSignup:[{description:"dyn_embedded_authenticator.passkey.no_email_auth_info.convinience.description",title:"dyn_embedded_authenticator.passkey.no_email_auth_info.convinience.title"},{description:"dyn_embedded_authenticator.passkey.no_email_auth_info.security.description",title:"dyn_embedded_authenticator.passkey.no_email_auth_info.security.title"}]}};return jsxRuntimeExports.jsx("div",{className:"auth-choice-info",children:ro[Xr][eo].map((no,io)=>jsxRuntimeExports.jsxs("div",{className:"auth-choice-info__container-item",children:[jsxRuntimeExports.jsx("div",{className:"auth-choice-info__container-icon",children:jsxRuntimeExports.jsx(Icon,{size:"medium",className:"auth-choice-info__icon",children:jsxRuntimeExports.jsx(SvgAdd,{})})}),jsxRuntimeExports.jsxs("div",{className:"action-card__item-title",children:[jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",copykey:no.title,children:to(no.title)}),jsxRuntimeExports.jsx(Typography,{variant:"body_small",weight:"regular",color:"secondary",copykey:no.description,children:to(no.description)})]})]},`authChoiceInfo_${io}`))})},PasskeyIntroView=({chains:Xr})=>{var eo;const{walletConnectorOptions:to,environmentId:ro,handleLogOut:no,user:io,userWithMissingInfo:oo}=useInternalDynamicContext(),ao=((eo=io==null?void 0:io.verifiedCredentials)===null||eo===void 0?void 0:eo.length)===1&&!getUserVerifiedCredentialType(io,JwtVerifiedCredentialFormatEnum.Email),{t:so}=useTranslation(),[co,lo]=reactExports.useState(!1);reactExports.useEffect(()=>StorageService.removeItem(LAST_USED_WALLET),[]);const{createDynamicEmbeddedWalletMutation:fo,isLoading:ho,error:go}=useCreateDynamicEmbeddedWalletMutation(),yo=wo=>__awaiter$j(void 0,void 0,void 0,function*(){if(!io&&!oo)throw new Error("User is not logged in");lo(wo),yield fo({chains:Xr,environmentId:ro,walletConnectorOptions:to,withAuthenticator:wo})}),vo=reactExports.useMemo(()=>{if(go)return go instanceof DynamicError?go.message:getProperErrorMessage(go)},[go]);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalHeader,{children:jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary","data-testid":"dynamic-auth-modal-heading",className:"header__typography",copykey:"dyn_passkey_intro.title",children:so("dyn_passkey_intro.title")})}),jsxRuntimeExports.jsxs("div",{className:"passkey-intro-view",children:[jsxRuntimeExports.jsx("div",{className:"passkey-intro-view__header",children:jsxRuntimeExports.jsx(SvgPasskeyIntro2,{})}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"passkey-intro-view__subtitle",copykey:"dyn_passkey_intro.subtitle",children:so("dyn_passkey_intro.subtitle")}),vo&&jsxRuntimeExports.jsx(ErrorContainer,{children:vo}),jsxRuntimeExports.jsx(AuthChoiceInfo,{choice:"passkey",variant:ao?"noEmailSignup":"default"}),jsxRuntimeExports.jsxs("div",{className:"passkey-intro-view__actions",children:[jsxRuntimeExports.jsx(TypographyButton,{buttonVariant:"brand-primary",buttonPadding:"large",onClick:()=>yo(!0),dataTestId:"setup-passkey-button",loading:ho&&co,disabled:ho,typographyProps:{color:"inherit"},children:jsxRuntimeExports.jsxs("div",{className:"passkey-intro-view__inline-button",children:[jsxRuntimeExports.jsx(PasskeyDeviceIcon,{size:"small"}),jsxRuntimeExports.jsx(Typography,{copykey:"dyn_passkey_intro.button",children:so("dyn_passkey_intro.button")})]})}),jsxRuntimeExports.jsx(TextButton,{"data-testid":"setup-passkey-logout-button",className:"passkey-intro-view__log-out",onClick:no,copykey:"dyn_passkey_intro.button_logout",children:so("dyn_passkey_intro.button_logout")})]})]})]})};var _circle$1,_path$4,_g$2,_defs$2,_excluded$6=["title","titleId"];function _extends$8(){return _extends$8=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$6(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgPasskeyIntroIcon=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$6(eo,_excluded$6);return reactExports.createElement("svg",_extends$8({width:206,height:206,viewBox:"0 0 206 206",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_circle$1||(_circle$1=reactExports.createElement("circle",{cx:103,cy:103,r:103,fill:"url(#passkey-intro-icon_svg__a)",fillOpacity:.12})),_path$4||(_path$4=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M101.59 42.066a6.37 6.37 0 0 1 1.822 0c.696.1 1.343.345 1.858.54l.138.051 17.072 6.402.416.156c1.967.734 3.695 1.38 5.025 2.551a9.553 9.553 0 0 1 2.612 3.77c.631 1.657.628 3.501.625 5.6v15.672c0 9-4.895 16.504-10.187 22.016-5.326 5.55-11.421 9.469-14.643 11.349l-.131.077c-.588.345-1.351.793-2.361 1.01a6.78 6.78 0 0 1-2.67 0c-1.01-.217-1.774-.665-2.362-1.01l-.13-.077c-3.223-1.88-9.317-5.799-14.644-11.349-5.291-5.512-10.186-13.015-10.186-22.016V61.137c-.003-2.1-.006-3.944.625-5.601a9.553 9.553 0 0 1 2.612-3.77c1.33-1.172 3.058-1.817 5.025-2.551l.416-.156 17.072-6.402.138-.052c.514-.194 1.162-.439 1.858-.54ZM94.382 69.11v-4.037a8.073 8.073 0 1 1 16.147 0v4.036a13.434 13.434 0 0 1 5.383 10.766c0 7.431-6.024 13.456-13.456 13.456C95.025 93.33 89 87.306 89 79.875c0-4.402 2.114-8.31 5.382-10.765Zm13.147-1.702v-2.335a5.073 5.073 0 1 0-10.147 0v2.336a13.414 13.414 0 0 1 5.074-.99c1.795 0 3.508.352 5.073.99ZM106 77.5a3.5 3.5 0 0 1-2 3.163V83.5a1.5 1.5 0 1 1-3 0v-2.837a3.5 3.5 0 1 1 5-3.163ZM126 22a4 4 0 0 1 4-4h45a4 4 0 0 1 4 4v10a4 4 0 0 1-4 4h-45a4 4 0 0 1-4-4V22Zm15 5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm7 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm13-3a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm9 0a2 2 0 1 1-4 0 2 2 0 0 1 4 0Zm1 0a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z",fill:"#4779FF"})),_g$2||(_g$2=reactExports.createElement("g",{clipPath:"url(#passkey-intro-icon_svg__b)"},reactExports.createElement("g",{clipPath:"url(#passkey-intro-icon_svg__c)"},reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M59.731 54.983a15.068 15.068 0 0 0 1.087-10.69C58.656 36.226 50.362 31.438 42.294 33.6c-8.069 2.162-12.857 10.455-10.695 18.524a15.068 15.068 0 0 0 6.288 8.715c1.864-4.039 6.77-6.622 9.948-7.473 3.179-.852 8.204-1.183 11.896 1.618Zm-19.98-8.96a5.672 5.672 0 1 1 10.957-2.935 5.672 5.672 0 0 1-10.957 2.936Z",fill:"#4779FF"})))),_defs$2||(_defs$2=reactExports.createElement("defs",null,reactExports.createElement("clipPath",{id:"passkey-intro-icon_svg__b"},reactExports.createElement("path",{fill:"#fff",transform:"rotate(-15 151.778 -80.474)",d:"M0 0h33v33H0z"})),reactExports.createElement("clipPath",{id:"passkey-intro-icon_svg__c"},reactExports.createElement("rect",{x:27.684,y:37.513,width:30.25,height:30.25,rx:15.125,transform:"rotate(-15 27.684 37.513)",fill:"#fff"})),reactExports.createElement("linearGradient",{id:"passkey-intro-icon_svg__a",x1:103,y1:0,x2:103,y2:105.711,gradientUnits:"userSpaceOnUse"},reactExports.createElement("stop",{stopColor:"#4779FF"}),reactExports.createElement("stop",{offset:1,stopColor:"#4779FF",stopOpacity:0})))))};const AddRecoveryEmail=({canSkipAddingEmail:Xr=!0,shouldInitRecovery:eo=!1,authenticatorType:to,currentAction:ro,isFromEmailVerification:no=!1})=>{const{user:io,setShowAuthFlow:oo}=useInternalDynamicContext(),{t:ao}=useTranslation(),{addRecoveryEmail:so,initPasskeyRecoveryProcess:co}=usePasskeyRecovery(),[lo,fo]=reactExports.useState(!1),[ho,go]=reactExports.useState(void 0);useEffectOnce(()=>{dynamicEvents.once("embeddedWalletRecoveryEmailCompleted",()=>__awaiter$j(void 0,void 0,void 0,function*(){if(fo(!0),go(void 0),!eo){setTimeout(()=>{oo(!1,{ignoreIfIsEmbeddedWidget:!1,performMultiWalletChecks:!1})},5e3);return}return co(to,ro)})),dynamicEvents.once("embeddedWalletRecoveryEmailFailed",Ao=>__awaiter$j(void 0,void 0,void 0,function*(){go(Ao)}))});const{mutate:yo,isLoading:vo}=useMutation(Ao=>__awaiter$j(void 0,void 0,void 0,function*(){yield so(Ao)})),wo=()=>{oo(!1)},Eo=()=>{if(ho)return ho instanceof DynamicError?ho.message:getProperErrorMessage(ho)},ko=Xr&&jsxRuntimeExports.jsx(IconButton,{onClick:wo,type:"button","data-testid":"add-recovery-email-close-button",children:jsxRuntimeExports.jsx(SvgClose,{})});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalHeader,{trailing:ko,children:jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary","data-testid":"passkey-recovery-heading",className:"header__typography",copykey:"dyn_passkey_recovery.add_email.title",children:ao("dyn_passkey_recovery.add_email.title")})}),jsxRuntimeExports.jsxs("div",{className:"passkey-recovery-view",children:[jsxRuntimeExports.jsx("div",{className:"passkey-recovery-view__header",children:jsxRuntimeExports.jsx(SvgPasskeyIntroIcon,{})}),lo&&jsxRuntimeExports.jsx(ErrorContainer,{variant:"success",copykey:"dyn_passkey_recovery.add_email.success_message",children:ao("dyn_passkey_recovery.add_email.success_message")}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"passkey-recovery-view__subtitle",copykey:"dyn_passkey_recovery.add_email.description",children:ao("dyn_passkey_recovery.add_email.description")}),ho!==void 0&&jsxRuntimeExports.jsx(ErrorContainer,{children:Eo()}),jsxRuntimeExports.jsx("div",{className:"passkey-recovery-view__form",children:jsxRuntimeExports.jsx(EmailForm,{onSubmit:yo,currentEmail:io==null?void 0:io.email,isLoading:(vo||no)&&!ho,buttonCopyKey:"dyn_passkey_recovery.add_email.confirm_button",isDisabled:no&&!ho&&!lo})})]})]})},bundleRegex=new RegExp(/^([A-Za-z0-9\s_+@\.-]+)$/),PasskeyBundleRecovery=({authenticatorType:Xr,currentAction:eo})=>{const{primaryWallet:to,environmentId:ro,user:no,setShowAuthFlow:io}=useInternalDynamicContext(),{isTurnkeyWalletWithoutAuthenticator:oo}=useIsTurnkeyWallet(),{getEOAWallet:ao}=useSmartWallets(),[so,co]=reactExports.useState(""),[lo,fo]=reactExports.useState(!1),[ho,go]=reactExports.useState(!1),{t:yo}=useTranslation(),{setView:vo}=useViewContext(),{mutate:wo,isLoading:Eo,error:ko}=useMutation(Xo=>__awaiter$j(void 0,void 0,void 0,function*(){var Lo;const Bo=(Lo=to&&ao(to))!==null&&Lo!==void 0?Lo:to;yield passkeyRecoveryBundleValidation({bundleInput:Xo,user:no,wallet:Bo}),go(!0),Xr==="email"&&dynamicEvents.emit("passkeyRecoveryCompleted",to),setTimeout(()=>{if(Xr==="passkey")return vo("passkey-recovery-complete");eo!=="reveal"&&io(!1)},2e3)})),Ao=Xo=>!(!(Xo!=null&&Xo.length)||Xo.length<100||Xo.length>=256||!bundleRegex.test(Xo)),Po=Xo=>{var Lo;const Bo=(Lo=Xo.target.value)===null||Lo===void 0?void 0:Lo.trim();co(Bo),Ao(Bo)&&wo(Bo)},jo=()=>__awaiter$j(void 0,void 0,void 0,function*(){try{fo(!0),yield resentRecoveryEmail({authenticatorType:Xr,environmentId:ro,user:no,wallet:to})}catch(Xo){logger$8.error("Failed to complete passkey recovery",Xo)}finally{fo(!1)}}),Mo=reactExports.useMemo(()=>{if(ko)return ko instanceof DynamicError?ko.message:getProperErrorMessage(ko)},[ko]),No=jsxRuntimeExports.jsx(Icon,{color:"brand-primary",children:jsxRuntimeExports.jsx(SignInWithEmailIcon,{})}),Do=oo?"dyn_passkey_secure_modal":"dyn_passkey_recovery",Fo=jsxRuntimeExports.jsx(IconButton,{type:"button",onClick:()=>{io(!1,{emitCancelAuth:!0}),dynamicEvents.emit("passkeyRecoveryFailed",new DynamicError("Validation request cancelled"))},"data-testid":"close-button",children:jsxRuntimeExports.jsx(SvgClose,{})});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalHeader,{trailing:Fo,children:jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary","data-testid":"dynamic-auth-modal-heading",className:"header__typography",copykey:`${Do}.code.title`,children:yo(`${Do}.code.title`)})}),jsxRuntimeExports.jsxs("div",{className:"passkey-recovery-view",children:[!ko&&!ho?jsxRuntimeExports.jsx(IconWithSpinner,{Icon:No,isSpinning:!ko&&!ho,iconSize:96}):jsxRuntimeExports.jsx(IconWithStatus,{Icon:SignInWithEmailIcon,iconSize:64,variant:ko?"red":"green",InnerIcon:ko?SvgError:SvgCheck}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"passkey-recovery-view__subtitle",copykey:`${Do}.code.description`,children:yo(`${Do}.code.description`,{email:no==null?void 0:no.email})}),jsxRuntimeExports.jsx("div",{className:"passkey-recovery-view__actions",children:jsxRuntimeExports.jsx(Input,{id:"passkey-recovery-bundle","data-testid":"passkey-recovery-bundle-input",value:so,onChange:Po,label:yo(`${Do}.code.input_label`),disabled:Eo||lo,error:!!ko,className:ho?"passkey-recovery-view__input-valid":"",autoFocus:!0,message:Mo})}),jsxRuntimeExports.jsxs("div",{className:"passkey-recovery-view__resend-code",children:[jsxRuntimeExports.jsx(Typography,{color:"secondary",variant:"body_small",copykey:`${Do}.code.resend.text`,children:yo(`${Do}.code.resend.text`)}),jsxRuntimeExports.jsx(Typography,{variant:"body_small",color:"link",copykey:`${Do}.code.resend.button`,children:jsxRuntimeExports.jsx(TextButton,{"data-testid":"resend-email-button",onClick:jo,disabled:lo||Eo||so.length>0&&!ko,children:yo(`${Do}.code.resend.button`)})})]})]})]})},NeedHelpSection=({isRecoveryFlow:Xr=!1})=>{var eo,to,ro,no,io,oo;const{projectSettings:ao,primaryWallet:so}=useInternalDynamicContext(),{t:co}=useTranslation(),{initPasskeyRecoveryProcess:lo}=usePasskeyRecovery(),fo=(eo=ao==null?void 0:ao.general)===null||eo===void 0?void 0:eo.supportEmail,ho=((to=ao==null?void 0:ao.general)===null||to===void 0?void 0:to.supportUrls)&&((ro=Object.values(ao==null?void 0:ao.general.supportUrls))===null||ro===void 0?void 0:ro[0]),go=!Xr&&((no=ao==null?void 0:ao.providers)===null||no===void 0?void 0:no.find(Po=>Po.provider===ProviderEnum.Turnkey&&Po.enabledAt))&&!!(!((oo=(io=ao==null?void 0:ao.sdk)===null||io===void 0?void 0:io.embeddedWallets)===null||oo===void 0)&&oo.emailRecoveryEnabled),{getEOAWallet:yo}=useSmartWallets(),vo=so&&yo(so),wo=so&&isSessionKeyCompatibleWallet(so)||vo&&isSessionKeyCompatibleWallet(vo),Eo=!!(fo||ho),ko=()=>Eo?jsxRuntimeExports.jsxs("div",{className:"need-help-section__links",children:[ho&&jsxRuntimeExports.jsx(Typography,{variant:"body_small",color:"link",copykey:"dyn_need_help_section.contact_support",children:jsxRuntimeExports.jsx("a",{href:ho,rel:"noreferrer",target:"_blank",children:co("dyn_need_help_section.contact_support")})}),fo&&jsxRuntimeExports.jsx(Typography,{variant:"body_small",color:"link",children:jsxRuntimeExports.jsx("a",{href:`mailto:${fo}`,children:fo})})]}):null,Ao=()=>{if(!go)return null;const Po=co("dyn_need_help_section.help_button"),jo=Eo?Po:Po.slice(0,1).toUpperCase()+Po.slice(1);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Eo&&jsxRuntimeExports.jsx(Typography,{color:"secondary",variant:"body_small",copykey:"dyn_need_help_section.divider",children:co("dyn_need_help_section.divider")}),jsxRuntimeExports.jsx(TextButton,{copykey:"dyn_need_help_section.help_button",className:classNames("need-help-section__helper-link"),onClick:()=>lo(void 0,"helpSession"),children:jo})]})};return!Eo&&(!go||wo)?null:jsxRuntimeExports.jsxs("div",{className:"need-help-section",children:[jsxRuntimeExports.jsx(Typography,{color:"secondary",variant:"body_small",copykey:"dyn_need_help_section.info",children:co("dyn_need_help_section.info")}),ko(),Ao()]})},PasskeyCompleteRecovery=()=>{const{primaryWallet:Xr,environmentId:eo,user:to,setShowAuthFlow:ro,setPasskeySuccessPopup:no}=useInternalDynamicContext(),{isTurnkeyWalletWithoutAuthenticator:io}=useIsTurnkeyWallet(),{getEOAWallet:oo}=useSmartWallets(),{t:ao}=useTranslation(),{mutate:so,isLoading:co,error:lo}=useMutation(()=>__awaiter$j(void 0,void 0,void 0,function*(){var go;const yo=(go=Xr&&oo(Xr))!==null&&go!==void 0?go:Xr;if(!(yield completePasskeyRecovery({environmentId:eo,user:to,wallet:yo})))throw new DynamicError("Error completing passkey recovery");dynamicEvents.emit("passkeyRecoveryCompleted",Xr),ro(!1),no(PasskeySuccessEnum.CREATED)}),{onFailure:go=>{logger$8.error("Failed to init passkey recovery",go),dynamicEvents.emit("passkeyRecoveryFailed",go)}}),fo=reactExports.useMemo(()=>{if(lo)return lo instanceof DynamicError?lo.message:getProperErrorMessage(lo)},[lo]),ho=io?"dyn_passkey_secure_modal":"dyn_passkey_recovery";return jsxRuntimeExports.jsxs("div",{className:"passkey-recovery-view",children:[jsxRuntimeExports.jsx("div",{className:"passkey-recovery-view__header",children:jsxRuntimeExports.jsx(SvgPasskeyIntroIcon,{})}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"passkey-recovery-view__subtitle",children:ao(`${ho}.complete.description`)}),fo&&jsxRuntimeExports.jsx(ErrorContainer,{children:fo}),jsxRuntimeExports.jsx("div",{className:"passkey-recovery-view__actions",children:jsxRuntimeExports.jsx(TypographyButton,{buttonVariant:"brand-primary",buttonPadding:"large",dataTestId:"passkey-recovery-complete-button",onClick:()=>so(),disabled:co,showInternalLoading:!1,typographyProps:{color:"inherit"},children:jsxRuntimeExports.jsxs("div",{className:"passkey-recovery-view__inline-button",children:[jsxRuntimeExports.jsx(PasskeyDeviceIcon,{size:"small"}),jsxRuntimeExports.jsx(Typography,{children:ao(`${ho}.complete.complete_button`)})]})})}),jsxRuntimeExports.jsx(NeedHelpSection,{isRecoveryFlow:!0})]})},PasskeyInitRecovery=({authenticatorType:Xr})=>{const{setShowAuthFlow:eo}=useInternalDynamicContext(),{isTurnkeyWalletWithoutAuthenticator:to}=useIsTurnkeyWallet(),{initAuthMethod:ro,isLoading:no,error:io}=useInitEmbeddedWalletAuthMethod(),{createRootElement:oo}=useElementById(),ao=oo(iframeContainerId$1),{t:so}=useTranslation(),co=reactExports.useMemo(()=>{if(io)return io instanceof DynamicError?io.message:"Something went wrong."},[io]),lo=jsxRuntimeExports.jsx(Icon,{color:"brand-primary",children:jsxRuntimeExports.jsx(SvgSignInWithEmail,{})}),fo=to?"dyn_passkey_secure_modal":"dyn_passkey_recovery",ho=jsxRuntimeExports.jsx(IconButton,{type:"button",onClick:()=>eo(!1,{emitCancelAuth:!0}),"data-testid":"close-button",children:jsxRuntimeExports.jsx(SvgClose,{})});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalHeader,{trailing:ho,children:jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary","data-testid":"dynamic-auth-modal-heading",className:"header__typography",children:so(`${fo}.start.title`)})}),jsxRuntimeExports.jsxs("div",{className:"passkey-recovery-view",children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:lo,isSpinning:no,iconSize:96}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"passkey-recovery-view__subtitle",children:so(`${fo}.start.description`)}),co&&jsxRuntimeExports.jsx(ErrorContainer,{children:co}),jsxRuntimeExports.jsx("div",{className:"passkey-recovery-view__actions",children:jsxRuntimeExports.jsx(TypographyButton,{buttonPadding:"large",dataTestId:"passkey-recovery-button",onClick:()=>ro({authenticatorType:Xr,iframeContainer:ao.current}),disabled:no,showInternalLoading:!1,children:jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx(Typography,{children:so(`${fo}.start.start_button`)})})})}),jsxRuntimeExports.jsx(NeedHelpSection,{isRecoveryFlow:!0})]})]})},RenamePasskeyView=()=>{var Xr;const{passkey:eo,setPasskey:to,passkeyIcon:ro,passkeyEdited:no,setPasskeyEdited:io}=usePasskeyContext(),{t:oo}=useTranslation(),{environmentId:ao,setShowAuthFlow:so,setPasskeySuccessPopup:co}=useInternalDynamicContext(),[lo,fo]=reactExports.useState(!1),ho=vo=>__awaiter$j(void 0,void 0,void 0,function*(){if(vo&&(eo!=null&&eo.id)){const wo=yield updateUserPasskey({alias:vo.trim(),environmentId:ao,id:eo.id});wo?(to(wo),io(!no),so(!1),co(PasskeySuccessEnum.EDITED)):fo(!0)}else fo(!0)}),go=jsxRuntimeExports.jsx(IconButton,{type:"button",onClick:()=>{so(!1)},"data-testid":"back-button",children:jsxRuntimeExports.jsx(SvgChevronLeft,{})}),yo=jsxRuntimeExports.jsx(IconButton,{onClick:()=>so(!1),type:"button",id:"close-button","data-testid":"close-button",children:jsxRuntimeExports.jsx(SvgClose,{})});return eo?jsxRuntimeExports.jsxs("div",{className:"edit-passkeys-widget-view",children:[jsxRuntimeExports.jsx(ModalHeader,{leading:go,trailing:yo}),jsxRuntimeExports.jsx("div",{className:"edit-passkeys-widget-view__icon",children:ro}),jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary",className:"edit-passkeys-widget-view__title",copykey:"dyn_rename_passkeys.title",children:oo("dyn_rename_passkeys.title")}),jsxRuntimeExports.jsx(Formik,{initialValues:{alias:(Xr=eo.alias)!==null&&Xr!==void 0?Xr:""},onSubmit:vo=>{ho(vo.alias)},children:({values:vo})=>jsxRuntimeExports.jsxs(Form,{className:"edit-passkeys-widget-view__body",children:[jsxRuntimeExports.jsx(Field$1,{"data-testid":"input-field",name:"alias",type:"text",label:oo("dyn_rename_passkeys.input_label"),copykey:"dyn_rename_passkeys.input_label",className:"edit-passkeys-widget-view__input",as:Input,error:lo,maxLength:32}),jsxRuntimeExports.jsx(TypographyButton,{type:"submit",className:"edit-passkeys-widget-view__body",buttonPadding:"large",disabled:!vo.alias,copykey:"dyn_rename_passkeys.save",children:oo("dyn_rename_passkeys.save")}),lo&&jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"body_small",color:"error-1",copykey:"dyn_rename_passkeys.error",children:oo("dyn_rename_passkeys.error")})]})})]}):jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary",className:"edit-passkeys-widget-view__title",children:oo("dyn_rename_passkeys.not_found")})};var _g$1,_defs$1,_excluded$5=["title","titleId"];function _extends$7(){return _extends$7=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$5(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgMultipleAccountSecurity=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$5(eo,_excluded$5);return reactExports.createElement("svg",_extends$7({width:327,height:112,viewBox:"0 0 327 112",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_g$1||(_g$1=reactExports.createElement("g",{clipPath:"url(#multiple-account-security_svg__a)"},reactExports.createElement("circle",{cx:164,cy:114,r:114,fill:"url(#multiple-account-security_svg__b)",fillOpacity:.12}),reactExports.createElement("g",{clipPath:"url(#multiple-account-security_svg__c)"},reactExports.createElement("g",{clipPath:"url(#multiple-account-security_svg__d)"},reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M118.709 55.166a14.617 14.617 0 0 0 1.054-10.366c-2.097-7.824-10.139-12.467-17.963-10.371-7.824 2.096-12.468 10.139-10.371 17.963a14.612 14.612 0 0 0 6.097 8.451c1.808-3.916 6.565-6.42 9.647-7.247 3.083-.826 7.955-1.146 11.536 1.57Zm-19.375-8.688a5.5 5.5 0 1 1 10.625-2.848 5.5 5.5 0 0 1-10.625 2.848Z",fill:"#4779FF"}))),reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m207.67 19.875-.767 2.862a9.86 9.86 0 0 0-5.861 6.61c-1.412 5.269 1.715 10.684 6.984 12.096 5.268 1.412 10.684-1.715 12.096-6.984a9.862 9.862 0 0 0-1.771-8.655l.767-2.861a5.926 5.926 0 0 0-11.448-3.068Zm9.321 2.498-.444 1.655a9.844 9.844 0 0 0-3.409-1.665 9.847 9.847 0 0 0-3.785-.262l.444-1.656a3.723 3.723 0 1 1 7.194 1.928Zm-3.445 8.52a2.57 2.57 0 0 1-2.019 1.862l-.539 2.011a1.1 1.1 0 1 1-2.127-.57l.539-2.01a2.569 2.569 0 1 1 4.146-1.294ZM164.943 32.064a6.216 6.216 0 0 0-1.779 0c-.681.098-1.313.337-1.816.527l-.135.05-16.68 6.256-.407.152c-1.922.718-3.61 1.348-4.909 2.493a9.336 9.336 0 0 0-2.553 3.683c-.616 1.62-.613 3.421-.61 5.473V66.01c0 8.793 4.783 16.125 9.953 21.51 5.204 5.422 11.159 9.252 14.307 11.089l.128.075c.574.337 1.32.775 2.307.987a6.619 6.619 0 0 0 2.609 0c.987-.212 1.733-.65 2.307-.987l.128-.075c3.148-1.837 9.103-5.667 14.307-11.088 5.17-5.386 9.953-12.718 9.953-21.511V50.698c.003-2.052.006-3.854-.611-5.473a9.333 9.333 0 0 0-2.552-3.683c-1.3-1.145-2.987-1.775-4.909-2.493l-.407-.152-16.68-6.255-.135-.05c-.503-.19-1.136-.43-1.816-.528Zm7.008 18.695c0-1.726-1.4-3.126-3.127-3.126h-14.069a6.253 6.253 0 0 0-6.153 5.133 6.234 6.234 0 0 1 4.589-2.007h18.76Zm1.562 3.127c3.454 0 6.253 2.8 6.253 6.253v12.506a6.253 6.253 0 0 1-6.253 6.254h-18.759a6.253 6.253 0 0 1-6.253-6.254V60.14a6.253 6.253 0 0 1 6.253-6.253h18.759Z",fill:"#4779FF"}))),_defs$1||(_defs$1=reactExports.createElement("defs",null,reactExports.createElement("clipPath",{id:"multiple-account-security_svg__a"},reactExports.createElement("rect",{width:327,height:112,rx:12,fill:"#fff"})),reactExports.createElement("clipPath",{id:"multiple-account-security_svg__c"},reactExports.createElement("path",{fill:"#fff",transform:"rotate(-15 184.593 -307.976)",d:"M0 0h32v32H0z"})),reactExports.createElement("clipPath",{id:"multiple-account-security_svg__d"},reactExports.createElement("rect",{x:87.633,y:38.225,width:29.333,height:29.333,rx:14.667,transform:"rotate(-15 87.633 38.225)",fill:"#fff"})),reactExports.createElement("linearGradient",{id:"multiple-account-security_svg__b",x1:164,y1:0,x2:164,y2:93.5,gradientUnits:"userSpaceOnUse"},reactExports.createElement("stop",{stopColor:"#4779FF"}),reactExports.createElement("stop",{offset:1,stopColor:"#4779FF",stopOpacity:0})))))},_g,_defs,_excluded$4=["title","titleId"];function _extends$6(){return _extends$6=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$4(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgPasskeyAccountSecurity=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$4(eo,_excluded$4);return reactExports.createElement("svg",_extends$6({width:327,height:112,viewBox:"0 0 327 112",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_g||(_g=reactExports.createElement("g",{clipPath:"url(#passkey-account-security_svg__a)"},reactExports.createElement("circle",{cx:164,cy:114,r:114,fill:"url(#passkey-account-security_svg__b)",fillOpacity:.12}),reactExports.createElement("g",{clipPath:"url(#passkey-account-security_svg__c)",fill:"#4779FF"},reactExports.createElement("path",{d:"M106.009 34.681a2.666 2.666 0 0 1 3.266 1.886l-15.454 4.141a5.319 5.319 0 0 0-3.339 2.666 5.335 5.335 0 0 1 3.936-5.587l11.591-3.105ZM117.785 42.57a5.333 5.333 0 0 0-6.532-3.772l-15.455 4.141a5.333 5.333 0 0 0-3.771 6.532l2.76 10.303a5.334 5.334 0 0 0 6.533 3.771l15.454-4.14a5.333 5.333 0 0 0 3.772-6.533l-2.761-10.303Z"})),reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m207.67 19.875-.767 2.862a9.86 9.86 0 0 0-5.861 6.61c-1.412 5.268 1.715 10.684 6.984 12.096 5.268 1.412 10.684-1.715 12.096-6.984a9.862 9.862 0 0 0-1.771-8.655l.767-2.861a5.926 5.926 0 0 0-11.448-3.068Zm9.321 2.498-.444 1.655a9.846 9.846 0 0 0-3.409-1.665 9.849 9.849 0 0 0-3.785-.262l.444-1.656a3.723 3.723 0 1 1 7.194 1.928Zm-3.445 8.52a2.57 2.57 0 0 1-2.019 1.862l-.539 2.011a1.1 1.1 0 1 1-2.127-.57l.539-2.01a2.569 2.569 0 1 1 4.146-1.294ZM164.943 32.064a6.216 6.216 0 0 0-1.779 0c-.681.098-1.313.337-1.816.527l-.135.05-16.68 6.256-.407.152c-1.922.718-3.61 1.348-4.909 2.493a9.336 9.336 0 0 0-2.553 3.683c-.616 1.62-.613 3.421-.61 5.473V66.01c0 8.793 4.783 16.125 9.953 21.51 5.204 5.422 11.159 9.252 14.307 11.089l.128.075c.574.337 1.32.775 2.307.987a6.619 6.619 0 0 0 2.609 0c.987-.212 1.733-.65 2.307-.987l.128-.075c3.148-1.837 9.103-5.667 14.307-11.088 5.17-5.386 9.953-12.718 9.953-21.511V50.698c.003-2.052.006-3.854-.611-5.473a9.333 9.333 0 0 0-2.552-3.683c-1.3-1.145-2.987-1.775-4.909-2.493l-.407-.152-16.68-6.255-.135-.05c-.503-.19-1.136-.43-1.816-.528Zm-1.34 14.592a15.89 15.89 0 0 0-7.978 2.135 1.772 1.772 0 1 0 1.776 3.069 12.34 12.34 0 0 1 6.202-1.66c6.853 0 12.408 5.556 12.408 12.409a44.34 44.34 0 0 1-1.688 12.156 1.772 1.772 0 1 0 3.41.97 47.883 47.883 0 0 0 1.823-13.126c0-8.81-7.142-15.953-15.953-15.953Zm-10.749 9.75a1.772 1.772 0 1 0-3.068-1.775 15.882 15.882 0 0 0-2.136 7.978c0 2.499-.573 4.86-1.594 6.96a1.772 1.772 0 1 0 3.189 1.55 19.43 19.43 0 0 0 1.95-8.51c0-2.263.605-4.38 1.659-6.203Zm10.749-2.66a8.863 8.863 0 0 0-8.863 8.863c0 4.516-1.29 8.704-3.518 12.246l1.5.944-1.5-.944a8.75 8.75 0 0 0-.12.196 1.773 1.773 0 1 0 3.048 1.81c.023-.04.048-.079.072-.118a26.434 26.434 0 0 0 4.063-14.134 5.318 5.318 0 0 1 10.636 0c0 1.722-.118 3.417-.344 5.077a1.772 1.772 0 1 0 3.512.48 41.12 41.12 0 0 0 .377-5.557 8.863 8.863 0 0 0-8.863-8.863Zm1.772 8.863a1.772 1.772 0 1 0-3.545 0c0 5.89-1.688 11.381-4.607 16.021a1.773 1.773 0 0 0 3.001 1.888 33.528 33.528 0 0 0 5.151-17.91Zm5.554 11.117a1.773 1.773 0 0 0-3.411-.965 37.01 37.01 0 0 1-2.523 6.502 1.771 1.771 0 1 0 3.169 1.588 40.517 40.517 0 0 0 2.765-7.124Z",fill:"#4779FF"}))),_defs||(_defs=reactExports.createElement("defs",null,reactExports.createElement("clipPath",{id:"passkey-account-security_svg__a"},reactExports.createElement("rect",{width:327,height:112,rx:12,fill:"#fff"})),reactExports.createElement("clipPath",{id:"passkey-account-security_svg__c"},reactExports.createElement("path",{fill:"#fff",transform:"rotate(-15 184.593 -307.976)",d:"M0 0h32v32H0z"})),reactExports.createElement("linearGradient",{id:"passkey-account-security_svg__b",x1:164,y1:0,x2:164,y2:93.5,gradientUnits:"userSpaceOnUse"},reactExports.createElement("stop",{stopColor:"#4779FF"}),reactExports.createElement("stop",{offset:1,stopColor:"#4779FF",stopOpacity:0})))))};const ActionCard=({titleKey:Xr,descriptionKey:eo,description:to,LeadingIcon:ro,action:no,badgeVariant:io,badgeKey:oo,isLoading:ao,dataTestId:so})=>{const{t:co}=useTranslation();return jsxRuntimeExports.jsxs("button",{className:"action-card",onClick:no,"data-testid":so,children:[jsxRuntimeExports.jsx(Icon,{className:"action-card__icon",children:ro}),jsxRuntimeExports.jsxs("div",{className:"action-card__content",children:[jsxRuntimeExports.jsxs("div",{className:"action-card__content__row",children:[jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"medium",copykey:Xr,children:co(Xr)}),jsxRuntimeExports.jsx(Badge,{text:co(oo),className:classNames("action-card__content__row__badge",{"action-card__content__row__badge--primary":io==="primary"},{"action-card__content__row__badge--secondary":io==="secondary"}),copykey:oo})]}),jsxRuntimeExports.jsx(Typography,{variant:"body_small",color:"secondary",copykey:eo,children:to})]}),jsxRuntimeExports.jsx(Icon,{color:"text-tertiary",className:"action-card__action-icon",children:ao?jsxRuntimeExports.jsx(Spinner$1,{}):jsxRuntimeExports.jsx(SvgChevronLeft,{})})]})},EmbeddedAuthChoiceCards=({currentAction:Xr,supportedAuthenticators:eo})=>{var to,ro;const[no,io]=reactExports.useState(),{projectSettings:oo}=useInternalDynamicContext(),{t:ao}=useTranslation(),{initAuthMethod:so,isLoading:co}=useInitEmbeddedWalletAuthMethod(),{createRootElement:lo}=useElementById(),fo=lo(iframeContainerId$1),ho={email:{badgeKey:"dyn_embedded_authenticator.email.badge",description:ao("dyn_embedded_authenticator.email.description",{expiration:(ro=(to=oo==null?void 0:oo.sdk.embeddedWallets)===null||to===void 0?void 0:to.sessionKeyDuration)===null||ro===void 0?void 0:ro.amount}),descriptionKey:"dyn_embedded_authenticator.email.description",icon:jsxRuntimeExports.jsx(Icon,{color:"text-tertiary",size:"small",children:jsxRuntimeExports.jsx(SvgMail,{})},"one-time-code-icon"),titleKey:"dyn_embedded_authenticator.email.title"},passkey:{badgeKey:"dyn_embedded_authenticator.passkey.badge",description:ao("dyn_embedded_authenticator.passkey.description"),descriptionKey:"dyn_embedded_authenticator.passkey.description",icon:jsxRuntimeExports.jsx(PasskeyDeviceIcon,{defaultIcon:jsxRuntimeExports.jsx(SvgAndroidTouchId,{"data-testid":"default-icon"})}),titleKey:Xr==="reveal"?"dyn_embedded_authenticator.passkey.reveal_title":"dyn_embedded_authenticator.passkey.title"}},go=yo=>()=>__awaiter$j(void 0,void 0,void 0,function*(){io(yo),yield so({authenticatorType:yo,currentAction:Xr,iframeContainer:fo.current})});return jsxRuntimeExports.jsx("div",{className:"embedded-auth-choice-cards",children:eo&&eo.map(yo=>jsxRuntimeExports.jsx(ActionCard,{LeadingIcon:ho[yo].icon,action:go(yo),badgeKey:ho[yo].badgeKey,badgeVariant:yo==="passkey"?"primary":"secondary",descriptionKey:ho[yo].descriptionKey,description:ho[yo].description,titleKey:ho[yo].titleKey,isLoading:co&&yo===no,dataTestId:`embedded-auth-choice__item-${yo}`},yo))})},titleDescriptionMap={helpSession:{description:"dyn_embedded_authenticator.need_help_description",title:"dyn_embedded_authenticator.need_help_title"},reveal:{description:"dyn_embedded_authenticator.reveal_description",title:"dyn_embedded_authenticator.reveal_title"},sendTransaction:{description:"dyn_embedded_authenticator.description",title:"dyn_embedded_authenticator.title"},signMessage:{description:"dyn_embedded_authenticator.description",title:"dyn_embedded_authenticator.title"}},EmbeddedAuthChoice=({currentAction:Xr})=>{var eo;const{t:to}=useTranslation(),{primaryWallet:ro,projectSettings:no,setShowAuthFlow:io}=useInternalDynamicContext(),{getEOAWallet:oo}=useSmartWallets(),ao=(eo=ro&&oo(ro))!==null&&eo!==void 0?eo:ro,{initPasskeyRecoveryProcess:so}=usePasskeyRecovery(),{isTurnkeyWallet:co}=useIsTurnkeyWallet(),lo=reactExports.useMemo(()=>{var wo;const Eo=getEnabledEmbeddedWalletsAuthenticators((wo=no==null?void 0:no.sdk.embeddedWallets)===null||wo===void 0?void 0:wo.supportedSecurityMethods),ko=Object.keys(Eo);return!Xr||!["helpSession","reveal"].includes(Xr)?ko.filter(Ao=>Ao!=="email"):ko},[no==null?void 0:no.sdk.embeddedWallets]),fo=()=>!ao||!co?!1:ao.connector.getAuthenticatorHandler().isSessionActive(),ho=()=>lo.length>1?jsxRuntimeExports.jsx(SvgMultipleAccountSecurity,{}):jsxRuntimeExports.jsx(SvgPasskeyAccountSecurity,{}),go=fo()?"dyn_embedded_authenticator.passkey.auth_info.start_button":"dyn_embedded_authenticator.passkey.auth_info.add_button",{title:yo,description:vo}=titleDescriptionMap[Xr||"signMessage"];return lo!=null&&lo.length?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalHeader,{children:jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary","data-testid":"dynamic-auth-modal-heading",className:"header__typography",copykey:yo,children:to(yo)})}),jsxRuntimeExports.jsxs("div",{className:"embedded-auth-choice",children:[jsxRuntimeExports.jsx("div",{className:"embedded-auth-choice__header",children:ho()}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"embedded-auth-choice__subtitle",copykey:vo,children:to(vo)}),lo.length>1?jsxRuntimeExports.jsx(EmbeddedAuthChoiceCards,{currentAction:Xr,supportedAuthenticators:lo}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(AuthChoiceInfo,{choice:"passkey"}),jsxRuntimeExports.jsx(TypographyButton,{dataTestId:"passkey-only-choice-button",buttonVariant:"brand-primary",color:"brand-primary",expanded:!0,onClick:()=>so("passkey"),copykey:go,typographyProps:{color:"inherit"},children:to(go)})]}),Xr!=="reveal"&&jsxRuntimeExports.jsx(TypographyButton,{buttonVariant:"primary",buttonClassName:"embedded-auth-choice__skip-button",expanded:!0,onClick:()=>io(!1),copykey:"dyn_embedded_authenticator.skip",children:to("dyn_embedded_authenticator.skip")})]})]}):null},PendingSignatureView=()=>{const[Xr,eo]=reactExports.useState(!1),{selectedWalletConnector:to}=useInternalDynamicContext(),{signAlreadyConnectedUser:ro}=useConnectAndSignSplitSteps(),{t:no}=useTranslation(),io=96,oo=isHardwareWalletEnabled(to);if(!to)return null;const ao=()=>__awaiter$j(void 0,void 0,void 0,function*(){try{eo(!0),yield ro({walletConnector:to})}catch(lo){logger$8.error(lo)}finally{eo(!1)}}),so=jsxRuntimeExports.jsx(WalletIcon,{walletKey:to.key,style:{height:pixelToRem(io*iconRatio),width:pixelToRem(io*iconRatio)}}),co=no(oo?"dyn_pending_signature.phantom_ledger_sign":"dyn_pending_signature.regular_sign_description");return jsxRuntimeExports.jsxs("div",{className:"pending-signature__container","data-testid":"pending-signature-view",children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:so,iconSize:io,isSpinning:!0,indicator:"connected",className:"pending-signature__icon-with-spinner"}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",className:classNames("pending-signature__copy"),copykey:oo?"dyn_pending_signature.phantom_ledger_sign":"dyn_pending_signature.regular_sign_description",children:co}),oo&&jsxRuntimeExports.jsxs(Typography,{variant:"body_small",weight:"regular",className:classNames("pending-signature__copy","pending-signature__copy--mini"),copykey:"dyn_pending_signature.phantom_ledger_warning",children:[jsxRuntimeExports.jsx("strong",{children:no("dyn_pending_signature.note")}),no("dyn_pending_signature.phantom_ledger_warning")]}),requiresTwoStepAuthentication(to)&&jsxRuntimeExports.jsx(TypographyButton,{buttonClassName:"pending-signature__button",onClick:ao,loading:Xr,buttonVariant:"primary",buttonPadding:"large",expanded:!0,typographyProps:{variant:"button_primary",weight:"medium"},copykey:"dyn_pending_signature.click_to_sign",children:no("dyn_pending_signature.click_to_sign")})]})},QrCodeView=()=>{var Xr;const{theme:{theme:eo}}=useThemeContext(),{name:to}=eo,{qrcodeUri:ro,desktopUri:no,selectedWalletConnector:io}=useInternalDynamicContext(),{walletBook:oo}=useWalletBookContext();if(!io)return null;const ao=jsxRuntimeExports.jsx(WalletIcon,{walletKey:io.key,style:{height:pixelToRem(32),width:pixelToRem(32)}});return jsxRuntimeExports.jsx(QrCodeWrapper,{uri:ro,desktopUri:no,accentColor:to==="dark"?eo.colors.textPrimary:(Xr=getWalletPrimaryColor(oo,io.key))!==null&&Xr!==void 0?Xr:"",icon:ao,showCopyToClipboardButton:io.isWalletConnect,walletConnector:io})},PendingConnectView=()=>{const{selectedWalletConnector:Xr}=useInternalDynamicContext(),{t:eo}=useTranslation(),to=94,ro=jsxRuntimeExports.jsx(WalletIcon,{walletKey:Xr==null?void 0:Xr.key,style:{height:pixelToRem(to*iconRatio),width:pixelToRem(to*iconRatio)}});return jsxRuntimeExports.jsxs("div",{className:"pending-connect__container",children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:ro,iconSize:to,isSpinning:!0,className:"pending-connect__icon-with-spinner"}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",className:"pending-connect__copy-text",copykey:isMobile$1()?"dyn_pending_connection.mobile":"dyn_pending_connection.computer",children:isMobile$1()?eo("dyn_pending_connection.mobile"):eo("dyn_pending_connection.computer")})]})},SandboxMaximumThresholdReached=()=>{const{t:Xr}=useTranslation(),{goToInitialView:eo}=useViewContext(),to=()=>{eo()};return jsxRuntimeExports.jsxs("div",{className:"sandbox-threshold__main",children:[jsxRuntimeExports.jsx(Typography,{variant:"title",color:"primary",className:"sandbox-threshold__title",children:Xr("dyn_sandbox_maximum_threshold.title")}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",className:"sandbox-threshold__description",children:Xr("dyn_sandbox_maximum_threshold.description")}),jsxRuntimeExports.jsx(TypographyButton,{onClick:to,className:"sandbox-threshold__button",expanded:!0,buttonPadding:"large",children:Xr("dyn_sandbox_maximum_threshold.button")})]})},Toggle=Xr=>{var{icon:eo,variant:to="primary",className:ro}=Xr,no=__rest$7(Xr,["icon","variant","className"]);return jsxRuntimeExports.jsxs("label",{className:classNames("toggle",ro),children:[jsxRuntimeExports.jsx("input",Object.assign({type:"checkbox",className:"toggle--input"},no)),jsxRuntimeExports.jsx("div",{className:classNames("toggle--content",`toggle--content__variant-${to}`),children:jsxRuntimeExports.jsx("div",{className:"toggle--knob",children:eo})})]})},HardwareWalletToggle=({connectors:Xr,label:eo,copykey:to})=>{const ro=jsxRuntimeExports.jsx(Toggle,{defaultChecked:Xr.some(no=>no.isHardwareWalletEnabled),onChange:no=>{Xr.forEach(io=>{io.isHardwareWalletEnabled=no.target.checked})},"data-testid":"hardware-wallet-toggle",icon:jsxRuntimeExports.jsx(Icon,{size:"small",children:jsxRuntimeExports.jsx(SvgCheck,{})})});return jsxRuntimeExports.jsx(ListTile,{trailing:ro,children:jsxRuntimeExports.jsx("span",{copykey:to,children:eo})})},SelectHardwareWalletView=({wallet:Xr,onSelectWallet:eo})=>{const{t:to}=useTranslation();return jsxRuntimeExports.jsx("div",{className:"select-hardware-wallet-view",children:jsxRuntimeExports.jsxs("div",{className:"select-hardware-wallet-view__container",children:[jsxRuntimeExports.jsx(Icon,{className:"select-hardware-wallet-view__icon",children:jsxRuntimeExports.jsx(WalletIcon,{walletKey:Xr.key})}),jsxRuntimeExports.jsx(Typography,{className:"select-hardware-wallet-view__text",as:"p",color:"secondary",variant:"body_normal",copykey:"dyn_select_hardware_wallet.description",children:to("dyn_select_hardware_wallet.description")}),isHardwareWalletConnector(Xr.walletConnector)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(HardwareWalletToggle,{connectors:[Xr.walletConnector],copykey:"dyn_select_chain.using_hardware_wallet_toggle_label",label:to("dyn_select_chain.using_hardware_wallet_toggle_label")}),jsxRuntimeExports.jsx(Divider,{})]}),jsxRuntimeExports.jsx(TypographyButton,{buttonVariant:"primary",onClick:()=>eo==null?void 0:eo(Xr),copykey:"dyn_select_hardware_wallet.button",dataTestId:"select-hardware-wallet-connect-button",children:to("dyn_select_hardware_wallet.button")})]})})},WalletGroupViewLayout=({icon:Xr,title:eo,titleCopyKey:to,children:ro})=>jsxRuntimeExports.jsxs("div",{className:"wallet-group-view-layout__container",children:[jsxRuntimeExports.jsx(IconWithSpinner,{className:"wallet-group-view-layout__icon",Icon:Xr,iconSize:96}),jsxRuntimeExports.jsxs("div",{className:"wallet-group-view-layout__body",children:[jsxRuntimeExports.jsx(Typography,{className:"wallet-group-view-layout__title",as:"p",color:"secondary",variant:"body_normal",copykey:to,children:eo}),jsxRuntimeExports.jsx("div",{className:"wallet-group-view-layout__list",children:ro})]})]}),WalletGroupItem$1=({groupKey:Xr,wallet:eo,onClick:to})=>{const{recommendedWallets:ro}=useInternalDynamicContext(),{walletBook:no}=useWalletBookContext(),io=findWalletGroupOverride(no,Xr,eo.key),oo=findWalletBookWallet(no,eo.key),ao=(io==null?void 0:io.brand)||(oo==null?void 0:oo.brand),so=(io==null?void 0:io.name)||(oo==null?void 0:oo.name),co=ao?jsxRuntimeExports.jsx(BrandIcon,{brand:ao,walletKey:eo.key,style:{height:pixelToRem(28),width:pixelToRem(28)}}):null,lo=getWalletListItemLabel({recommendedWallets:ro,wallet:eo}),fo=jsxRuntimeExports.jsx(ListTileAnimatedTrailing,{hoverElement:jsxRuntimeExports.jsx(Icon,{color:"text-tertiary",size:"mini",children:jsxRuntimeExports.jsx(SvgStroke,{})}),children:lo&&jsxRuntimeExports.jsx(Badge,{dot:!lo.isRecommended,variant:lo.isRecommended?"primary":"secondary",text:jsxRuntimeExports.jsx(Typography,{variant:"body_small",children:lo.label})})});return jsxRuntimeExports.jsx(ListTile,{onClick:to,leading:co,trailing:fo,children:so})},SelectWalletInWalletGroupView=()=>{const{selectedWalletGroup:Xr}=useWalletGroupContext(),{walletBook:eo}=useWalletBookContext(),{handleWalletItemClick:to}=useWalletItemActions(),{t:ro}=useTranslation();if(!Xr)throw new Error("Could not access WalletGroup view without selected group");const no=getWalletGroup(eo,Xr==null?void 0:Xr.key);return jsxRuntimeExports.jsx(WalletGroupViewLayout,{icon:jsxRuntimeExports.jsx(WalletIcon,{walletKey:no.key}),title:ro("dyn_select_wallet.description",{walletName:no.name}),titleCopyKey:"dyn_select_wallet.description",children:Xr.groupedWallets.map((io,oo)=>jsxRuntimeExports.jsx(WalletGroupItem$1,{groupKey:Xr.key,wallet:io,onClick:()=>to(io)},`${io.key}_${oo}`))})};var _path$3,_excluded$3=["title","titleId"];function _extends$5(){return _extends$5=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$3(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgSignInWithPhone=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$3(eo,_excluded$3);return reactExports.createElement("svg",_extends$5({width:64,height:64,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_path$3||(_path$3=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32 64c17.673 0 32-14.327 32-32C64 14.327 49.673 0 32 0 14.327 0 0 14.327 0 32c0 17.673 14.327 32 32 32Zm-7.91-50h14.892a4.092 4.092 0 0 1 4.09 4.09v27.82a4.092 4.092 0 0 1-4.09 4.09H24.09A4.092 4.092 0 0 1 20 45.91V18.09A4.092 4.092 0 0 1 24.09 14Zm4.992 31.91a2.451 2.451 0 0 0 2.454 2.454 2.451 2.451 0 0 0 2.455-2.455 2.451 2.451 0 0 0-2.455-2.454 2.451 2.451 0 0 0-2.454 2.454Zm-5.81-4.092H39.8V18.91H23.273v22.91Z",fill:"#4779FF"})))};const PhoneIcon=Xr=>jsxRuntimeExports.jsx(Icon,{color:"brand-primary",children:jsxRuntimeExports.jsx(SvgSignInWithPhone,Object.assign({},Xr,{"data-testid":"sign-in-with-sms-icon"}))}),useSmsVerification=Xr=>{const{verificationUUID:eo,displayedDestination:to,retryData:ro}=useVerification(),{environmentId:no,user:io,userWithMissingInfo:oo}=useInternalDynamicContext(),[ao,so]=reactExports.useState(),{verifyOtp:co}=useOtpVerificationRequest(),{generateSessionKey:lo,shouldRegisterSessionKeysOnSignin:fo}=useEmbeddedWalletSessionKeys(no),{initAuth:ho,completeAuth:go,cancelAuth:yo}=useUserAuth({authMethod:"sms"}),vo=reactExports.useRef(!1);useOnUnmount(()=>{const jo=ro??{dialCode:"",iso2:"",phone:""};ro||logger$8.warn("WARNING: emitted smsVerificationResult with incomplete params because retryData was undefined"),dynamicEvents.emit("smsVerificationResult",vo.current,jo),vo.current||dynamicEvents.emit("authFailure",{option:jo,phone:jo,type:"sms"},"user-cancelled")});const wo=()=>__awaiter$j(void 0,void 0,void 0,function*(){if(so(void 0),!eo||!ro){yield yo();return}retrySmsVerification({environmentId:no,isoCountryCode:ro.iso2,phoneCountryCode:ro.dialCode,phoneNumber:de$4({dialCode:ro.dialCode,phone:ro.phone}),verificationUUID:eo})}),Eo=reactExports.useCallback(jo=>__awaiter$j(void 0,void 0,void 0,function*(){if(!eo||!io&&!oo){yield yo();return}yield go({onValidUpdatedJwt:()=>vo.current=!0,updateJwtFunction:()=>__awaiter$j(void 0,void 0,void 0,function*(){return co(jo,"sms",eo)})})}),[yo,go,io,oo,eo,co]),ko=reactExports.useCallback(jo=>__awaiter$j(void 0,void 0,void 0,function*(){if(!eo){yield yo();return}yield ho({onError:Mo=>so(Mo),onVerifySuccess:()=>{vo.current=!0},options:{phone:ro},showSuccessMessage:!0,verifyFunction:()=>__awaiter$j(void 0,void 0,void 0,function*(){let Mo;return fo()&&(Mo=(yield lo()).publicKey),signInWithSmsVerification({environmentId:no,sessionPublicKey:Mo,verificationToken:jo,verificationUUID:eo})})})}),[eo,ho,ro,yo,no]),{isLoading:Ao,mutate:Po}=useMutation(Xr==="login"?ko:Eo,{onFailure:jo=>{so(jo)}});return{error:ao,formattedPhone:to??"",isLoading:Ao,isValid:vo.current,onSubmit:Po,retryOneTimePassword:wo,setError:so}},SmsVerification=()=>{const{view:Xr}=useViewContext(),{handleLogOut:eo}=useInternalDynamicContext(),{t:to}=useTranslation(),ro=Xr.type==="login-with-sms-verification",{error:no,formattedPhone:io,isLoading:oo,isValid:ao,onSubmit:so,retryOneTimePassword:co,setError:lo}=useSmsVerification(ro?"login":"verify-only"),fo=ro?void 0:jsxRuntimeExports.jsx(TextButton,{className:"sms-verification__log-out",onClick:eo,copykey:"dyn_otp_verification.log_out_button",children:to("dyn_otp_verification.log_out_button")});return jsxRuntimeExports.jsx(OTPVerificationView,{MainIcon:PhoneIcon,displayedDestination:io,error:no,hideHeader:!0,isLoading:oo,onPinComplete:so,isValid:ao,retryHandler:co,onPinChange:()=>lo(void 0),appendToEnd:fo})},SocialRedirectView=()=>{const{socialProvider:Xr,signInProvider:eo}=useSocialRedirectContext(),to=useFindSocialIcon(),{t:ro}=useTranslation();return jsxRuntimeExports.jsxs("div",{className:classNames("social-redirect-view__container"),children:[Xr&&jsxRuntimeExports.jsx(IconWithSpinner,{iconSize:64,Icon:to(Xr),isSpinning:!0}),jsxRuntimeExports.jsx(Typography,{weight:"medium",variant:"title",className:classNames("social-redirect-view__title"),copykey:"dyn_social_redirect.logging_in",children:ro("dyn_social_redirect.logging_in")}),eo!==SignInProviderEnum.MagicLink&&jsxRuntimeExports.jsx(PoweredByDynamic,{classNameRoot:"powered-by-dynamic"})]})},SocialWrongAccountView=()=>{const[Xr,eo]=reactExports.useState(!1),{socialWalletConnector:to,socialAccount:ro}=useSocialRedirectContext(),{t:no}=useTranslation(),io=useFindSocialIcon();return!ro||!to?null:jsxRuntimeExports.jsxs("div",{className:classNames("social-wrong-account-view__container"),children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:io(ro.oauthProvider),isSpinning:Xr,iconSize:64}),jsxRuntimeExports.jsx(Typography,{weight:"medium",variant:"title",className:classNames("social-wrong-account-view__title"),copykey:"dyn_login.wrong_social_account.title",children:no("dyn_login.wrong_social_account.title")}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",className:classNames("social-wrong-account-view__copy"),copykey:"dyn_login.wrong_social_account.subtitle",children:no("dyn_login.wrong_social_account.subtitle")}),jsxRuntimeExports.jsxs(Typography,{variant:"body_normal",weight:"regular",className:classNames("social-wrong-account-view__copy"),copykey:"dyn_login.wrong_social_account.retry_title",children:[no("dyn_login.wrong_social_account.retry_title"),jsxRuntimeExports.jsx("b",{children:ro.oauthUsername})]}),jsxRuntimeExports.jsx(TypographyButton,{buttonClassName:"social-wrong-account-view__button",buttonVariant:"primary",buttonPadding:"large",expanded:!0,typographyProps:{variant:"button_primary",weight:"medium"},disabled:Xr,onClick:()=>{eo(!0),to.connect(ro.oauthProvider)},copykey:"dyn_login.wrong_social_account.retry_button",children:no("dyn_login.wrong_social_account.retry_button")})]})},WalletCannotBeTransferredView=()=>{const{goToInitialView:Xr}=useViewContext(),{selectedWalletConnector:eo}=useInternalDynamicContext(),{t:to}=useTranslation(),{data:ro}=usePromise(()=>__awaiter$j(void 0,void 0,void 0,function*(){const no=yield eo==null?void 0:eo.getConnectedAccounts();return shortenWalletAddress(no==null?void 0:no[0])}),{deps:[eo]});return jsxRuntimeExports.jsxs("div",{className:"wallet-cannot-be-transferred-view__container",children:[jsxRuntimeExports.jsx(Typography,{className:"wallet-cannot-be-transferred-view__title",as:"h6",variant:"title",color:"primary",weight:"medium",copykey:"dyn_wallet_link.cannot_link.title",children:to("dyn_wallet_link.cannot_link.title")}),jsxRuntimeExports.jsx("div",{className:"wallet-cannot-be-transferred-view__icon",children:jsxRuntimeExports.jsx(WalletIcon,{walletKey:eo==null?void 0:eo.key,width:64,height:64})}),jsxRuntimeExports.jsx(Typography,{className:"wallet-cannot-be-transferred-view__shorten-wallet-address",variant:"body_normal",weight:"regular",color:"primary",children:ro}),jsxRuntimeExports.jsx(Typography,{className:"wallet-cannot-be-transferred-view__copy",variant:"body_normal",color:"secondary",weight:"regular",copykey:"dyn_wallet_link.cannot_link.description",children:to("dyn_wallet_link.cannot_link.description")}),jsxRuntimeExports.jsx(TypographyButton,{buttonClassName:"wallet-cannot-be-transferred-view__transfer-alt-wallet-button",buttonVariant:"primary",expanded:!0,buttonPadding:"large",onClick:Xr,dataTestId:"wallet-cannot-be-transferred-view-transfer-alt-wallet",copykey:"dyn_wallet_link.cannot_link.link_other_button",children:to("dyn_wallet_link.cannot_link.link_other_button")}),jsxRuntimeExports.jsx(TypographyButton,{dataTestId:"wallet-cannot-be-transferred-view-cancel",buttonPadding:"small",buttonClassName:"wallet-cannot-be-transferred-view__cancel",onClick:Xr,copykey:"dyn_wallet_link.cannot_link.cancel_button",children:to("dyn_wallet_link.cannot_link.cancel_button")})]})},WalletGroupItem=({wallet:Xr,onClick:eo})=>{const[to]=Xr.walletConnector.supportedChains,{walletBook:ro}=useWalletBookContext(),no=getChainInfoWithOverrides(to),io=Xr.group?findWalletGroupOverride(ro,Xr.group,Xr.key):void 0,oo=getWalletListItemLabel({wallet:Xr}),ao=jsxRuntimeExports.jsx(ListTileAnimatedTrailing,{hoverElement:jsxRuntimeExports.jsx(Icon,{color:"text-tertiary",size:"mini",children:jsxRuntimeExports.jsx(SvgStroke,{})}),children:oo&&jsxRuntimeExports.jsx(Badge,{dot:!oo.isRecommended,variant:oo.isRecommended?"primary":"secondary",text:jsxRuntimeExports.jsx(Typography,{variant:"body_small",children:oo.label})})}),so=reactExports.useMemo(()=>{const lo={height:pixelToRem(28),width:pixelToRem(28)};if(io!=null&&io.brand)return jsxRuntimeExports.jsx(BrandIcon,{brand:io.brand,walletKey:Xr.key,style:lo});const fo=getChainIcon(to);return jsxRuntimeExports.jsx(fo,{style:lo})},[to,Xr.key,io]),co=(io==null?void 0:io.name)||(no==null?void 0:no.displayName)||Xr.name;return jsxRuntimeExports.jsx(ListTile,{className:"chain-card",onClick:eo,leading:so,trailing:ao,children:co},Xr.key)},WalletGroupView=()=>{const{selectedWalletGroup:Xr}=useWalletGroupContext(),{walletBook:eo}=useWalletBookContext(),{handleWalletItemClick:to}=useWalletItemActions(),{t:ro}=useTranslation();if(!Xr)throw new Error("Could not access WalletGroup view without selected group");const no=getWalletGroup(eo,Xr==null?void 0:Xr.key),io=Xr.groupedWallets.map(({walletConnector:oo})=>oo).filter(oo=>isHardwareWalletConnector(oo)&&oo.canConnectWithHardwareWallet());return jsxRuntimeExports.jsx(WalletGroupViewLayout,{icon:jsxRuntimeExports.jsx(WalletIcon,{walletKey:no.key}),title:ro("dyn_select_chain.description"),titleCopyKey:"dyn_select_chain.description",children:jsxRuntimeExports.jsxs("div",{className:"wallet-group__list",children:[!!io.length&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(HardwareWalletToggle,{connectors:io,copykey:"dyn_select_chain.using_hardware_wallet_toggle_label",label:ro("dyn_select_chain.using_hardware_wallet_toggle_label")}),jsxRuntimeExports.jsx(Divider,{})]}),jsxRuntimeExports.jsx("div",{className:"wallet-group-view-layout__list",children:Xr.groupedWallets.map((oo,ao)=>jsxRuntimeExports.jsx(WalletGroupItem,{wallet:oo,onClick:()=>to(oo)},`${oo.key}_${ao}`))})]})})},iconSize=64,WalletLockedView=()=>{const{handleLogOut:Xr,primaryWallet:eo,setShowAuthFlow:to,appName:ro}=useInternalDynamicContext(),{t:no}=useTranslation();if(!eo)return null;const io=()=>__awaiter$j(void 0,void 0,void 0,function*(){try{yield eo.connector.connect(),to(!1)}catch{logger$8.info("could not connect wallet")}}),oo=jsxRuntimeExports.jsx(WalletIcon,{walletKey:eo.connector.key,style:{height:pixelToRem(iconSize*iconRatio),width:pixelToRem(iconSize*iconRatio)}});return jsxRuntimeExports.jsxs("div",{"data-testid":"wallet-locked-view",children:[jsxRuntimeExports.jsx(ErrorContainer,{withIcon:!1,variant:"success",className:"wallet-locked-view__error-container",copykey:"dyn_wallet_locked.connect_continue",children:no("dyn_wallet_locked.connect_continue")}),jsxRuntimeExports.jsxs("div",{className:"wallet-locked-view__content",children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:oo,iconSize,className:"wallet-locked-view__icon",isSpinning:!0}),jsxRuntimeExports.jsx(Typography,{variant:"title",color:"primary",weight:"medium",className:"wallet-locked-view__title",copykey:"dyn_wallet_locked.title",children:no("dyn_wallet_locked.title")}),jsxRuntimeExports.jsxs(Typography,{variant:"body_normal",color:"secondary",weight:"regular",copykey:"dyn_wallet_locked.subtitle",children:[no("dyn_wallet_locked.subtitle"),ro,"."]}),jsxRuntimeExports.jsx(TypographyButton,{onClick:()=>io(),buttonClassName:"wallet-locked-view__button",copykey:"dyn_wallet_locked.connect",children:no("dyn_wallet_locked.connect")}),jsxRuntimeExports.jsx(Divider,{text:"Or"}),jsxRuntimeExports.jsx(TextButton,{className:"wallet-locked-view__log-out",onClick:Xr,copykey:"dyn_wallet_locked.logout",children:no("dyn_wallet_locked.logout")})]})]})},WalletRedirectView=()=>{const{t:Xr}=useTranslation(),{selectedWalletConnector:eo}=useInternalDynamicContext();return jsxRuntimeExports.jsxs("div",{className:classNames("wallet-redirect-view__container"),children:[eo&&jsxRuntimeExports.jsx(IconWithSpinner,{iconSize:64,Icon:jsxRuntimeExports.jsx(WalletIcon,{walletKey:eo.key}),isSpinning:!0}),jsxRuntimeExports.jsx(Typography,{weight:"medium",variant:"title",className:classNames("wallet-redirect-view__title"),copykey:"dyn_wallet_redirect.loading",children:Xr("dyn_wallet_redirect.loading")}),jsxRuntimeExports.jsx(PoweredByDynamic,{classNameRoot:"powered-by-dynamic"})]})},WalletSignSpinnerView=()=>{const{goToInitialView:Xr}=useViewContext(),{t:eo}=useTranslation(),{setMultiWalletWidgetState:to,setSelectedWalletConnectorKey:ro,selectedWalletConnector:no}=useInternalDynamicContext();if(!no)return null;const{key:io}=no,oo=96,ao=()=>__awaiter$j(void 0,void 0,void 0,function*(){Xr(),to("idle"),ro(null),yield no==null?void 0:no.endSession()}),so=jsxRuntimeExports.jsx(WalletIcon,{walletKey:io,style:{height:pixelToRem(oo*iconRatio),width:pixelToRem(oo*iconRatio)}});return jsxRuntimeExports.jsxs("div",{className:"wallet-sign-spinner__container","data-testid":"wallet-sign-spinner-view",children:[jsxRuntimeExports.jsx(IconWithSpinner,{Icon:so,iconSize:oo,isSpinning:!0}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",className:classNames("wallet-sign-spinner__copy"),copykey:"dyn_wallet_transfer.sign.spinner.confirm_transfer",children:eo("dyn_wallet_transfer.sign.spinner.confirm_transfer")}),jsxRuntimeExports.jsx(TypographyButton,{expanded:!0,buttonPadding:"large",buttonVariant:"primary",buttonClassName:"wallet-sign-spinner__button",onClick:()=>ao(),typographyProps:{variant:"button_primary",weight:"medium"},copykey:"dyn_wallet_transfer.sign.spinner.cancel",children:eo("dyn_wallet_transfer.sign.spinner.cancel")})]})},useTransferWallet=()=>{const{displaySiweStatement:Xr,environmentId:eo,user:to,primaryWallet:ro,setPrimaryWalletId:no}=useInternalDynamicContext(),{addedWalletsIds:io}=useInternalUserWallets(),oo=reactExports.useCallback((ao,so)=>{const co=ao.key;if(so.lastVerifiedCredentialId){if(!ro){no(so.lastVerifiedCredentialId);return}const lo=ro.connector.key;co===lo&&no(so.lastVerifiedCredentialId),ro.connector.connectedChain==="FLOW"&&ao.connectedChain==="FLOW"&&no(so.lastVerifiedCredentialId)}},[ro,no]);return reactExports.useCallback(ao=>__awaiter$j(void 0,void 0,void 0,function*(){if(!to)throw new DynamicError(USER_NOT_LOGGED_IN);const{overrideSiweStatement:so,walletConnector:co}=ao,lo="nonce"in ao?Object.assign(Object.assign({},ao),{displaySiweStatement:Xr,environmentId:eo,siweStatement:so,walletProvider:getWalletProvider(co)}):Object.assign(Object.assign({},ao),{displaySiweStatement:Xr,environmentId:eo,nonce:"",siweStatement:ao.overrideSiweStatement,walletProvider:getWalletProvider(co)}),fo=yield getVerifyArgs(lo),ho=yield transferWallet(eo,fo);if(!ho)throw new DynamicError("Error transferring wallet.");oo(co,ho);const go=ho.lastVerifiedCredentialId;go&&io.current.push(go)}),[io,Xr,eo,oo,to])},WalletUsedView=()=>{const[Xr,eo]=reactExports.useState(!1),{t:to}=useTranslation(),{setErrorMessage:ro}=useErrorContext(),{loading:no,setLoading:io}=useLoadingContext(),{setView:oo,goToInitialView:ao}=useViewContext(),{setShowAuthFlow:so,appName:co,siweStatement:lo,setMultiWalletWidgetState:fo,connectWallet:ho,selectedWalletConnector:go,isSingleWalletAccount:yo,consumeNonce:vo,handleLogOut:wo}=useInternalDynamicContext(),{data:Eo}=usePromise(()=>__awaiter$j(void 0,void 0,void 0,function*(){const jo=yield go==null?void 0:go.getConnectedAccounts();return jo==null?void 0:jo[0]}),{deps:[go]}),ko=shortenWalletAddress(Eo),Ao=useTransferWallet(),Po=()=>__awaiter$j(void 0,void 0,void 0,function*(){if(!go)return;const jo=vo();if(!jo){ao(),ro("missing-nonce");return}fo("awaiting_signature",void 0,"transferring_wallet"),io(!0),oo("wallet-sign");const Mo=getSiweStatement({appName:co,siweStatement:lo});try{const No=yield ho(go);if(!(No!=null&&No.address))return;go.key==="phantom"&&isMobile$1()&&StorageService.setItem(PHANTOM_SIGNATURE_STATE,{loseOriginalAccountOnTransfer:Xr,submittedAtTimestamp:new Date().toString(),verificationType:"awaiting_transfer"}),yield Ao({nonce:jo,overrideSiweStatement:Mo,publicWalletAddress:No.address,skipEmptyAccountCheck:Xr,walletConnector:go}),so(!1)}catch(No){logger$8.error(No),so(!1,{emitCancelAuth:!0})}finally{io(!1),fo("idle")}});return jsxRuntimeExports.jsxs("div",{className:"wallet-used-view__container",children:[jsxRuntimeExports.jsx("div",{className:"wallet-used-view__icon",children:jsxRuntimeExports.jsx(WalletIcon,{walletKey:go==null?void 0:go.key,width:64,height:64})}),jsxRuntimeExports.jsx(Typography,{className:"wallet-used-view__shorten-wallet-address",variant:"body_normal",weight:"medium",color:"primary",children:ko}),jsxRuntimeExports.jsx(Typography,{className:"wallet-used-view__copy",variant:"body_normal",color:"secondary",weight:"regular",copykey:"dyn_wallet_link.existent_account.warning",children:to("dyn_wallet_link.existent_account.warning")}),yo&&jsxRuntimeExports.jsxs("label",{htmlFor:"skipEmptyAccountCheck",className:"wallet-used-view__checkbox-label",children:[jsxRuntimeExports.jsx(Checkbox,{id:"skipEmptyAccountCheck",className:"wallet-used-view__checkbox-container",defaultChecked:Xr,onChange:()=>eo(!Xr),ariaLabel:"skip empty account check"}),jsxRuntimeExports.jsx(Typography,{variant:"body_small",color:"secondary",copykey:"dyn_wallet_link.existent_account.acceptance",children:to("dyn_wallet_link.existent_account.acceptance")})]}),jsxRuntimeExports.jsx(TypographyButton,{buttonClassName:"wallet-used-view__accept-button",buttonVariant:"primary",expanded:!0,buttonPadding:"large",onClick:()=>Po(),disabled:!Xr&&yo||no,dataTestId:"wallet-used-view-transfer-wallet",copykey:"dyn_wallet_link.confirm_button",children:to("dyn_wallet_link.confirm_button")}),jsxRuntimeExports.jsx(TypographyButton,{dataTestId:"wallet-used-view-log-out",buttonPadding:"small",buttonClassName:"wallet-used-view__logout",onClick:wo,copykey:"dyn_wallet_link.log_out_button",children:to("dyn_wallet_link.log_out_button")})]})};var _path$2,_excluded$2=["title","titleId"];function _extends$4(){return _extends$4=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$2(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgDomain=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$2(eo,_excluded$2);return reactExports.createElement("svg",_extends$4({width:65,height:64,viewBox:"0 0 65 64",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_path$2||(_path$2=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32.5 64c17.673 0 32-14.327 32-32 0-17.673-14.327-32-32-32C14.827 0 .5 14.327.5 32c0 17.673 14.327 32 32 32Zm-4.928-29.305h9.717c-.207 4.908-1.087 9.168-2.3 12.206-.7 1.756-1.433 2.9-2.036 3.54-.245.26-.42.387-.523.448-.102-.06-.277-.189-.522-.449-.603-.638-1.336-1.783-2.037-3.539-1.213-3.038-2.092-7.298-2.3-12.206Zm2.3-16.655c-1.242 3.108-2.134 7.497-2.314 12.55h9.744c-.18-5.053-1.071-9.442-2.313-12.55-.7-1.756-1.433-2.9-2.036-3.54-.245-.26-.42-.388-.523-.449-.102.061-.277.19-.522.45-.603.638-1.336 1.783-2.037 3.539ZM14.5 30.59h8.951c.216-6.53 1.541-12.27 3.503-16.036C20.23 16.789 15.22 23.03 14.5 30.59Zm.036 4.105h8.928c.25 6.387 1.563 11.993 3.49 15.692-6.622-2.201-11.582-8.288-12.418-15.692Zm35.789 0h-8.928c-.25 6.387-1.563 11.993-3.49 15.692 6.621-2.201 11.581-8.288 12.418-15.692Zm.125-2.224v.066-.133.066Zm-9.04-1.88h8.95c-.719-7.56-5.73-13.802-12.454-16.037 1.962 3.766 3.288 9.507 3.503 16.036Zm-9.09 20.35c0-.001.008-.004.023-.007-.015.006-.023.008-.023.007Zm.198-.007a.072.072 0 0 1 .023.007s-.008-.001-.023-.007ZM32.541 14s-.008.004-.023.007c.015-.006.023-.008.023-.007Zm-.198.007A.068.068 0 0 1 32.32 14s.008.001.023.007Z",fill:"#4779FF"})))};const PasskeyNewDomainDetectedView=()=>{const{t:Xr}=useTranslation(),{projectSettings:eo}=useInternalDynamicContext(),to=reactExports.useMemo(()=>{var ro;const no=getEnabledEmbeddedWalletsAuthenticators((ro=eo==null?void 0:eo.sdk.embeddedWallets)===null||ro===void 0?void 0:ro.supportedSecurityMethods);return Object.keys(no).filter(io=>io!=="email")},[eo==null?void 0:eo.sdk.embeddedWallets]);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalHeader,{children:jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary","data-testid":"dynamic-auth-modal-heading",className:"header__typography",copykey:"dyn_passkey_new_domain_detected.title",children:Xr("dyn_passkey_new_domain_detected.title")})}),jsxRuntimeExports.jsxs("div",{className:"passkey-new-domain-detected",children:[jsxRuntimeExports.jsx(SvgDomain,{className:"passkey-new-domain-detected__header"}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",children:Xr("dyn_passkey_new_domain_detected.description")}),jsxRuntimeExports.jsx(EmbeddedAuthChoiceCards,{supportedAuthenticators:to}),jsxRuntimeExports.jsx(NeedHelpSection,{isRecoveryFlow:!0})]})]})},viewToComponentMap={"access-blocked":AccessBlockedView,"account-exists":AccountExistsView,"bridge-next-wallet-connection":BridgeNextWalletConnectionView,"bridge-summary":BridgeSummaryView,"bridge-welcome":BridgeWelcomeView,captcha:CaptchaVerifyUser,"chainalysis-blocked-wallet":NoAccess,"collect-user-data":CollectUserDataView,"collect-user-data-login-no-wallet":CollectUserDataViewNoWallet,"create-password-view":CreatePasswordView,"email-wallet-otp-verification-view":EmailWalletOTPVerificationView,"embedded-reveal-account-view":EmbeddedRevealView,"embedded-reveal-view":EmbeddedRevealView,"embedded-wallet-auth-choice":EmbeddedAuthChoice,"farcaster-connect-view":FarcasterConnectView,"gate-blocked-wallet":NoAccess,"global-wallet-confirm":GlobalWalletConfirmView,"global-wallet-info":GlobalWalletInfoView,"global-wallet-malicious":GlobalWalletMaliciousView,"login-with-email-or-wallet":LoginView,"login-with-email-or-wallet-full-wallet-list":WalletList,"login-with-email-verification":EmailVerification,"login-with-sms-verification":SmsVerification,"login-with-wallet-only":LoginView,"merge-user-accounts":MergeUserAccountsView,"merge-user-accounts-conflicts":MergeUserAccountsConflictsView,"merge-user-accounts-with-same-email":MergeUserAccountsWithSameEmailView,"mfa-choose-device":MfaChooseDeviceView,"mfa-display-backup-codes":MfaDisplayBackupCodesView,"mfa-recovery":MfaRecoveryView,"mfa-secure-device":MfaSecureDeviceView,"mfa-secure-device-help":MfaSecureDeviceHelper,"mfa-verification":MfaVerificationView,"mobile-wallet-redirect-view":MobileWalletRedirectView,"multi-wallet-wallet-list":WalletList,"network-not-supported":NetworkNotSupported,"network-not-supported-manual":NetworkNotSupportedSwitchManual,"no-access":NoAccess,"no-qr-not-installed":NoQrNotInstalledView,"passkey-intro":PasskeyIntroView,"passkey-new-domain-detected":PasskeyNewDomainDetectedView,"passkey-recovery-add-email":AddRecoveryEmail,"passkey-recovery-bundle":PasskeyBundleRecovery,"passkey-recovery-complete":PasskeyCompleteRecovery,"passkey-recovery-start":PasskeyInitRecovery,"pending-connect":PendingConnectView,"pending-signature":PendingSignatureView,"pending-signature-without-back-button":PendingSignatureView,"qr-code":QrCodeView,"rename-passkey":RenamePasskeyView,"sandbox-maximum-threshold-reached":SandboxMaximumThresholdReached,"select-hardware-wallet":SelectHardwareWalletView,"select-wallet-in-wallet-group":SelectWalletInWalletGroupView,"social-redirect-view":SocialRedirectView,"social-wrong-account":SocialWrongAccountView,"verify-email":EmailVerification,"verify-sms":SmsVerification,"wait-for-email-confirmation-view":EmailConfirmationWaitingView,"wallet-cannot-be-transferred":WalletCannotBeTransferredView,"wallet-claim-intro":CoinbaseMPCClaimIntro,"wallet-connect-mobile-wallets-list":()=>jsxRuntimeExports.jsx(WalletList,{isWalletConnectList:!0}),"wallet-group":WalletGroupView,"wallet-list":WalletList,"wallet-locked-view":WalletLockedView,"wallet-redirect-view":WalletRedirectView,"wallet-sign":WalletSignSpinnerView,"wallet-used":WalletUsedView},RenderView=()=>{const{view:Xr}=useViewContext(),eo=viewToComponentMap[Xr.type];return jsxRuntimeExports.jsx(eo,Object.assign({},Xr.props||{}))};function styleInject(Xr,eo){eo===void 0&&(eo={});var to=eo.insertAt;if(!(typeof document>"u")){var ro=document.head||document.getElementsByTagName("head")[0],no=document.createElement("style");no.type="text/css",to==="top"&&ro.firstChild?ro.insertBefore(no,ro.firstChild):ro.appendChild(no),no.styleSheet?no.styleSheet.cssText=Xr:no.appendChild(document.createTextNode(Xr))}}var css_248z='@layer dynamic-sdk-styles{#argent-mobile-modal-overlay,iframe[src*="wallet-dev.blocto.app"],iframe[src*="wallet-staging.blocto.app"],iframe[src*="wallet-testnet.blocto.app"],iframe[src*="wallet.blocto.app"]{z-index:2147483647!important}iframe[id*=dyn-passkey-recovery-element-id],iframe[id*=dyn-secure-enclave-element-id]{display:none!important}#pera-wallet-connect-modal-wrapper{position:relative;z-index:2147483647!important}@font-face{font-display:swap;font-family:DM Sans;font-style:normal;font-weight:400;src:url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-400-normal.woff2) format("woff2"),url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-400-normal.woff) format("woff")}@font-face{font-display:swap;font-family:DM Sans;font-style:italic;font-weight:400;src:url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-400-italic.woff2) format("woff2"),url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-400-italic.woff) format("woff")}@font-face{font-display:swap;font-family:DM Sans;font-style:normal;font-weight:500;src:url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-500-normal.woff2) format("woff2"),url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-500-normal.woff) format("woff")}@font-face{font-display:swap;font-family:DM Sans;font-style:italic;font-weight:500;src:url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-500-italic.woff2) format("woff2"),url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-500-italic.woff) format("woff")}@font-face{font-display:swap;font-family:DM Sans;font-style:normal;font-weight:700;src:url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-700-normal.woff2) format("woff2"),url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-700-normal.woff) format("woff")}@font-face{font-display:swap;font-family:DM Sans;font-style:italic;font-weight:700;src:url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-700-italic.woff2) format("woff2"),url(https://cdn.jsdelivr.net/npm/@fontsource/dm-sans/files/dm-sans-latin-700-italic.woff) format("woff")}@layer light-theme-default{:root{--dynamic-font-family-primary:"DM Sans",sans-serif;--dynamic-search-border-radius:1rem;--dynamic-font-family-numbers:"Roboto Mono",monospace,sans-serif;--dynamic-base-1:#f7f7f9;--dynamic-base-2:#fff;--dynamic-base-3:#eeeef1;--dynamic-base-4:#e7e8ed;--dynamic-brand-hover-color:linear-gradient(0deg,rgba(0,0,0,.08),rgba(0,0,0,.08)),#4779ff;--dynamic-brand-primary-color:#4779ff;--dynamic-brand-secondary-color:rgba(71,121,255,.15);--dynamic-success-1:#30a67b;--dynamic-success-2:#e3f7ef;--dynamic-border-radius:1.5rem;--dynamic-hover:rgba(22,37,77,.03);--dynamic-info-2:rgba(71,121,255,.1);--dynamic-error-1:#ff4646;--dynamic-error-2:rgba(255,70,70,.1);--dynamic-alert-1:#dd8500;--dynamic-alert-2:#faedd9;--dynamic-footer-background-color:#fff;--dynamic-footer-text-color:#383c48;--dynamic-footer-icon-color:#4779ff;--dynamic-loading-animation-gradient:linear-gradient(90deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2) 20%,hsla(0,0%,100%,.5) 60%,hsla(0,0%,100%,0));--dynamic-overlay:rgba(24,27,34,.15);--dynamic-shadow-down-1:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-shadow-down-2:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-shadow-down-3:0 1.5rem 2rem -1.5rem rgba(0,0,0,.24);--dynamic-shadow-up-1:0 -0.5rem 3rem -0.5rem rgba(109,121,165,.16);--dynamic-text-link:#0047ff;--dynamic-text-primary:#383c48;--dynamic-text-secondary:#7b7d86;--dynamic-text-size-body-mini:0.6875rem;--dynamic-text-size-body-normal:0.9375rem;--dynamic-text-size-body-small:0.75rem;--dynamic-text-size-button-primary:0.875rem;--dynamic-text-size-button-secondary:0.75rem;--dynamic-text-size-numbers-big:0.875rem;--dynamic-text-size-numbers-medium:0.75rem;--dynamic-text-size-title:1.125rem;--dynamic-text-tertiary:#abacb2;--dynamic-badge-background:#eeeef1;--dynamic-badge-color:#7b7d86;--dynamic-badge-primary-background:#e3f7ef;--dynamic-badge-primary-color:#30a67b;--dynamic-badge-dot-background:#4779ff;--dynamic-search-bar-background:#fff;--dynamic-search-bar-background-hover:#fff;--dynamic-search-bar-background-focus:#fff;--dynamic-search-bar-border:0.0625rem solid #eeeef1;--dynamic-search-bar-border-hover:0.0625rem solid #e7e8ed;--dynamic-search-bar-border-focus:0.0625rem solid #e7e8ed;--dynamic-modal-border: ;--dynamic-modal-width:22.5rem;--dynamic-modal-padding:1.5rem;--dynamic-modal-backdrop-background:rgba(0,0,0,.25);--dynamic-modal-backdrop-filter:blur(4px);--dynamic-wallet-list-tile-padding:0.75rem;--dynamic-wallet-list-tile-gap:0.375rem;--dynamic-wallet-list-max-height:16.25rem;--dynamic-wallet-list-tile-background:#fff;--dynamic-wallet-list-tile-border: ;--dynamic-wallet-list-tile-shadow:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-background-hover:#fff;--dynamic-wallet-list-tile-border-hover: ;--dynamic-wallet-list-tile-border-radius:0.75rem;--dynamic-wallet-list-tile-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-animation-duration:150ms;--dynamic-tooltip-color:#383c48;--dynamic-tooltip-text-color:#fff;--dynamic-button-border-radius:0.75rem;--dynamic-initial-view-content-padding:0rem 1.5rem 1.5rem;--dynamic-button-primary-hover:#fff;--dynamic-button-primary-background:#fff;--dynamic-button-primary-font-size:0.875rem;--dynamic-button-primary-padding:0;--dynamic-button-primary-border:0.0625rem solid #e7e8ed;--dynamic-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-button-secondary-hover:#f7f8fa;--dynamic-button-secondary-background:transparent;--dynamic-button-secondary-font-size:0.75rem;--dynamic-button-secondary-padding:0;--dynamic-button-secondary-border:0.0625rem solid transparent;--dynamic-connect-button-background:#fff;--dynamic-connect-button-background-hover:#fff;--dynamic-connect-button-color:#383c48;--dynamic-connect-button-border:0.0625rem solid #e7e8ed;--dynamic-connect-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-connect-button-color-hover:#383c48;--dynamic-connect-button-border-hover:0.0625rem solid #e7e8ed;--dynamic-connect-button-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-search-padding:0 1.5rem 0.5rem;--dynamic-layout-content-padding:0 1.5rem 1.5rem;--dynamic-layout-content-error-padding:1.5rem 1.5rem 1.5rem;--dynamic-footer-border-top:0.0625rem solid #e7e8ed;--dynamic-footer-padding:0.75rem 1.5rem 0.75rem;--dynamic-footer-background:transparent;--dynamic-header-border-bottom:1px solid transparent;--dynamic-header-padding:1.5rem 1.5rem 1.25rem;--dynamic-header-background:transparent}:root [data-dynamic-theme-brand=bold],:root[data-dynamic-theme-brand=bold]{--dynamic-footer-text-color:#fff;--dynamic-footer-icon-color:rgba(247,247,249,.75);--dynamic-footer-arrow-color:rgba(247,247,249,.75)}:root [data-dynamic-theme-brand=subtle],:root[data-dynamic-theme-brand=subtle]{--dynamic-footer-arrow-color:#abacb2}@media (prefers-color-scheme:light){:root [data-dynamic-theme=auto]{--dynamic-font-family-primary:"DM Sans",sans-serif;--dynamic-search-border-radius:1rem;--dynamic-font-family-numbers:"Roboto Mono",monospace,sans-serif;--dynamic-base-1:#f7f7f9;--dynamic-base-2:#fff;--dynamic-base-3:#eeeef1;--dynamic-base-4:#e7e8ed;--dynamic-brand-hover-color:linear-gradient(0deg,rgba(0,0,0,.08),rgba(0,0,0,.08)),#4779ff;--dynamic-brand-primary-color:#4779ff;--dynamic-brand-secondary-color:rgba(71,121,255,.15);--dynamic-success-1:#30a67b;--dynamic-success-2:#e3f7ef;--dynamic-border-radius:1.5rem;--dynamic-hover:rgba(22,37,77,.03);--dynamic-info-2:rgba(71,121,255,.1);--dynamic-error-1:#ff4646;--dynamic-error-2:rgba(255,70,70,.1);--dynamic-alert-1:#dd8500;--dynamic-alert-2:#faedd9;--dynamic-footer-background-color:#fff;--dynamic-footer-text-color:#383c48;--dynamic-footer-icon-color:#4779ff;--dynamic-loading-animation-gradient:linear-gradient(90deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2) 20%,hsla(0,0%,100%,.5) 60%,hsla(0,0%,100%,0));--dynamic-overlay:rgba(24,27,34,.15);--dynamic-shadow-down-1:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-shadow-down-2:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-shadow-down-3:0 1.5rem 2rem -1.5rem rgba(0,0,0,.24);--dynamic-shadow-up-1:0 -0.5rem 3rem -0.5rem rgba(109,121,165,.16);--dynamic-text-link:#0047ff;--dynamic-text-primary:#383c48;--dynamic-text-secondary:#7b7d86;--dynamic-text-size-body-mini:0.6875rem;--dynamic-text-size-body-normal:0.9375rem;--dynamic-text-size-body-small:0.75rem;--dynamic-text-size-button-primary:0.875rem;--dynamic-text-size-button-secondary:0.75rem;--dynamic-text-size-numbers-big:0.875rem;--dynamic-text-size-numbers-medium:0.75rem;--dynamic-text-size-title:1.125rem;--dynamic-text-tertiary:#abacb2;--dynamic-badge-background:#eeeef1;--dynamic-badge-color:#7b7d86;--dynamic-badge-primary-background:#e3f7ef;--dynamic-badge-primary-color:#30a67b;--dynamic-badge-dot-background:#4779ff;--dynamic-search-bar-background:#fff;--dynamic-search-bar-background-hover:#fff;--dynamic-search-bar-background-focus:#fff;--dynamic-search-bar-border:0.0625rem solid #eeeef1;--dynamic-search-bar-border-hover:0.0625rem solid #e7e8ed;--dynamic-search-bar-border-focus:0.0625rem solid #e7e8ed;--dynamic-modal-border: ;--dynamic-modal-width:22.5rem;--dynamic-modal-padding:1.5rem;--dynamic-modal-backdrop-background:rgba(0,0,0,.25);--dynamic-modal-backdrop-filter:blur(4px);--dynamic-wallet-list-tile-padding:0.75rem;--dynamic-wallet-list-tile-gap:0.375rem;--dynamic-wallet-list-max-height:16.25rem;--dynamic-wallet-list-tile-background:#fff;--dynamic-wallet-list-tile-border: ;--dynamic-wallet-list-tile-shadow:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-background-hover:#fff;--dynamic-wallet-list-tile-border-hover: ;--dynamic-wallet-list-tile-border-radius:0.75rem;--dynamic-wallet-list-tile-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-animation-duration:150ms;--dynamic-tooltip-color:#383c48;--dynamic-tooltip-text-color:#fff;--dynamic-button-border-radius:0.75rem;--dynamic-initial-view-content-padding:0rem 1.5rem 1.5rem;--dynamic-button-primary-hover:#fff;--dynamic-button-primary-background:#fff;--dynamic-button-primary-font-size:0.875rem;--dynamic-button-primary-padding:0;--dynamic-button-primary-border:0.0625rem solid #e7e8ed;--dynamic-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-button-secondary-hover:#f7f8fa;--dynamic-button-secondary-background:transparent;--dynamic-button-secondary-font-size:0.75rem;--dynamic-button-secondary-padding:0;--dynamic-button-secondary-border:0.0625rem solid transparent;--dynamic-connect-button-background:#fff;--dynamic-connect-button-background-hover:#fff;--dynamic-connect-button-color:#383c48;--dynamic-connect-button-border:0.0625rem solid #e7e8ed;--dynamic-connect-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-connect-button-color-hover:#383c48;--dynamic-connect-button-border-hover:0.0625rem solid #e7e8ed;--dynamic-connect-button-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-search-padding:0 1.5rem 0.5rem;--dynamic-layout-content-padding:0 1.5rem 1.5rem;--dynamic-layout-content-error-padding:1.5rem 1.5rem 1.5rem;--dynamic-footer-border-top:0.0625rem solid #e7e8ed;--dynamic-footer-padding:0.75rem 1.5rem 0.75rem;--dynamic-footer-background:transparent;--dynamic-header-border-bottom:1px solid transparent;--dynamic-header-padding:1.5rem 1.5rem 1.25rem;--dynamic-header-background:transparent}:root [data-dynamic-theme=auto] [data-dynamic-theme-brand=bold],:root [data-dynamic-theme=auto][data-dynamic-theme-brand=bold]{--dynamic-footer-text-color:#fff;--dynamic-footer-icon-color:rgba(247,247,249,.75);--dynamic-footer-arrow-color:rgba(247,247,249,.75)}:root [data-dynamic-theme=auto] [data-dynamic-theme-brand=subtle],:root [data-dynamic-theme=auto][data-dynamic-theme-brand=subtle]{--dynamic-footer-arrow-color:#abacb2}}:root [data-dynamic-theme=light]{--dynamic-font-family-primary:"DM Sans",sans-serif;--dynamic-search-border-radius:1rem;--dynamic-font-family-numbers:"Roboto Mono",monospace,sans-serif;--dynamic-base-1:#f7f7f9;--dynamic-base-2:#fff;--dynamic-base-3:#eeeef1;--dynamic-base-4:#e7e8ed;--dynamic-brand-hover-color:linear-gradient(0deg,rgba(0,0,0,.08),rgba(0,0,0,.08)),#4779ff;--dynamic-brand-primary-color:#4779ff;--dynamic-brand-secondary-color:rgba(71,121,255,.15);--dynamic-success-1:#30a67b;--dynamic-success-2:#e3f7ef;--dynamic-border-radius:1.5rem;--dynamic-hover:rgba(22,37,77,.03);--dynamic-info-2:rgba(71,121,255,.1);--dynamic-error-1:#ff4646;--dynamic-error-2:rgba(255,70,70,.1);--dynamic-alert-1:#dd8500;--dynamic-alert-2:#faedd9;--dynamic-footer-background-color:#fff;--dynamic-footer-text-color:#383c48;--dynamic-footer-icon-color:#4779ff;--dynamic-loading-animation-gradient:linear-gradient(90deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2) 20%,hsla(0,0%,100%,.5) 60%,hsla(0,0%,100%,0));--dynamic-overlay:rgba(24,27,34,.15);--dynamic-shadow-down-1:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-shadow-down-2:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-shadow-down-3:0 1.5rem 2rem -1.5rem rgba(0,0,0,.24);--dynamic-shadow-up-1:0 -0.5rem 3rem -0.5rem rgba(109,121,165,.16);--dynamic-text-link:#0047ff;--dynamic-text-primary:#383c48;--dynamic-text-secondary:#7b7d86;--dynamic-text-size-body-mini:0.6875rem;--dynamic-text-size-body-normal:0.9375rem;--dynamic-text-size-body-small:0.75rem;--dynamic-text-size-button-primary:0.875rem;--dynamic-text-size-button-secondary:0.75rem;--dynamic-text-size-numbers-big:0.875rem;--dynamic-text-size-numbers-medium:0.75rem;--dynamic-text-size-title:1.125rem;--dynamic-text-tertiary:#abacb2;--dynamic-badge-background:#eeeef1;--dynamic-badge-color:#7b7d86;--dynamic-badge-primary-background:#e3f7ef;--dynamic-badge-primary-color:#30a67b;--dynamic-badge-dot-background:#4779ff;--dynamic-search-bar-background:#fff;--dynamic-search-bar-background-hover:#fff;--dynamic-search-bar-background-focus:#fff;--dynamic-search-bar-border:0.0625rem solid #eeeef1;--dynamic-search-bar-border-hover:0.0625rem solid #e7e8ed;--dynamic-search-bar-border-focus:0.0625rem solid #e7e8ed;--dynamic-modal-border: ;--dynamic-modal-width:22.5rem;--dynamic-modal-padding:1.5rem;--dynamic-modal-backdrop-background:rgba(0,0,0,.25);--dynamic-modal-backdrop-filter:blur(4px);--dynamic-wallet-list-tile-padding:0.75rem;--dynamic-wallet-list-tile-gap:0.375rem;--dynamic-wallet-list-max-height:16.25rem;--dynamic-wallet-list-tile-background:#fff;--dynamic-wallet-list-tile-border: ;--dynamic-wallet-list-tile-shadow:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-background-hover:#fff;--dynamic-wallet-list-tile-border-hover: ;--dynamic-wallet-list-tile-border-radius:0.75rem;--dynamic-wallet-list-tile-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-animation-duration:150ms;--dynamic-tooltip-color:#383c48;--dynamic-tooltip-text-color:#fff;--dynamic-button-border-radius:0.75rem;--dynamic-initial-view-content-padding:0rem 1.5rem 1.5rem;--dynamic-button-primary-hover:#fff;--dynamic-button-primary-background:#fff;--dynamic-button-primary-font-size:0.875rem;--dynamic-button-primary-padding:0;--dynamic-button-primary-border:0.0625rem solid #e7e8ed;--dynamic-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-button-secondary-hover:#f7f8fa;--dynamic-button-secondary-background:transparent;--dynamic-button-secondary-font-size:0.75rem;--dynamic-button-secondary-padding:0;--dynamic-button-secondary-border:0.0625rem solid transparent;--dynamic-connect-button-background:#fff;--dynamic-connect-button-background-hover:#fff;--dynamic-connect-button-color:#383c48;--dynamic-connect-button-border:0.0625rem solid #e7e8ed;--dynamic-connect-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-connect-button-color-hover:#383c48;--dynamic-connect-button-border-hover:0.0625rem solid #e7e8ed;--dynamic-connect-button-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-search-padding:0 1.5rem 0.5rem;--dynamic-layout-content-padding:0 1.5rem 1.5rem;--dynamic-layout-content-error-padding:1.5rem 1.5rem 1.5rem;--dynamic-footer-border-top:0.0625rem solid #e7e8ed;--dynamic-footer-padding:0.75rem 1.5rem 0.75rem;--dynamic-footer-background:transparent;--dynamic-header-border-bottom:1px solid transparent;--dynamic-header-padding:1.5rem 1.5rem 1.25rem;--dynamic-header-background:transparent}:root [data-dynamic-theme=light] [data-dynamic-theme-brand=bold],:root [data-dynamic-theme=light][data-dynamic-theme-brand=bold]{--dynamic-footer-text-color:#fff;--dynamic-footer-icon-color:rgba(247,247,249,.75);--dynamic-footer-arrow-color:rgba(247,247,249,.75)}:root [data-dynamic-theme=light] [data-dynamic-theme-brand=subtle],:root [data-dynamic-theme=light][data-dynamic-theme-brand=subtle]{--dynamic-footer-arrow-color:#abacb2}}@layer dark-theme-default{@media (prefers-color-scheme:dark){:root [data-dynamic-theme=auto]{--dynamic-font-family-primary:"DM Sans",sans-serif;--dynamic-search-border-radius:1rem;--dynamic-font-family-numbers:"Roboto Mono",monospace,sans-serif;--dynamic-base-1:#0c0e13;--dynamic-base-2:#1b1d22;--dynamic-base-3:#24272e;--dynamic-base-4:#282b33;--dynamic-brand-hover-color:linear-gradient(0deg,rgba(0,0,0,.08),rgba(0,0,0,.08)),#4779ff;--dynamic-brand-primary-color:#4779ff;--dynamic-brand-secondary-color:rgba(71,121,255,.15);--dynamic-success-1:#79ffcf;--dynamic-success-2:#192d2c;--dynamic-border-radius:1.5rem;--dynamic-hover:hsla(0,0%,100%,.1);--dynamic-error-1:#ff6a6a;--dynamic-error-2:hsla(0,100%,71%,.2);--dynamic-alert-1:#e2a140;--dynamic-alert-2:#2b2621;--dynamic-footer-background-color:#0c0e13;--dynamic-footer-text-color:#fbfcff;--dynamic-footer-icon-color:#4779ff;--dynamic-loading-animation-gradient:linear-gradient(90deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.01) 20%,hsla(0,0%,100%,.05) 60%,hsla(0,0%,100%,0));--dynamic-overlay:rgba(0,0,0,.25);--dynamic-shadow-down-1:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-shadow-down-2:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-shadow-down-3:0 1.5rem 2rem -1.5rem rgba(0,0,0,.24);--dynamic-shadow-up-1:0 -0.5rem 3rem -0.5rem rgba(109,121,165,.16);--dynamic-text-link:#69a5ff;--dynamic-text-primary:#fbfcff;--dynamic-text-secondary:#a8aab0;--dynamic-text-size-body-mini:0.6875rem;--dynamic-text-size-body-normal:0.9375rem;--dynamic-text-size-body-small:0.75rem;--dynamic-text-size-button-primary:0.875rem;--dynamic-text-size-button-secondary:0.75rem;--dynamic-text-size-numbers-big:0.875rem;--dynamic-text-size-numbers-medium:0.75rem;--dynamic-text-size-title:1.125rem;--dynamic-text-tertiary:#6f7177;--dynamic-badge-background:#24272e;--dynamic-badge-color:#a8aab0;--dynamic-badge-dot-background:#4779ff;--dynamic-search-bar-background:#1b1d22;--dynamic-search-bar-background-hover:#1b1d22;--dynamic-search-bar-background-focus:#1b1d22;--dynamic-search-bar-border:0.0625rem solid #24272e;--dynamic-search-bar-border-hover:0.0625rem solid #282b33;--dynamic-search-bar-border-focus:0.0625rem solid #282b33;--dynamic-modal-border: ;--dynamic-modal-width:22.5rem;--dynamic-modal-padding:1.5rem;--dynamic-modal-backdrop-background:rgba(0,0,0,.25);--dynamic-modal-backdrop-filter:blur(4px);--dynamic-wallet-list-tile-padding:0.75rem;--dynamic-wallet-list-tile-gap:0.375rem;--dynamic-wallet-list-max-height:16.25rem;--dynamic-wallet-list-tile-background:#24272e;--dynamic-wallet-list-tile-border: ;--dynamic-wallet-list-tile-shadow:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-background-hover:#282b33;--dynamic-wallet-list-tile-border-hover: ;--dynamic-wallet-list-tile-border-radius:0.75rem;--dynamic-wallet-list-tile-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-animation-duration:150ms;--dynamic-tooltip-color:#fbfcff;--dynamic-tooltip-text-color:#0c0e13;--dynamic-initial-view-content-padding:0rem 1.5rem 1.5rem;--dynamic-button-primary-hover:#1b1d22;--dynamic-button-primary-background:#1b1d22;--dynamic-button-primary-font-size:0.875rem;--dynamic-button-primary-padding:0;--dynamic-button-primary-border:0.0625rem solid #282b33;--dynamic-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-button-secondary-hover:#1a1c21;--dynamic-button-secondary-background:transparent;--dynamic-button-secondary-font-size:0.75rem;--dynamic-button-secondary-padding:0;--dynamic-button-secondary-border:0.0625rem solid transparent;--dynamic-connect-button-background:#1b1d22;--dynamic-connect-button-background-hover:#1b1d22;--dynamic-connect-button-color:#fbfcff;--dynamic-connect-button-border:0.0625rem solid #282b33;--dynamic-connect-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-connect-button-color-hover:#fbfcff;--dynamic-connect-button-border-hover:0.0625rem solid #282b33;--dynamic-connect-button-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-search-padding:0 1.5rem 0.5rem;--dynamic-layout-content-padding:0 1.5rem 1.5rem;--dynamic-layout-content-error-padding:1.5rem 1.5rem 1.5rem;--dynamic-footer-border-top:0.0625rem solid #282b33;--dynamic-footer-padding:0.75rem 1.5rem 0.75rem;--dynamic-footer-background:transparent;--dynamic-header-border-bottom:1px solid transparent;--dynamic-header-padding:1.5rem 1.5rem 1.25rem;--dynamic-header-background:transparent}:root [data-dynamic-theme=auto] [data-dynamic-theme-brand=bold],:root [data-dynamic-theme=auto][data-dynamic-theme-brand=bold]{--dynamic-footer-text-color:#fbfcff;--dynamic-footer-icon-color:rgba(247,247,249,.75);--dynamic-footer-arrow-color:rgba(247,247,249,.75)}:root [data-dynamic-theme=auto] [data-dynamic-theme-brand=subtle],:root [data-dynamic-theme=auto][data-dynamic-theme-brand=subtle]{--dynamic-footer-arrow-color:#6f7177;--dynamic-footer-icon-color:#6f7177}}:root [data-dynamic-theme=dark]{--dynamic-font-family-primary:"DM Sans",sans-serif;--dynamic-search-border-radius:1rem;--dynamic-font-family-numbers:"Roboto Mono",monospace,sans-serif;--dynamic-base-1:#0c0e13;--dynamic-base-2:#1b1d22;--dynamic-base-3:#24272e;--dynamic-base-4:#282b33;--dynamic-brand-hover-color:linear-gradient(0deg,rgba(0,0,0,.08),rgba(0,0,0,.08)),#4779ff;--dynamic-brand-primary-color:#4779ff;--dynamic-brand-secondary-color:rgba(71,121,255,.15);--dynamic-success-1:#79ffcf;--dynamic-success-2:#192d2c;--dynamic-border-radius:1.5rem;--dynamic-hover:hsla(0,0%,100%,.1);--dynamic-error-1:#ff6a6a;--dynamic-error-2:hsla(0,100%,71%,.2);--dynamic-alert-1:#e2a140;--dynamic-alert-2:#2b2621;--dynamic-footer-background-color:#0c0e13;--dynamic-footer-text-color:#fbfcff;--dynamic-footer-icon-color:#4779ff;--dynamic-loading-animation-gradient:linear-gradient(90deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.01) 20%,hsla(0,0%,100%,.05) 60%,hsla(0,0%,100%,0));--dynamic-overlay:rgba(0,0,0,.25);--dynamic-shadow-down-1:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-shadow-down-2:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-shadow-down-3:0 1.5rem 2rem -1.5rem rgba(0,0,0,.24);--dynamic-shadow-up-1:0 -0.5rem 3rem -0.5rem rgba(109,121,165,.16);--dynamic-text-link:#69a5ff;--dynamic-text-primary:#fbfcff;--dynamic-text-secondary:#a8aab0;--dynamic-text-size-body-mini:0.6875rem;--dynamic-text-size-body-normal:0.9375rem;--dynamic-text-size-body-small:0.75rem;--dynamic-text-size-button-primary:0.875rem;--dynamic-text-size-button-secondary:0.75rem;--dynamic-text-size-numbers-big:0.875rem;--dynamic-text-size-numbers-medium:0.75rem;--dynamic-text-size-title:1.125rem;--dynamic-text-tertiary:#6f7177;--dynamic-badge-background:#24272e;--dynamic-badge-color:#a8aab0;--dynamic-badge-dot-background:#4779ff;--dynamic-search-bar-background:#1b1d22;--dynamic-search-bar-background-hover:#1b1d22;--dynamic-search-bar-background-focus:#1b1d22;--dynamic-search-bar-border:0.0625rem solid #24272e;--dynamic-search-bar-border-hover:0.0625rem solid #282b33;--dynamic-search-bar-border-focus:0.0625rem solid #282b33;--dynamic-modal-border: ;--dynamic-modal-width:22.5rem;--dynamic-modal-padding:1.5rem;--dynamic-modal-backdrop-background:rgba(0,0,0,.25);--dynamic-modal-backdrop-filter:blur(4px);--dynamic-wallet-list-tile-padding:0.75rem;--dynamic-wallet-list-tile-gap:0.375rem;--dynamic-wallet-list-max-height:16.25rem;--dynamic-wallet-list-tile-background:#24272e;--dynamic-wallet-list-tile-border: ;--dynamic-wallet-list-tile-shadow:0 0.0625rem 0.125rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-background-hover:#282b33;--dynamic-wallet-list-tile-border-hover: ;--dynamic-wallet-list-tile-border-radius:0.75rem;--dynamic-wallet-list-tile-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-wallet-list-tile-animation-duration:150ms;--dynamic-tooltip-color:#fbfcff;--dynamic-tooltip-text-color:#0c0e13;--dynamic-initial-view-content-padding:0rem 1.5rem 1.5rem;--dynamic-button-primary-hover:#1b1d22;--dynamic-button-primary-background:#1b1d22;--dynamic-button-primary-font-size:0.875rem;--dynamic-button-primary-padding:0;--dynamic-button-primary-border:0.0625rem solid #282b33;--dynamic-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-button-secondary-hover:#1a1c21;--dynamic-button-secondary-background:transparent;--dynamic-button-secondary-font-size:0.75rem;--dynamic-button-secondary-padding:0;--dynamic-button-secondary-border:0.0625rem solid transparent;--dynamic-connect-button-background:#1b1d22;--dynamic-connect-button-background-hover:#1b1d22;--dynamic-connect-button-color:#fbfcff;--dynamic-connect-button-border:0.0625rem solid #282b33;--dynamic-connect-button-shadow:0px 2px 3px 0px rgba(24,39,75,.08);--dynamic-connect-button-color-hover:#fbfcff;--dynamic-connect-button-border-hover:0.0625rem solid #282b33;--dynamic-connect-button-shadow-hover:0 0.75rem 1.25rem -0.375rem rgba(24,39,75,.02),0 1rem 1.625rem -0.25rem rgba(24,39,75,.04);--dynamic-search-padding:0 1.5rem 0.5rem;--dynamic-layout-content-padding:0 1.5rem 1.5rem;--dynamic-layout-content-error-padding:1.5rem 1.5rem 1.5rem;--dynamic-footer-border-top:0.0625rem solid #282b33;--dynamic-footer-padding:0.75rem 1.5rem 0.75rem;--dynamic-footer-background:transparent;--dynamic-header-border-bottom:1px solid transparent;--dynamic-header-padding:1.5rem 1.5rem 1.25rem;--dynamic-header-background:transparent}:root [data-dynamic-theme=dark] [data-dynamic-theme-brand=bold],:root [data-dynamic-theme=dark][data-dynamic-theme-brand=bold]{--dynamic-footer-text-color:#fbfcff;--dynamic-footer-icon-color:rgba(247,247,249,.75);--dynamic-footer-arrow-color:rgba(247,247,249,.75)}:root [data-dynamic-theme=dark] [data-dynamic-theme-brand=subtle],:root [data-dynamic-theme=dark][data-dynamic-theme-brand=subtle]{--dynamic-footer-arrow-color:#6f7177;--dynamic-footer-icon-color:#6f7177}}.dynamic-shadow-dom{position:relative}#dynamic-tooltips{left:0;position:absolute;top:0}@supports (overflow:clip){.dynamic-no-scroll{overflow:clip}}@supports not (overflow:clip){.dynamic-no-scroll{overflow:hidden}}}';styleInject(css_248z);const useVerifyOnAwaitingSignature=()=>{const{awaitingSignatureState:Xr,multiWalletWidgetState:eo,setMultiWalletWidgetState:to,legacyIsVerifying:ro,setLegacyIsVerifying:no,selectedWalletConnector:io}=useInternalDynamicContext(),oo=useConnectAndSign(),ao=reactExports.useRef(!1),so=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){if(logger$8.debug("runConnectAndSign",{selectedWalletConnector:io}),!!io){ao.current=!0,no(!0);try{yield oo({walletConnector:io})}catch(co){logger$8.error(co)}to("idle"),no(!1),ao.current=!1}}),[io==null?void 0:io.key,no,to,oo]);reactExports.useEffect(()=>{!ro&&!ao.current&&eo==="awaiting_signature"&&io&&Xr==="linking_new_wallet"&&!requiresTwoStepAuthentication(io)&&so()},[so,Xr,ro,eo,io==null?void 0:io.key,no,to]),useInternalDynamicEvents("triggerConnectAndSign",so)},viewsToDisableCloseOnOverlayClick=["email-wallet-otp-verification-view","social-redirect-view","passkey-intro"],Main=()=>{const{selectedWalletConnector:Xr,linkedWallets:eo,projectSettings:to,setShowAuthFlow:ro,showAuthFlow:no,walletConnectorOptions:io,clearStatesOnBackClick:oo,user:ao,disconnectWallet:so,authMode:co,connectedWallets:lo,handleLogOut:fo}=useInternalDynamicContext(),{view:ho,goToInitialView:go}=useViewContext(),{setDeniedAddress:yo,setDeniedOauthProvider:vo}=useAccessDeniedContext(),{setExistentAccountData:wo}=useAccountExistsContext(),{setSocialProvider:Eo}=useSocialRedirectContext();usePreventPageScroll(no);const ko=useUserWallets(),Ao=()=>__awaiter$j(void 0,void 0,void 0,function*(){var xo;if(!viewsToDisableCloseOnOverlayClick.includes(ho.type)){if(!((xo=ho.events)===null||xo===void 0)&&xo.onClose){ho.events.onClose();return}(ho.type==="network-not-supported"||ho.type==="network-not-supported-manual")&&ko.length===1&&(yield fo()),ho.type==="farcaster-connect-view"&&(Eo(void 0),dynamicEvents.emit("farcasterConnectCancelled")),ro(!1,{emitCancelAuth:!0}),yo(""),vo(void 0),wo(void 0),oo()}}),Po=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const xo=["network-not-supported","network-not-supported-manual"];if(!isConnectOnly(ao,co)||!xo.includes(ho.type)||!Xr)return;const uo=lo.find(po=>po.connector.key===Xr.key);uo&&(isSupportedNetwork({network:yield uo.connector.getNetwork(),walletConnector:uo.connector})||so(uo.id))}),[Xr,co,lo,so,ao,ho]),jo=reactExports.useCallback(()=>{go()},[go]);useVerifyOnAwaitingSignature();const{handleAlreadyConnectedWallet:Mo,handleCustodialWalletClick:No,handleInstalledExtensionClick:Do,handleMobileWalletClick:Fo,handleUninstalledClick:Xo}=useWalletItemActions(),Lo=xo=>__awaiter$j(void 0,void 0,void 0,function*(){ro(!0),isSelectedWalletAlreadyConnected(eo,xo,ao)?Mo(xo):xo.canConnectViaCustodialService?No(xo):isMobile$1()?Fo(xo):xo.isInstalledOnBrowser()?Do(xo):Xo(xo)});reactExports.useEffect(()=>{const xo=StorageService.getItem(NEWTOWEB3_WALLET_EXTENSION_FLAG_KEY);if(io!=null&&io.length&&xo){const uo=io.find(po=>po.key===xo);uo!=null&&uo.walletConnector&&Lo(uo.walletConnector),StorageService.removeItem(NEWTOWEB3_WALLET_EXTENSION_FLAG_KEY)}},[io]);const Bo=no&&!!to;return jsxRuntimeExports.jsx(FooterAnimationContextProvider,{children:jsxRuntimeExports.jsx(Portal,{zIndex:authModalZIndex,isShown:Bo,handleClose:Ao,withBackdrop:!0,transitionEvents:{onExiting:Po,onUnmount:jo},children:jsxRuntimeExports.jsx(PopperProvider,{children:jsxRuntimeExports.jsx(DynamicAuthModal,{transitionProps:{isShown:Bo},onClose:Ao,projectSettings:to,children:jsxRuntimeExports.jsx(RenderView,{})})})})})},DynamicAuthFlow=()=>jsxRuntimeExports.jsx(IsBrowser,{children:jsxRuntimeExports.jsx(Main,{})}),lastAuthenticatedAccount=Xr=>Xr.verifiedCredentials.find(eo=>eo.id===Xr.lastVerifiedCredentialId),useGlobalLoading=({authMode:Xr,connectedInfo:eo,connectedWallets:to,projectSettings:ro,primaryWalletId:no,primaryWallet:io,user:oo,isLoadingUserFromCookie:ao,walletBook:so,enableInstrumentation:co,appName:lo,environmentId:fo})=>{var ho,go;const yo=reactExports.useRef(!1),vo=reactExports.useRef(new Date().getTime()),{sessionValidation:wo}=useLoadingAndLifecycle(),Eo=()=>{if(!yo.current&&(yo.current=!0,logger$8.debug("[useGlobalLoading] SDK finished loading",{authMode:Xr,enableInstrumentation:co,primaryWallet:io,user:oo}),co)){const Fo=new Date().getTime()-vo.current;logger$8.instrument(`SDK loaded in (ms) ${Fo}`,{appName:lo,environmentId:fo,key:"sdkHasLoaded",primaryWalletId:no,time:Fo,userId:oo==null?void 0:oo.userId})}};if(yo.current)return!0;const ko=!Object.keys((ho=so==null?void 0:so.wallets)!==null&&ho!==void 0?ho:{}).length,Ao=!ro,Po=ao,Mo=!!((no||oo&&((go=lastAuthenticatedAccount(oo))===null||go===void 0?void 0:go.format)==="blockchain")&&!io),No=Xr==="connect-only"&&eo&&to.length===0,Do=!wo;return logger$8.logVerboseTroubleshootingMessage("[useGlobalLoading] SDK loading",{isConnectOnlyWalletsLoading:No,isPrimaryWalletLoading:Mo,isProjectSettingsLoading:Ao,isUserLoading:Po,isValidatingSession:Do,isWalletBookLoading:ko}),!ko&&!Ao&&!Po&&!Mo&&!No&&!Do&&Eo(),yo.current},usePrefetch=({as:Xr,href:eo,id:to,type:ro})=>{if(isSSR()||document.head.querySelector(`#${to}`))return;const io=document.createElement("link");io.setAttribute("id",to),io.setAttribute("rel","prefetch"),io.setAttribute("href",eo),io.setAttribute("as",Xr),io.setAttribute("type",ro),document.head.insertAdjacentElement("beforeend",io)},fetchNonce=Xr=>__awaiter$j(void 0,void 0,void 0,function*(){try{return(yield sdkApi$1().getNonce({environmentId:Xr})).nonce}catch{return}}),validateLocalStorageExpiry=Xr=>!(!Xr||new Date().getTime()>Xr.expiry),useFetchNonce=(Xr,eo=2)=>{const[to,ro,no]=useLocalStorage(NONCE_STORAGE_KEY,void 0,validateLocalStorageExpiry),io=(to==null?void 0:to.value)!==""&&(to==null?void 0:to.value)!==void 0;to&&to.environmentId&&to.environmentId!==Xr&&no(),usePromise(()=>__awaiter$j(void 0,void 0,void 0,function*(){return fetchNonce(Xr).then(ao=>{if(!ao)throw new DynamicError("Nonce is not defined");const so=new Date().getTime()+6e4*60*24;return{environmentId:Xr,expiry:so,value:ao}})}),{deps:[Xr,io],enabled:!io,initialData:void 0,onResolve:ro,retries:eo});const oo=reactExports.useCallback(()=>{const ao=to==null?void 0:to.value;return no(),ao},[no,to==null?void 0:to.value]);return{consumeNonce:()=>oo()}},useSetWalletConnectorVerifiedCredentials=(Xr,eo)=>{!Xr||!(eo!=null&&eo.length)||eo.forEach(to=>{to.walletConnector.setVerifiedCredentials(Xr.verifiedCredentials)})},handleStoreAndEnvironmentMismatch=Xr=>__awaiter$j(void 0,[Xr],void 0,function*({environmentId:eo,logout:to}){const ro=getEnvironmentId();return!ro||eo===ro?!0:(yield to("store and environment are out of sync",{currentEnvId:eo,storedEnvId:ro}),setEnvironmentId(eo),!1)}),handleUserDataOutOfSync=Xr=>__awaiter$j(void 0,[Xr],void 0,function*({environmentId:eo,logout:to}){const ro=isCookieEnabled$1(),no=getAuthToken(),io=getUser();if(no||!io)return!0;if(io&&!no&&ro){try{yield getAuthenticatedUser({environmentId:eo})}catch(oo){if(oo instanceof CookieInvalidError)return yield to("user auth cookie invalid",{authToken:no,user:io}),!1}return!0}return yield to("user data out of sync",{authToken:no,user:io}),!1}),useValidateSession=({environmentId:Xr,handleLogOut:eo})=>{const to=reactExports.useCallback((no,io)=>__awaiter$j(void 0,void 0,void 0,function*(){return logger$8.debug(`Logging out due to invalid session - Reason: ${no}`,Object.assign({},io)),eo()}),[eo]),ro=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const no={environmentId:Xr,logout:to};yield Promise.all([handleStoreAndEnvironmentMismatch(no),handleUserDataOutOfSync(no)]),setLoadingAndLifecycle({sessionValidation:!0})}),[Xr,to]);useEffectOnce(()=>{ro()}),useInternalDynamicEvents("triggerSessionValidation",ro)},serializeWalletConnectors=Xr=>{try{return Xr?Xr.map(eo=>eo.name):void 0}catch(eo){logger$8.error("error serializing walletConnectors",eo);return}};class ConnectorSetupError extends DynamicError{constructor(eo,to){super(`${eo} is enabled but ${to} is not in your walletConnectors list. See https://docs.dynamic.xyz/react-sdk/wallet-connectors for more information.`)}}const magicEmailOtpWalletConnectorKey="magicemailotp",magicSocialWalletConnectorKey="magicsocial",verifyMagicIsSetup=(Xr,eo)=>{var to;const ro=isProviderEnabled((to=Xr.providers)!==null&&to!==void 0?to:[],ProviderEnum.MagicLink),no=eo.some(({key:io})=>[magicEmailOtpWalletConnectorKey,magicSocialWalletConnectorKey].includes(io));if(ro&&!no)throw new ConnectorSetupError("Magic","MagicWalletConnectors")},zeroDevWalletConnectorKey="zerodev",verifyZeroDevIsSetup=(Xr,eo)=>{var to;const ro=isProviderEnabled((to=Xr.providers)!==null&&to!==void 0?to:[],ProviderEnum.Zerodev),no=eo.some(({key:io})=>io===zeroDevWalletConnectorKey);if(ro&&!no)throw new ConnectorSetupError("ZeroDev","ZeroDevSmartWalletConnectors")},verifyRequiredConnectorsAreSetup=(Xr,eo)=>{verifyMagicIsSetup(Xr,eo),verifyZeroDevIsSetup(Xr,eo)},useCreateWalletConnectorOptions=({projectSettings:Xr,appLogoUrl:eo,appName:to,coinbaseWalletPreference:ro,deepLinkPreference:no,flowNetwork:io,mobileExperience:oo,networkConfigurations:ao,walletBook:so,walletUiUtils:co,walletConnectorsProp:lo,walletConnectPreferredChains:fo,walletConnectorExtensions:ho})=>{const go=reactExports.useMemo(()=>{var wo;return(wo=serializeWalletConnectors(lo))===null||wo===void 0?void 0:wo.join(",")},[lo]),yo=reactExports.useMemo(()=>Object.keys(so??{}).length,[so]),vo=reactExports.useMemo(()=>!Xr||!Object.keys(so??{}).length||!ao?[]:getWallets$1({getSupportedWalletOpts:{appLogoUrl:eo,appName:to,coinbaseWalletPreference:ro,deepLinkPreference:no,flowNetwork:io,mobileExperience:oo,networkConfigurations:ao,settings:Xr,skipMemo:!0,walletBook:so,walletConnectPreferredChains:fo,walletConnectorsProp:lo??[],walletUiUtils:co},walletConnectorExtensions:ho}),[eo,to,Xr,go,fo,io,yo,ao]);return reactExports.useEffect(()=>{!Xr||vo.length===0||(verifyRequiredConnectorsAreSetup(Xr,vo.map(({walletConnector:wo})=>wo)),setWalletConnectorOptions(vo))},[vo,Xr]),{walletConnectorOptions:vo}},shouldManuallyReconnectOnRefresh=Xr=>Xr.connectedChain==="STARK"||Xr.connectedChain==="FLOW",convertLegacyPhantomLedgerConnector=Xr=>Object.assign(Object.assign({},Xr),{walletName:"phantom",walletProperties:{hardwareWallet:HardwareWalletEnum.Ledger}}),createLinkedWalletsFromWalletOptions=({user:Xr,walletConnectorOptions:eo,primaryWalletId:to})=>!eo||!Xr?[]:Xr.verifiedCredentials.map(convertLegacyPhantomLedger).map(ro=>{var no,io;const oo=findWalletOptionFor(ro,eo);return!oo||(ro.id===to&&shouldManuallyReconnectOnRefresh(oo.walletConnector)&&oo.walletConnector.connect(),((no=ro.walletProperties)===null||no===void 0?void 0:no.hardwareWallet)===HardwareWalletEnum.Ledger&&isHardwareWalletConnector(oo.walletConnector)&&(oo.walletConnector.isHardwareWalletEnabled=!0),isOwnerOfASmartWallet(ro,Xr.verifiedCredentials))?null:ro.address&&ro.chain?(ro.walletProvider===WalletProviderEnum.SmartContractWallet&&initializeSmartWallet({account:ro,primaryWalletId:to,verifiedCredentials:Xr.verifiedCredentials,walletConnectorOptions:eo}),oo.walletConnector.createWallet({additionalAddresses:ro.walletAdditionalAddresses,address:ro.address,chain:oo.walletConnector.connectedChain,connector:oo.walletConnector,id:ro.id,isAuthenticated:!0,key:(io=ro.walletName)!==null&&io!==void 0?io:oo.walletConnector.key})):null}).filter(ro=>ro!==null),convertLegacyPhantomLedger=Xr=>Xr.walletName==="phantomledger"?convertLegacyPhantomLedgerConnector(Xr):Xr,updateUserWalletsFromLinkedWallets=(Xr,eo)=>{const to=[...Xr],ro=new Set;for(const no of eo){ro.add(no.address);const io=to.findIndex(oo=>oo.address===no.address);if(io===-1){to.push(no);continue}to[io]=no}return to.filter(no=>ro.has(no.address))},useWalletConnectors=({authMode:Xr,connectedWallets:eo,walletConnectorOptions:to,setMultiWalletWidgetState:ro,primaryWalletId:no,setPrimaryWalletId:io,user:oo,canHaveMultipleWalletsConnected:ao})=>{const[so,co]=reactExports.useState(!1),lo=reactExports.useMemo(()=>oo?createLinkedWalletsFromWalletOptions({primaryWalletId:no,user:oo,walletConnectorOptions:to}):[],[oo,no,to]);logger$8.logVerboseTroubleshootingMessage("linkedWallets",lo);const fo=reactExports.useMemo(()=>Xr==="connect-and-sign"&&oo||Xr==="connect-only"&&lo.find(Eo=>isEmbeddedConnector(Eo.connector))?lo:eo??[],[Xr,eo,lo,oo]);logger$8.logVerboseTroubleshootingMessage("wallets",fo),reactExports.useEffect(()=>fo.forEach(Eo=>{Eo.connector.initEventListener()}),[fo]);const{setUserWallets:ho}=useInternalUserWallets();reactExports.useEffect(()=>{logger$8.logVerboseTroubleshootingMessage("[useWalletConnectors] will call setUserWallets",fo),ho(Eo=>updateUserWalletsFromLinkedWallets(Eo,fo))},[ho,fo]);const go=reactExports.useMemo(()=>{var Eo;return(Eo=fo.find(ko=>ko.id===no))!==null&&Eo!==void 0?Eo:null},[no,fo]),yo=reactExports.useMemo(()=>ao?fo.filter(Eo=>Eo.id!==no):[],[no,fo,ao]),vo=reactExports.useCallback(Eo=>__awaiter$j(void 0,void 0,void 0,function*(){const ko=fo.find(({id:Ao})=>Ao===Eo);if(!ko)throw new DynamicError(`Wallet with id: ${Eo} not found`);return ko}),[fo]),wo=reactExports.useCallback(Eo=>__awaiter$j(void 0,void 0,void 0,function*(){const ko=yield vo(Eo);if(!no){yield ko.connector.connect(),io(Eo);return}if(no!==Eo){if(isEmailWalletConnector(ko.connector)){const Ao=ko.connector,Po=localStorage.getItem("magic-link-email");Po&&Ao.setEmail(Po)}io(Eo),ro("idle")}}),[vo,no,ro,io]);return{primaryWallet:go,secondaryWallets:yo,setPrimaryWallet:wo,setShowQrcodeModal:co,showQrcodeModal:so,wallets:fo}},ConfirmationModal=({modalId:Xr,closeModal:eo,show:to,zIndex:ro,handleOnModalUnmount:no,children:io})=>jsxRuntimeExports.jsx(Portal,{elementId:Xr,handleClose:eo,isShown:to,zIndex:ro??authModalZIndex+1,withBackdrop:!0,transitionEvents:{onUnmount:no},children:jsxRuntimeExports.jsx(Modal$1,{children:jsxRuntimeExports.jsx(ModalCard,{children:io})})}),useConfirmationPortal=({onResolve:Xr,onReject:eo,defaultErrorMessage:to})=>{usePreventPageScroll(!0);const[ro,no]=reactExports.useState(!0),io=reactExports.useRef(null),oo=reactExports.useRef(null),ao=reactExports.useCallback(()=>{no(!1)},[no]),so=reactExports.useCallback(()=>{if(oo.current)return Xr(oo.current);const fo=io.current||new DynamicError(to||"Something went wrong");return eo(fo)},[Xr,eo,to]);return{closeModal:ao,handleOnModalUnmount:so,onError:(fo,ho=!1)=>{oo.current=null,io.current=fo,ho&&ao()},onSuccess:(fo,ho=!0)=>{io.current=null,oo.current=fo,ho&&ao()},show:ro}},CreatePasswordModal=({onResolve:Xr,onReject:eo,closeView:to})=>{const{onSuccess:ro,onError:no,show:io,handleOnModalUnmount:oo,closeModal:ao}=useConfirmationPortal({defaultErrorMessage:"User canceled",onReject:eo,onResolve:Xr});return jsxRuntimeExports.jsx(ConfirmationModal,{modalId:"create-password-modal",show:io,closeModal:ao,handleOnModalUnmount:oo,children:jsxRuntimeExports.jsx(CreatePasswordView,{closeView:to,onSuccess:ro,onError:no})})},EnterPasswordView=({mutation:Xr,onSuccess:eo,onError:to,closeView:ro=!0})=>{const{setShowAuthFlow:no}=useInternalDynamicContext(),[io,oo]=reactExports.useState(""),[ao,so]=reactExports.useState("password"),{t:co}=useTranslation(),{mutate:lo,isLoading:fo,hasError:ho}=useMutation(()=>Xr(io),{onFailure:to,onSuccess:()=>{ro&&no(!1),eo==null||eo(io)}}),go=()=>{if(to){to==null||to(co("dyn_enter_password.error.invalid_password"));return}no(!1)},yo=ho?co("dyn_enter_password.error.invalid_password"):void 0,vo=jsxRuntimeExports.jsx(IconButton,{onClick:go,type:"button",children:jsxRuntimeExports.jsx(SvgClose,{})}),wo=jsxRuntimeExports.jsx(ToggleVisibilityButton,{initialState:ao==="password",onClick:ko=>so(ko?"password":"text"),className:"enter-password-view__password-input__suffix-icon"}),Eo=ko=>{const Ao=ko.target.value;oo(Ao)};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalHeader,{trailing:vo,children:jsxRuntimeExports.jsx(Typography,{as:"h1",variant:"title",color:"primary",className:"header__typography",copykey:"dyn_enter_password.title",children:co("dyn_enter_password.title")})}),jsxRuntimeExports.jsx("div",{className:"enter-password-view",children:jsxRuntimeExports.jsxs("form",{className:"enter-password-view__body",onSubmit:ko=>{ko.preventDefault(),lo()},children:[jsxRuntimeExports.jsx("div",{className:"enter-password-view__body__icon",children:jsxRuntimeExports.jsx(SvgPasswordHero,{})}),jsxRuntimeExports.jsx("div",{className:"enter-password-view__body__description",children:jsxRuntimeExports.jsx(Typography,{variant:"body_normal",weight:"regular",color:"secondary",copykey:"dyn_enter_password.description",children:co("dyn_enter_password.description")})}),!!yo&&jsxRuntimeExports.jsx(ErrorContainer,{copykey:"dyn_enter_password.error",children:yo}),jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx(Input,{id:"password",placeholder:co("dyn_enter_password.input.placeholder"),type:ao,suffix:wo,label:co("dyn_enter_password.input.label"),value:io,onChange:Eo,copykey:"dyn_enter_password.input"})}),jsxRuntimeExports.jsx(TypographyButton,{buttonPadding:"large",buttonVariant:"brand-primary",typographyProps:{color:"inherit"},disabled:!io&&!yo,loading:fo,copykey:"dyn_enter_password.continue_button_label",type:"submit",children:co("dyn_enter_password.continue_button_label")})]})})]})},EnterPasswordModal=({handler:Xr,onResolve:eo,onReject:to,closeView:ro})=>{const{onSuccess:no,onError:io,show:oo,handleOnModalUnmount:ao,closeModal:so}=useConfirmationPortal({defaultErrorMessage:"User canceled",onReject:to,onResolve:eo});return jsxRuntimeExports.jsx(ConfirmationModal,{modalId:"enter-password-modal",show:oo,closeModal:so,handleOnModalUnmount:ao,children:jsxRuntimeExports.jsx(EnterPasswordView,{mutation:Xr,closeView:ro,onSuccess:no,onError:io})})},AppOriginTile=({appLogoUrl:Xr,appName:eo,appOrigin:to})=>{const ro=reactExports.useRef(null),[no,io]=reactExports.useState(!1);return reactExports.useLayoutEffect(()=>{if(ro.current){const{width:oo,height:ao}=ro.current.getBoundingClientRect();oo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose$1(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgSignCircle=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties$1(eo,_excluded$1);return reactExports.createElement("svg",_extends$3({width:64,height:64,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_circle||(_circle=reactExports.createElement("circle",{cx:32,cy:32,r:32,fill:"currentColor"})),_path$1||(_path$1=reactExports.createElement("path",{d:"M34.048 17.611a5.5 5.5 0 1 1 7.779 7.779l-.611.61.193.193a4.5 4.5 0 0 1 0 6.364l-3.238 3.239a1.125 1.125 0 0 1-1.592-1.591l3.239-3.239a2.25 2.25 0 0 0 0-3.182l-.193-.193-12.704 12.705a1.123 1.123 0 0 1-.523.296l-9 2.25a1.125 1.125 0 0 1-1.34-1.447l2.812-8.438c.055-.166.148-.316.272-.44l14.906-14.906Zm6.188 1.591a3.25 3.25 0 0 0-4.597 0L20.921 33.92l-2.08 6.242 6.709-1.678 14.686-14.686a3.25 3.25 0 0 0 0-4.596ZM24.925 47.375c-2.779 0-4.967-1.275-6.424-2.49l2.89-.723c1.003.562 2.19.963 3.534.963.912 0 1.853-.369 2.856-1.028 1.005-.66 1.976-1.546 2.956-2.465l.255-.24c.865-.812 1.764-1.658 2.624-2.242.918-.624 2.135-1.191 3.413-.7.844.325 1.393.925 1.78 1.658.362.687.612 1.548.855 2.485.111.427.3.841.515 1.12.105.137.196.214.26.253.055.034.08.034.086.034.274 0 .745-.185 1.417-.643.417-.284.774-.568 1.13-.852.221-.177.443-.354.679-.53.628-.47 1.171-.785 1.57-.986a6.86 6.86 0 0 1 .625-.28l.045-.016.016-.006.006-.002h.003s.002-.002.359 1.065l-.357-1.067a1.125 1.125 0 0 1 .721 2.132l-.008.003a4.59 4.59 0 0 0-.394.178 8.472 8.472 0 0 0-1.238.78c-.132.098-.304.235-.5.391-.409.324-.921.73-1.39 1.05-.7.476-1.67 1.033-2.684 1.033-.98 0-1.69-.595-2.127-1.162-.447-.578-.746-1.29-.912-1.93-.247-.95-.442-1.573-.667-2-.201-.38-.383-.525-.598-.608-.184-.07-.552-.075-1.34.46-.704.48-1.472 1.2-2.38 2.053l-.225.211c-.97.91-2.071 1.922-3.26 2.703-1.19.783-2.566 1.398-4.091 1.398Z",fill:"#fff"})))};const isSignTypedData=Xr=>{if(typeof Xr!="object"||Xr===null)return!1;const{types:eo,message:to,primaryType:ro}=Xr;return typeof eo=="object"&&eo!==null&&typeof to=="object"&&to!==null&&typeof ro=="string"},isRawMessage=Xr=>typeof Xr!="object"||Xr===null?!1:typeof Xr.raw=="string",SignTypedDataPreview=({currentType:Xr,types:eo,showTypeName:to=!1,data:ro})=>{const no=eo[Xr].map(io=>{var oo;const ao=io.type.replace("[]",""),so=io.type.endsWith("[]"),co=ao in eo;if(so&&co)return jsxRuntimeExports.jsx(TypeSection,{title:capitalize$1(io.name),children:(oo=ro==null?void 0:ro[io.name])===null||oo===void 0?void 0:oo.map((ho,go)=>jsxRuntimeExports.jsx(TypeSection,{title:go.toString(),children:jsxRuntimeExports.jsx(SignTypedDataPreview,{currentType:ao,types:eo,data:ho})},go))},io.name);if(co)return jsxRuntimeExports.jsx(TypeSection,{title:capitalize$1(io.name),children:jsxRuntimeExports.jsx(SignTypedDataPreview,{currentType:ao,types:eo,data:ro==null?void 0:ro[io.name]})},io.name);const lo=ro==null?void 0:ro[io.name],fo=io.type;return jsxRuntimeExports.jsx(FieldRow,{name:capitalize$1(io.name),data:lo,displayValue:fo==="address"?shortenWalletAddress(lo,4,4):lo},io.name)});return to?jsxRuntimeExports.jsx(TypeSection,{title:Xr,children:no}):jsxRuntimeExports.jsx("div",{className:"sign-typed-data-preview--fields-list",children:no})},TypeTitle=({children:Xr})=>jsxRuntimeExports.jsx(Typography,{color:"secondary",weight:"medium",children:Xr}),AttributeName=TypeTitle,AttributeValue=({children:Xr,title:eo})=>jsxRuntimeExports.jsx(Typography,{as:"span",weight:"regular",color:"primary",title:eo,children:Xr}),PaddedContent=({children:Xr})=>jsxRuntimeExports.jsx("div",{className:"sign-typed-data-preview--type-container",children:Xr}),TypeSection=({title:Xr,children:eo})=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(TypeTitle,{children:Xr}),jsxRuntimeExports.jsx(PaddedContent,{children:eo})]}),FieldRow=({name:Xr,displayValue:eo,data:to})=>jsxRuntimeExports.jsxs("div",{className:"sign-typed-data-preview--attribute-row",children:[jsxRuntimeExports.jsxs(AttributeName,{children:[capitalize$1(Xr),": "]}),jsxRuntimeExports.jsx(AttributeValue,{title:to,children:eo})]}),containsSpecialCharacters=Xr=>/[^ -~\s]/.test(Xr),SignMessagePreview=({message:Xr})=>{const eo=reactExports.useMemo(()=>{try{return JSON.parse(Xr)}catch{return}},[Xr]),to=reactExports.useMemo(()=>{const ro=isRawMessage(eo)?eo.raw:Xr,no=isHex$3(ro)?hexToString(ro):ro;return containsSpecialCharacters(no)?ro:no},[eo,Xr]);return isSignTypedData(eo)?jsxRuntimeExports.jsx(SignTypedDataPreview,{currentType:eo.primaryType,types:eo.types,showTypeName:!0,data:eo.message}):jsxRuntimeExports.jsx(Typography,{color:"primary",variant:"body_normal",children:jsxRuntimeExports.jsx("span",{style:{whiteSpace:"pre-line"},children:to})})},SignMessageConfirmationModal=({appLogoUrl:Xr,appName:eo,message:to,handler:ro,onReject:no,onSignMessage:io,hideModal:oo})=>{usePreventPageScroll(!0);const ao=reactExports.useRef(!1),[so,co]=reactExports.useState(!0),{initPasskeyRecoveryProcess:lo,shouldInitRecovery:fo}=usePasskeyRecovery(),{isTurnkeyWallet:ho}=useIsTurnkeyWallet(),{setShowAuthFlow:go,primaryWallet:yo}=useInternalDynamicContext(),{setView:vo}=useViewContext(),{userNeedsCrossDomainPasskey:wo}=usePasskeyContext(),{t:Eo}=useTranslation(),{getEOAWallet:ko}=useSmartWallets(),Ao=yo&&ko(yo),Po=reactExports.useCallback(()=>{ao.current=!1,co(!1)},[co]),{isLoading:jo,mutate:Mo,data:No,error:Do}=useMutation(()=>ro(to),{onSuccess:()=>{ao.current=!0,co(!1)}}),Fo=reactExports.useMemo(()=>{if(Do){if(Do instanceof DynamicError)return Do.message;try{return getProperErrorMessage(Do)}catch(xo){xo instanceof AccessBlockedError&&vo("access-blocked");return}}},[Do,vo]),Xo=reactExports.useCallback(()=>{if(No)return io(No);no(Do||new UserRejectedRequestError)},[No,io,no,Do]),Lo=xo=>__awaiter$j(void 0,void 0,void 0,function*(){const uo=yo&&isSessionKeyCompatibleWallet(yo)||Ao&&isSessionKeyCompatibleWallet(Ao);if((yield fo())&&!uo&&(yield lo("email","signMessage")),xo===!0){io("callHandlerOutsideModal");return}if(uo){Mo();return}if(ho&&wo){vo("passkey-new-domain-detected"),go(!0,{ignoreIfIsEmbeddedWidget:!1,performMultiWalletChecks:!1}),dynamicEvents.once("passkeyRecoveryCompleted",()=>{Mo()});return}Mo()});useEffectOnce(()=>{oo&&Lo(!0)});const Bo=jsxRuntimeExports.jsx(IconButton,{type:"button",onClick:Po,"data-testid":"close",disabled:jo,children:jsxRuntimeExports.jsx(SvgClose,{})});return oo?null:jsxRuntimeExports.jsx(Portal,{handleClose:Po,isShown:so,zIndex:authModalZIndex,withBackdrop:!0,elementId:"dynamic-sign-message",transitionEvents:{onUnmount:Xo},children:jsxRuntimeExports.jsx(Modal$1,{children:jsxRuntimeExports.jsxs(ModalCard,{children:[jsxRuntimeExports.jsx(ModalHeader,{trailing:Bo,alignContent:"bottom",children:jsxRuntimeExports.jsx(IconWithSpinner,{Icon:xo=>jsxRuntimeExports.jsx(Icon,{color:"brand-primary",children:jsxRuntimeExports.jsx(SvgSignCircle,Object.assign({},xo))}),iconSize:64,isSpinning:!0})}),jsxRuntimeExports.jsx(PasskeyCreatedSuccessBanner,{}),jsxRuntimeExports.jsxs("div",{className:"sign-message-confirmation__body",children:[jsxRuntimeExports.jsx(Typography,{variant:"title",color:"primary",className:"sign-message-confirmation__title",copykey:"dyn_sign_message.title",children:Eo("dyn_sign_message.title")}),jsxRuntimeExports.jsx(AnimatePresence,{animationComponent:jsxRuntimeExports.jsx(VerticalDrawerTransition,{}),children:Do&&jsxRuntimeExports.jsx("div",{className:"sign-message-confirmation__error",children:jsxRuntimeExports.jsx(ErrorContainer,{children:Fo})})}),jsxRuntimeExports.jsxs("div",{className:"sign-message-confirmation__message-container",children:[jsxRuntimeExports.jsx(AppOriginTile,{appLogoUrl:Xr,appName:eo,appOrigin:PlatformService.getDisplayOrigin()}),jsxRuntimeExports.jsx("div",{className:"sign-message-confirmation__message",children:jsxRuntimeExports.jsx(SignMessagePreview,{message:to.toString().replace(/^"(.*)"$/,"$1").replace(/\\n/g,` `)})})]}),jsxRuntimeExports.jsxs("div",{className:"sign-message-confirmation__actions",children:[jsxRuntimeExports.jsx(TypographyButton,{buttonVariant:"secondary",onClick:Po,expanded:!0,buttonPadding:"large",disabled:jo,copykey:"dyn_sign_message.cancel_button",children:Eo("dyn_sign_message.cancel_button")}),jsxRuntimeExports.jsx(TypographyButton,{buttonVariant:"primary",buttonPadding:"large",onClick:Lo,expanded:!0,loading:jo,copykey:"dyn_sign_message.sign_button",dataTestId:"sign-button",children:Eo("dyn_sign_message.sign_button")})]}),jsxRuntimeExports.jsx(NeedHelpSection,{}),jsxRuntimeExports.jsx(PoweredByDynamic,{})]})]})})})},WidgetPortal=({children:Xr,onClose:eo,disablePadding:to,portalClassName:ro,portalContainerClassName:no})=>jsxRuntimeExports.jsx("div",{className:classNames(ro,"widget-portal"),onClick:eo,"data-testid":"backdrop",children:jsxRuntimeExports.jsxs("div",{className:classNames(no,"widget-portal__container",{"widget-portal__container--no-padding":to}),onClick:io=>io.stopPropagation(),children:[eo&&jsxRuntimeExports.jsx("div",{className:"widget-portal__container__header",children:jsxRuntimeExports.jsx(IconButton,{className:"widget-portal__container__close-button",onClick:io=>eo(io),type:"button","data-testid":"close-button",children:jsxRuntimeExports.jsx(SvgClose,{})})}),Xr]})}),DefaultPromptLayout=({children:Xr,className:eo="",dataTestId:to="",icon:ro,showSpinnerInIcon:no=!0,title:io})=>jsxRuntimeExports.jsxs("div",{className:classNames("default-prompt-modal",eo),"data-testid":to,children:[ro&&jsxRuntimeExports.jsx(IconWithSpinner,{Icon:ro,iconSize:96,isSpinning:no,className:"default-prompt-modal__icon-with-spinner"}),jsxRuntimeExports.jsxs("div",{className:"default-prompt-modal__content",children:[io&&jsxRuntimeExports.jsx(Typography,{variant:"title",color:"primary","data-testid":"title",children:io}),Xr]})]}),DefaultPromptModal=Xr=>jsxRuntimeExports.jsx(WidgetPortal,{onClose:Xr.onClose,portalClassName:"prompt-modal-portal",portalContainerClassName:"prompt-modal-portal__container",children:jsxRuntimeExports.jsx(DefaultPromptLayout,Object.assign({},Xr))});var _path,_excluded=["title","titleId"];function _extends$2(){return _extends$2=Object.assign?Object.assign.bind():function(Xr){for(var eo=1;eo=0)&&Object.prototype.propertyIsEnumerable.call(Xr,ro)&&(to[ro]=Xr[ro])}return to}function _objectWithoutPropertiesLoose(Xr,eo){if(Xr==null)return{};var to={},ro=Object.keys(Xr),no,io;for(io=0;io=0)&&(to[no]=Xr[no]);return to}var SvgArrowCircleRight=function(eo){var to=eo.title,ro=eo.titleId,no=_objectWithoutProperties(eo,_excluded);return reactExports.createElement("svg",_extends$2({width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":ro},no),to?reactExports.createElement("title",{id:ro},to):null,_path||(_path=reactExports.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16ZM2 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10S2 17.523 2 12Zm10.293-3.707a1 1 0 0 1 1.414 0l3 3a1 1 0 0 1 0 1.414l-3 3a1 1 0 0 1-1.414-1.414L13.586 13H8a1 1 0 1 1 0-2h5.586l-1.293-1.293a1 1 0 0 1 0-1.414Z",fill:"#ABACB2"})))};const SwitchWalletView=({onCancel:Xr,connector:eo,expectedAddress:to,activeAddress:ro})=>{const{t:no}=useTranslation();return jsxRuntimeExports.jsx(DefaultPromptModal,{dataTestId:"switch-wallet",className:"switch-wallet",icon:jsxRuntimeExports.jsx(WalletIcon,{walletKey:eo.key}),title:no("dyn_sync_wallet.switch_wallet.title"),onClose:Xr,children:jsxRuntimeExports.jsxs("div",{className:"switch-wallet__body",children:[ro&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Typography,{variant:"body_mini",color:"secondary",weight:"regular",copykey:"dyn_sync_wallet.switch_wallet.active_address.heading",children:no("dyn_sync_wallet.switch_wallet.active_address.heading")}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"primary",weight:"regular",children:shortenWalletAddress(ro,3,3)}),jsxRuntimeExports.jsx(Divider,{className:"switch-wallet__body__divider",children:jsxRuntimeExports.jsx(SvgArrowCircleRight,{})})]}),jsxRuntimeExports.jsx(Typography,{variant:"body_mini",color:"secondary",weight:"regular",copykey:"dyn_sync_wallet.switch_wallet.expected_address.heading",children:no("dyn_sync_wallet.switch_wallet.expected_address.heading")}),jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"primary",weight:"regular",copykey:"dyn_sync_wallet.switch_wallet.expected_address.prompt",className:"switch-wallet__body__expected-address__prompt",children:no("dyn_sync_wallet.switch_wallet.expected_address.prompt")}),jsxRuntimeExports.jsx(Typography,{color:"green-1",weight:"bold",className:"switch-wallet__body__expected-address__address",children:shortenWalletAddress(to,3,3)})]})})},ReconnectWithQrCodeView=({onCancel:Xr,onSuccess:eo,connector:to,expectedAddress:ro})=>{var no;const{t:io}=useTranslation(),{walletBook:oo}=useWalletBookContext(),{theme:{theme:ao}}=useThemeContext(),{name:so}=ao,[co,lo]=reactExports.useState(),[fo,ho]=reactExports.useState();return usePromise(()=>__awaiter$j(void 0,void 0,void 0,function*(){const go=yield to.getAddress({onDesktopUri:yo=>__awaiter$j(void 0,void 0,void 0,function*(){ho(yo)}),onDisplayUri:yo=>__awaiter$j(void 0,void 0,void 0,function*(){lo(yo)})});if(go&&isSameAddress$1(go,ro,to.connectedChain)){eo();return}to.endSession(),Xr()}),{deps:[to],retries:3}),jsxRuntimeExports.jsx(DefaultPromptModal,{dataTestId:"reconnect-qr-code",title:io("dyn_sync_wallet.reconnect_with_qr_code.title"),onClose:Xr,children:co&&jsxRuntimeExports.jsx(QrCodeWrapper,{uri:co,desktopUri:fo,accentColor:so==="dark"?ao.colors.textPrimary:(no=getWalletPrimaryColor(oo,to.key))!==null&&no!==void 0?no:"",icon:jsxRuntimeExports.jsx(WalletIcon,{walletKey:to==null?void 0:to.key}),showCopyToClipboardButton:!0,walletConnector:to})})},reconnectSocialWallet=(Xr,eo,to,ro)=>__awaiter$j(void 0,void 0,void 0,function*(){if(!isSocialWalletConnector(eo))return;const no=Xr==null?void 0:Xr.verifiedCredentials.find(io=>io.format===JwtVerifiedCredentialFormatEnum.Oauth&&io.address&&isSameAddress$1(io.address,to,ro));!no||!no.oauthProvider||(yield eo.connect(no.oauthProvider))}),AutoReconnectingView=({onCancel:Xr,onSuccess:eo,connector:to,expectedAddress:ro})=>{const{t:no}=useTranslation(),{user:io}=useInternalDynamicContext();return usePromise(()=>__awaiter$j(void 0,void 0,void 0,function*(){isSocialWalletConnector(to)&&(yield reconnectSocialWallet(io,to,ro,to.connectedChain),eo())}),{deps:[to]}),jsxRuntimeExports.jsx(DefaultPromptModal,{dataTestId:"auto-reconnecting",icon:jsxRuntimeExports.jsx(WalletIcon,{walletKey:to==null?void 0:to.key}),title:no("dyn_sync_wallet.reconnecting.title"),onClose:Xr,children:jsxRuntimeExports.jsx(Typography,{variant:"body_normal",color:"secondary",weight:"regular",children:no("dyn_sync_wallet.reconnecting.description",{walletAddress:shortenWalletAddress(ro,3,3)})})})},SyncWalletView=({onSuccess:Xr,onError:eo,expectedAddress:to,activeAddress:ro,connector:no})=>{const io=no.canConnectViaQrCode&&!no.isInstalledOnBrowser()&&!no.canConnectViaCustodialService;logger$8.logVerboseTroubleshootingMessage("[SyncWallet]",{canConnectViaCustodialService:no.canConnectViaCustodialService,canConnectViaQrCode:no.canConnectViaQrCode,isEmbeddedWallet:no.isEmbeddedWallet,isInstalledOnBrowser:no.isInstalledOnBrowser()}),useWalletConnectorEvent(no,"accountChange",({accounts:so})=>{logger$8.logVerboseTroubleshootingMessage("[SyncWallet] accountChange",{accounts:so,expectedAddress:to});const[co]=so;isSameAddress$1(co,to,no.connectedChain)&&Xr(!0)}),useInternalDynamicEvents("logout",()=>eo(new Error("user logged out"),!0));const oo=()=>__awaiter$j(void 0,void 0,void 0,function*(){const so=yield no.getAddress();so&&isSameAddress$1(so,to,no.connectedChain)&&Xr(!0)}),ao=()=>{logger$8.logVerboseTroubleshootingMessage("[SyncWallet] handleCancel called"),eo(new DynamicError("User cancelled","0"),!0)};return no.isEmbeddedWallet?jsxRuntimeExports.jsx("div",{className:"sync-wallet-view","data-testid":"sync-wallet",children:jsxRuntimeExports.jsx(AutoReconnectingView,{connector:no,expectedAddress:to,onCancel:ao,onSuccess:()=>Xr(!0)})}):io?jsxRuntimeExports.jsx("div",{className:"sync-wallet-view","data-testid":"sync-wallet",children:jsxRuntimeExports.jsx(ReconnectWithQrCodeView,{connector:no,expectedAddress:to,onCancel:ao,onSuccess:()=>Xr(!0)})}):jsxRuntimeExports.jsx("div",{className:"sync-wallet-view","data-testid":"sync-wallet",children:jsxRuntimeExports.jsx(SwitchWalletView,{connector:no,expectedAddress:to,activeAddress:ro,onCancel:ao,onTryToReconnect:oo})})},SyncWalletPromptModal=({expectedAddress:Xr,connector:eo,onResolve:to,onReject:ro,activeAddress:no})=>{const{onSuccess:io,onError:oo,show:ao,handleOnModalUnmount:so}=useConfirmationPortal({defaultErrorMessage:"User canceled",onReject:ro,onResolve:to});return jsxRuntimeExports.jsx(ConfirmationModal,{modalId:"sync-wallet-modal",show:ao,closeModal:()=>{},handleOnModalUnmount:so,children:jsxRuntimeExports.jsx(SyncWalletView,{onSuccess:io,onError:oo,expectedAddress:Xr,connector:eo,activeAddress:no})})},TransactionConfirmationModal=({title:Xr,onReject:eo,onTransactionResponseSuccess:to,transaction:ro,copykey:no,walletConnector:io,hideModal:oo,isNativeToken:ao,currentToken:so})=>{usePreventPageScroll(!0);const[co,lo]=reactExports.useState(!0),fo=reactExports.useRef(null),ho=reactExports.useRef(null),go=reactExports.useCallback(()=>{lo(!1)},[lo]),yo=reactExports.useCallback(()=>ho.current?to(ho.current):eo(fo.current||new UserRejectedTransactionError),[to,eo]);return jsxRuntimeExports.jsx(Portal,{handleClose:go,isShown:co,zIndex:authModalZIndex,withBackdrop:!0,elementId:"dynamic-send-transaction",transitionEvents:{onUnmount:yo},children:jsxRuntimeExports.jsx(Modal$1,{children:jsxRuntimeExports.jsx(ModalCard,{children:jsxRuntimeExports.jsx(TransactionConfirmationView,{transaction:ro,title:Xr,copykey:no,hideModal:oo,mutation:()=>ro.submit(),onClickClose:go,onError:vo=>fo.current=vo,displayPoweredByDynamicFooter:!0,walletConnector:io,onSuccess:vo=>{fo.current=null,ho.current=vo,go()},isNativeToken:ao,currentToken:so,isModal:!0})})})})},useWalletUiUtils=({appLogoUrl:Xr,appName:eo,hideEmbeddedWalletTransactionUIs:to=!1})=>{const ro=reactExports.useRef("enabled"),{t:no}=useTranslation(),{modal:io,open:oo}=useConfirmationModal({elementId:"dynamic-send-transaction"}),{modal:ao,open:so}=useConfirmationModal({elementId:"dynamic-sign-message"}),{modal:co,open:lo}=useConfirmationModal({elementId:"dynamic-enter-password"}),{modal:fo,open:ho}=useConfirmationModal({elementId:"dynamic-create-password"}),{modal:go,open:yo}=useConfirmationModal({elementId:"dynamic-sync-wallet"}),vo=reactExports.useCallback(()=>ro.current==="disabled"?(ro.current="enabled",!1):!0,[ro]),wo=reactExports.useCallback(No=>__awaiter$j(void 0,[No],void 0,function*({walletConnector:Do,message:Fo,handler:Xo}){return vo()?so((Lo,Bo)=>jsxRuntimeExports.jsx(SignMessageConfirmationModal,{appLogoUrl:Xr,appName:eo,message:Fo,handler:Xo,onSignMessage:Lo,onReject:Bo,hideModal:to&&!(Do!=null&&Do.isGlobalTransaction)})).then(Lo=>__awaiter$j(void 0,void 0,void 0,function*(){return Lo==="callHandlerOutsideModal"?Xo():Lo})):Xo()}),[Xr,eo,to,so,vo]),Eo=reactExports.useCallback((No,Do)=>__awaiter$j(void 0,void 0,void 0,function*(){return vo()?oo((Fo,Xo)=>jsxRuntimeExports.jsx(TransactionConfirmationModal,{copykey:"dyn_send_transaction.confirmation.title",title:no("dyn_send_transaction.confirmation.title"),transaction:Do,onTransactionResponseSuccess:Fo,onReject:Xo,walletConnector:No,hideModal:to&&!(No!=null&&No.isGlobalTransaction)})).then(Fo=>__awaiter$j(void 0,void 0,void 0,function*(){return Fo==="callHandlerOutsideModal"?Do.submit():Fo})):Do.submit()}),[to,oo,vo,no]),ko=reactExports.useCallback(No=>__awaiter$j(void 0,[No],void 0,function*({handler:Do,closeView:Fo=!0}){return lo((Xo,Lo)=>jsxRuntimeExports.jsx(EnterPasswordModal,{handler:Do,onResolve:Xo,onReject:Lo,closeView:Fo}))}),[lo]),Ao=reactExports.useCallback(No=>__awaiter$j(void 0,[No],void 0,function*({closeView:Do=!0}){return ho((Fo,Xo)=>jsxRuntimeExports.jsx(CreatePasswordModal,{onResolve:Fo,onReject:Xo,closeView:Do}))}),[ho]),Po=reactExports.useCallback(No=>__awaiter$j(void 0,[No],void 0,function*({walletConnector:Do,activeAddress:Fo,expectedAddress:Xo}){yield yo((Lo,Bo)=>jsxRuntimeExports.jsx(SyncWalletPromptModal,{onResolve:Lo,onReject:Bo,connector:Do,expectedAddress:Xo,activeAddress:Fo}))}),[yo]),jo=reactExports.useCallback(()=>{ro.current="disabled"},[]),Mo=reactExports.useMemo(()=>({createPassword:Ao,disabledConfirmationOnce:jo,enterPassword:ko,sendTransaction:Eo,signMessage:wo,syncWallet:Po}),[wo,jo,Eo,ko,Ao,Po]);return reactExports.useMemo(()=>[ao||io||co||fo||go,Mo],[ao,io,co,fo,go,Mo])},useSetWalletConnectorFetchers=(Xr,eo)=>{const{registerEmbeddedWalletSessionKey:to,removeSessionKey:ro}=useEmbeddedWalletSessionKeys(eo);if(!(Xr!=null&&Xr.length))return;const{fetchAuthToken:no,fetchBackupCode:io,fetchPasscode:oo}=getCoinbaseMPCConnectorFetchers({environmentId:eo});Xr.forEach(ao=>{var so,co;isCoinbaseMpcWalletConnector(ao.walletConnector)&&(ao.walletConnector.setAuthTokenFetcher(no),ao.walletConnector.setBackupCodeFetcher(io),ao.walletConnector.setPasscodeFetcher(oo)),isSessionKeyCompatibleWalletConnector(ao.walletConnector)&&((so=ao.walletConnector)===null||so===void 0||so.setSessionKeyFetcher(to),(co=ao.walletConnector)===null||co===void 0||co.setSessionKeyRemoveFunction(()=>ro()))})},useSendDynamicProps=({settings:Xr,environmentId:eo})=>{useEffectOnce(()=>{const to={settings:Object.assign(Object.assign({},Xr),{customPrivacyPolicy:!!Xr.customPrivacyPolicy,customTermsOfServices:!!Xr.customTermsOfServices,policiesConsentInnerComponent:!!Xr.policiesConsentInnerComponent})},ro=serializeEventsCallbacks(Xr.events),no=serializeWalletConnectors(Xr.walletConnectors),io=Object.assign(Object.assign({},to),{settings:Object.assign(Object.assign({},to.settings),{events:ro,walletConnectors:no})});sendDynamicProps(eo,{dynamicContextProps:io,frameworkSettings:getFrameworkSettings()})})},serializeEventsCallbacks=Xr=>{try{if(!Xr)return;const eo=Object.values(Xr);return Object.keys(Xr).filter((ro,no)=>eo[no]===void 0?!1:ro)}catch(eo){logger$8.error("error serializing events",eo);return}},getFrameworkSettings=()=>{var Xr;return{nextJs:{version:(Xr=window.next)===null||Xr===void 0?void 0:Xr.version},react:{version:reactExports.version}}},useResetCookieLocalStorage=({environmentId:Xr,projectSettings:eo,setPrimaryWalletId:to})=>{const ro=reactExports.useRef(!0),no=reactExports.useRef(!1),io=getUser(),oo=reactExports.useRef(!1);return useInternalDynamicEvents("logout",()=>oo.current=!0),reactExports.useEffect(()=>{const ao=()=>__awaiter$j(void 0,void 0,void 0,function*(){if(!io&&isCookieEnabled$1()&&!oo.current){no.current=!0;try{const so=yield refreshUserJwt({environmentId:Xr}),co=so==null?void 0:so.verifiedCredentials.find(lo=>lo.format===JwtVerifiedCredentialFormatEnum.Blockchain&&lo.id===so.lastVerifiedCredentialId);co&&to(co.id)}catch{logger$8.debug("Ignore failed refreshUserJwt in useResetCookieLocalStorage")}}eo&&(ro.current=!1)});no.current||ao()},[io,eo,Xr,to]),{isLoading:ro.current}},useSyncEmbeddedWalletFlow=()=>{const{projectSettings:Xr,user:eo,primaryWalletId:to,walletConnectorOptions:ro,setShowAuthFlow:no}=useInternalDynamicContext(),{isLoadingEmbeddedWallet:io}=useWalletContext(),{loading:oo}=useLoadingContext(),{createEmbeddedWallet:ao,shouldAutoCreateEmbeddedWallet:so}=useEmbeddedWallet(),co=reactExports.useRef(!1);useInternalDynamicEvents("logout",()=>{co.current=!1}),reactExports.useEffect(()=>{const lo=()=>__awaiter$j(void 0,void 0,void 0,function*(){co.current=!0;try{yield ao()}catch(ho){ho instanceof EmbeddedWalletException?logger$8.debug("Error creating embedded wallet",ho):logger$8.error("Error creating embedded wallet",ho),no(!1)}});!so()||!eo||!Xr||!ro.length||io||oo||co.current||lo()},[eo,Xr,to,ao,io,ro,oo,so,no])},useSyncOnboardingFlow=({handler:Xr}={})=>{const{setShowAuthFlow:eo,userWithMissingInfo:to,sdkHasLoaded:ro,setSelectedWalletConnectorKey:no}=useInternalDynamicContext(),{setView:io}=useViewContext(),{updateUser:oo}=useUserUpdateRequestInternal({validationSchemaStripUnknown:!1}),{completeAuth:ao,handleAuthError:so}=useUserAuth({}),{displayedDestination:co}=useVerification(),lo=reactExports.useRef(!1);useInternalDynamicEvents("logout",()=>{lo.current=!1}),reactExports.useEffect(()=>{var fo;const ho=()=>__awaiter$j(void 0,void 0,void 0,function*(){var yo;if(!(!Xr||!(!((yo=to==null?void 0:to.missingFields)===null||yo===void 0)&&yo.length))){lo.current=!0;try{const vo=to.missingFields.map(Ao=>({isCustom:Ao.type==="custom",key:Ao.name,label:Ao.label,required:Ao.required})),wo=yield Xr(vo),Eo={},ko=Object.assign({},to==null?void 0:to.metadata);wo.forEach(Ao=>{Ao.isCustom?ko[Ao.key]=Ao.value:Eo[Ao.key]=Ao.value}),yield ao({updateJwtFunction:()=>__awaiter$j(void 0,void 0,void 0,function*(){return oo(Object.assign(Object.assign({},Eo),{metadata:ko}))})})}catch(vo){logger$8.error("Error handling user onboarding",vo),so(vo,{})}}}),go=()=>__awaiter$j(void 0,void 0,void 0,function*(){lo.current=!0,eo(!0);const yo=to==null?void 0:to.verifiedCredentials.find(vo=>vo.id===(to==null?void 0:to.lastVerifiedCredentialId));switch(yo!=null&&yo.walletName&&no(yo==null?void 0:yo.walletName),yo==null?void 0:yo.format){case JwtVerifiedCredentialFormatEnum.Email:case JwtVerifiedCredentialFormatEnum.Oauth:io("collect-user-data-login-no-wallet",{userIdentification:"email"});break;case JwtVerifiedCredentialFormatEnum.PhoneNumber:io("collect-user-data-login-no-wallet",{userIdentification:"phoneNumber",userIdentificationOverride:co});break;default:io("collect-user-data")}});if(!(!ro||lo.current||!(!((fo=to==null?void 0:to.missingFields)===null||fo===void 0)&&fo.length)||hasPendingMfaAction(to))){if(Xr){ho();return}go()}},[ro,to,Xr,ao,oo,eo,io,co,so,no])},useSyncMfaFlow=({handler:Xr}={})=>{const{setShowAuthFlow:eo,userWithMissingInfo:to,sdkHasLoaded:ro}=useInternalDynamicContext(),{setView:no}=useViewContext(),{getUserDevices:io}=useMfa(),oo=reactExports.useRef(!1);useInternalDynamicEvents("logout",()=>{oo.current=!1}),reactExports.useEffect(()=>{var ao;if(!(!ro||oo.current)&&!(!to||!hasPendingMfaAction(to))){if(oo.current=!0,Xr){eo(!1),Xr();return}eo(!0),!((ao=to.scope)===null||ao===void 0)&&ao.includes("requiresAdditionalAuth")?io().then(so=>{so.length===0?no("mfa-choose-device"):no("mfa-verification")}):no("mfa-display-backup-codes")}},[io,ro,eo,no,to,Xr])},SyncAuthFlow=()=>(useSyncOnboardingFlow(),useSyncEmbeddedWalletFlow(),useSyncMfaFlow(),null),Switch=({disabled:Xr=!1,firstButton:eo,secondButton:to,thirdButton:ro})=>jsxRuntimeExports.jsxs("div",{className:classNames("switch__container",{disabled:Xr}),children:[jsxRuntimeExports.jsx("button",{disabled:Xr,className:classNames("button",{active:eo.active}),onClick:eo.handleButtonClick,children:eo.name}),jsxRuntimeExports.jsx("button",{disabled:Xr,className:classNames("button",{active:to.active}),onClick:to.handleButtonClick,children:to.name}),ro&&jsxRuntimeExports.jsx("button",{disabled:Xr,className:classNames("button",{active:ro.active}),onClick:ro.handleButtonClick,children:ro.name})]}),ThemeSwitch=()=>{const{changeTheme:Xr,theme:eo}=useThemeContext();return jsxRuntimeExports.jsx(Switch,{firstButton:{active:eo.theme.name==="light",handleButtonClick:()=>Xr("light"),name:"Light"},secondButton:{active:eo.theme.name==="dark",handleButtonClick:()=>Xr("dark"),name:"Dark"},thirdButton:{active:eo.theme.name==="auto",handleButtonClick:()=>Xr("auto"),name:"Auto"}})},PrimaryColorInput=()=>{const{changePrimaryColor:Xr,theme:eo}=useThemeContext(),[to,ro]=reactExports.useState(eo.customColor);return jsxRuntimeExports.jsx(Input,{id:"primary-color",label:"Primary color",value:to,onChange:no=>ro(no.target.value),onBlur:no=>{const io=to||eo.customColor;ro(io),Xr(io)}})},AuthModeSwitch=({authMode:Xr,setAuthMode:eo})=>jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"auth-mode-switch__container",children:[jsxRuntimeExports.jsx(Checkbox,{checked:Xr==="connect-and-sign",onChange:()=>eo("connect-and-sign"),id:"connect-and-sign"}),jsxRuntimeExports.jsx("label",{htmlFor:"connect-and-sign",children:jsxRuntimeExports.jsx(Typography,{color:"primary",weight:"regular",children:"Connect and sign"})})]}),jsxRuntimeExports.jsxs("div",{className:"auth-mode-switch__container",children:[jsxRuntimeExports.jsx(Checkbox,{checked:Xr==="connect-only",onChange:()=>eo("connect-only"),id:"connect-only"}),jsxRuntimeExports.jsx("label",{htmlFor:"connect-only",children:jsxRuntimeExports.jsx(Typography,{color:"primary",weight:"regular",children:"Connect only"})})]})]}),LoginWithEmailSwitch=()=>{const{loginWithEmail:Xr,setLogInWithEmail:eo}=useInternalDynamicContext();return jsxRuntimeExports.jsx(Switch,{firstButton:{active:Xr,handleButtonClick:()=>eo(!0),name:"True"},secondButton:{active:!Xr,handleButtonClick:()=>eo(!1),name:"False"}})},LoginWithEmailViewDisplayPriorityOrderSwitch=()=>{const{authorizationViewDisplayOrder:Xr,setAuthorizationViewDisplayOrder:eo,loginWithEmail:to}=useInternalDynamicContext();return jsxRuntimeExports.jsx(Switch,{disabled:!to,firstButton:{active:Xr==="web2",handleButtonClick:()=>eo("web2"),name:"Email"},secondButton:{active:Xr==="web3",handleButtonClick:()=>eo("web3"),name:"Wallet"}})},TemplateSelect=()=>{const{theme:Xr,changeTemplate:eo}=useThemeContext(),to=ro=>{eo(ro.target.value)};return jsxRuntimeExports.jsxs(Select,{label:"template",value:Xr.template,onChange:to,selectDataTestId:"template-select",children:[jsxRuntimeExports.jsx("option",{value:"default",children:"Default"}),jsxRuntimeExports.jsx("option",{value:"matrix",children:"Matrix"}),jsxRuntimeExports.jsx("option",{value:"minimal",children:"Minimal"}),jsxRuntimeExports.jsx("option",{value:"rounded",children:"Rounded"}),jsxRuntimeExports.jsx("option",{value:"trinity",children:"Trinity"})]})},Toolkit=()=>{const{projectSettings:Xr,user:eo,showAuthFlow:to,showDynamicUserProfile:ro,toolkitEnabled:no,authMode:io,setAuthMode:oo}=useInternalDynamicContext();return reactExports.useMemo(()=>no?ro||to:!1,[to,ro,no])?jsxRuntimeExports.jsx(ShadowDOM,{dataTestId:"toolkit-shadowdom",className:"toolkit-shadowdom",zIndex:toolkitZIndex,children:jsxRuntimeExports.jsxs("div",{className:"toolkit__container",children:[jsxRuntimeExports.jsxs("div",{className:"toolkit__switcher",children:[jsxRuntimeExports.jsx(Typography,{className:"switcher__copy",as:"h2",variant:"body_normal",children:"Theme"}),jsxRuntimeExports.jsx(ThemeSwitch,{})]}),jsxRuntimeExports.jsxs("div",{className:"toolkit__switcher",children:[jsxRuntimeExports.jsx(Typography,{className:"switcher__copy",as:"h2",variant:"body_normal",children:"Template"}),jsxRuntimeExports.jsx(TemplateSelect,{})]}),jsxRuntimeExports.jsxs("div",{className:"toolkit__switcher",children:[jsxRuntimeExports.jsx(Typography,{className:"switcher__copy",as:"h2",variant:"body_normal",children:"Primary Color"}),jsxRuntimeExports.jsx(PrimaryColorInput,{})]}),!eo&&jsxRuntimeExports.jsxs("div",{className:"toolkit__switcher",children:[jsxRuntimeExports.jsx(Typography,{className:"switcher__copy",as:"h2",variant:"body_normal",children:"Auth mode"}),jsxRuntimeExports.jsx(AuthModeSwitch,{authMode:io,setAuthMode:oo})]}),isEmailProviderEnabled((Xr==null?void 0:Xr.providers)||[])&&!eo&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"toolkit__switcher",children:[jsxRuntimeExports.jsx(Typography,{className:"switcher__copy",as:"h2",variant:"body_normal",children:"Log in with Email"}),jsxRuntimeExports.jsx(LoginWithEmailSwitch,{})]}),jsxRuntimeExports.jsxs("div",{className:"toolkit__switcher",children:[jsxRuntimeExports.jsx(Typography,{className:"switcher__copy",as:"h2",variant:"body_normal",children:"Email vs Wallet priority"}),jsxRuntimeExports.jsx(LoginWithEmailViewDisplayPriorityOrderSwitch,{})]})]})]})}):null},useTelegramLogin=()=>{const{sdkHasLoaded:Xr,user:eo,projectSettings:to,environmentId:ro}=useInternalDynamicContext(),no=(to==null?void 0:to.providers)||[],{completeConnection:io}=useSocialAuth({sessionTimeout:2e4}),oo=()=>typeof window>"u"?void 0:new URLSearchParams(window.location.search).get("telegramAuthToken")||void 0,ao=lo=>isProviderEnabled(no,ProviderEnum.Telegram)&&Xr&&!eo&&lo;return{isAuthWithTelegram:()=>__awaiter$j(void 0,void 0,void 0,function*(){const lo=oo();if(ao(lo))return isUserLinkedWithTelegram(ro,{telegramAuthToken:lo})}),telegramSignIn:(...lo)=>__awaiter$j(void 0,[...lo],void 0,function*({forceCreateUser:fo=!1}={}){const ho=oo();ao(ho)&&(yield io({authMode:"signin",forceCreateUser:fo,provider:ProviderEnum.Telegram,state:"",telegramAuthToken:ho}))})}},TelegramAutoLogin=()=>(useTelegramLogin(),null),WalletConnectorEvents=()=>{const{walletConnectorOptions:Xr,primaryWallet:eo}=useInternalDynamicContext(),{handleWalletItemClick:to}=useWalletItemActions();return reactExports.useEffect(()=>{const ro=({connector:no})=>{logger$8.debug("[WalletConnectorEvents] handleProviderReady - onProviderReady");const io=Xr.map(oo=>oo.key===no.key?Object.assign(Object.assign({},oo),{isInstalledOnBrowser:no.isInstalledOnBrowser(),walletConnector:no}):oo);setWalletConnectorOptions(io)};return walletConnectorEvents.on("providerReady",ro),()=>{walletConnectorEvents.off("providerReady",ro)}},[Xr]),reactExports.useEffect(()=>{const ro=({connector:no})=>{logger$8.debug("[useWalletItemActions] handleAutoConnect",{connector:no});const io=Xr.find(oo=>oo.walletConnector.key===no.key);io&&to(io)};if(!eo)return walletConnectorEvents.on("autoConnect",ro),()=>{walletConnectorEvents.off("autoConnect",ro)}},[to,Xr,eo]),null},getMissingChains=(Xr,eo)=>{if(!Xr||!eo)return;const to=new Set(eo.map(no=>no.walletChain));return Xr.filter(no=>!to.has(no.chain))},themeModes=["light","dark","auto"],isThemeSetting=Xr=>themeModes.includes(Xr),parseTheme=(Xr,eo)=>isThemeSetting(Xr)?getThemeConfig(eo,Xr):Xr,validTransitions$2={idle:["linking_new_wallet","primary_not_connected","switching_primary"],linking_new_wallet:["idle"],primary_not_connected:["idle"],switching_primary:["idle"]},validateStateTransition$2=({from:Xr,to:eo})=>{if(Xr!==eo&&!validTransitions$2[Xr].includes(eo))throw new Error(`Invalid AccountSwitch state transition from ${Xr} to ${eo}`);return!0},validateMultiWalletWidgetState$1=Xr=>{if(Xr!=="awaiting_account_switch")throw new Error(`Invalid MultiWalletWidget state while trying to set AccountSwitch state: ${Xr} Expected: awaiting_account_switch`)},useAwaitingAccountSwitch=()=>{const[Xr,eo]=reactExports.useState("idle"),to=reactExports.useCallback(()=>{eo("idle")},[eo]),ro=reactExports.useCallback((no,io)=>{validateMultiWalletWidgetState$1(io),validateStateTransition$2({from:Xr,to:no}),eo(no)},[Xr]);return[Xr,ro,to]},validTransitions$1={idle:["linking_new_wallet","transferring_wallet"],linking_new_wallet:["idle"],transferring_wallet:["idle"]},validateStateTransition$1=({from:Xr,to:eo})=>{if(Xr!==eo&&!validTransitions$1[Xr].includes(eo))throw new Error(`Invalid AwaitingSignature state transition from ${Xr} to ${eo}`);return!0},validateMultiWalletWidgetState=Xr=>{if(Xr!=="awaiting_signature")throw new Error(`Invalid MultiWalletWidget state while trying to set AwaitingSignature state: ${Xr} -Expected: awaiting_signature`)},useAwaitingSignature=()=>{const[Xr,eo]=reactExports.useState("idle"),to=reactExports.useCallback(()=>{eo("idle")},[eo]),ro=reactExports.useCallback((no,io)=>{validateMultiWalletWidgetState(io),validateStateTransition$1({from:Xr,to:no}),eo(no)},[Xr]);return[Xr,ro,to]},validTransitions={awaiting_account_switch:["awaiting_signature","idle"],awaiting_connection:["idle"],awaiting_signature:["idle"],detected_new_wallet:["awaiting_signature","idle"],idle:["awaiting_account_switch","awaiting_connection","awaiting_signature","detected_new_wallet"]},validateStateTransition=({from:Xr,to:eo})=>{if(Xr!==eo&&!validTransitions[Xr].includes(eo))throw new Error(`Invalid MultiWalletWidget state transition from ${Xr} to ${eo}`);return!0},useMultiWalletWidgetState=()=>{const[Xr,eo]=reactExports.useState("idle"),[to,ro,no]=useAwaitingAccountSwitch(),[io,oo,ao]=useAwaitingSignature(),so=reactExports.useCallback(()=>{no(),ao()},[no,ao]),co=reactExports.useCallback((lo,fo,ho)=>{validateStateTransition({from:Xr,to:lo}),eo(lo),so(),fo&&ro(fo,lo),ho&&oo(ho,lo)},[Xr,so,ro,oo]);return[Xr,co,{awaiting_account_switch:[to,ro],awaiting_signature:[io,oo]}]},useClearWalletConnectSessions=({connectors:Xr})=>{const eo=()=>{if(!(typeof window>"u")){for(const to of StorageService.getKeys())(to.startsWith("walletconnect")||to.startsWith("walletlink")||to.startsWith("wc@2"))&&localStorage.removeItem(to);Xr==null||Xr.forEach(to=>{var ro,no,io;!((no=(ro=to==null?void 0:to.name)===null||ro===void 0?void 0:ro.toLowerCase())===null||no===void 0)&&no.startsWith("turnkey")&&((io=to.getAuthenticatorHandler())===null||io===void 0||io.clear(),StorageService.removeItem(EMBEDDED_WALLET_SESSION_SETTINGS),StorageService.removeItem(EMBEDDED_WALLET_SECURE_BANNER))})}};return reactExports.useEffect(()=>{if(typeof window>"u"||Xr.length===0)return;const to=new Set(Xr.map(ro=>ro.key));for(const ro of StorageService.getKeys())ro.startsWith("walletconnect")&&!to.has(ro.replace("walletconnect-",""))&&localStorage.removeItem(ro)},[Xr]),{clearAllWalletConnectSessions:eo}},revokeSession=Xr=>__awaiter$j(void 0,[Xr],void 0,function*({environmentId:eo,sessionId:to}){try{yield sdkApi$1().revokeSession({environmentId:eo})}catch(ro){const no=yield ro.json();logger$8.error(Error(no.error.message))}}),mapChainToChainEnum=Xr=>{const eo=Object.values(ChainEnum).find(to=>to===Xr);if(!eo)throw new DynamicError(`Invalid chain ${Xr}`);return eo},mapProviderToProviderEnum=Xr=>{const eo=Object.values(WalletProviderEnum).find(to=>to===Xr);if(!eo)throw new DynamicError(`Invalid provider ${Xr}`);return eo},mapAuthModeTypeToEnum=Xr=>{const eo=Object.values(AuthModeEnum).find(to=>to===Xr);if(!eo)throw new DynamicError(`Invalid authMode ${Xr}`);return eo},createVisit=Xr=>__awaiter$j(void 0,[Xr],void 0,function*({authMode:eo,chain:to,environmentId:ro,walletProvider:no,publicWalletAddress:io,walletName:oo}){try{const ao={address:io,authMode:mapAuthModeTypeToEnum(eo),chain:mapChainToChainEnum(to),provider:mapProviderToProviderEnum(no),walletName:oo};yield sdkApi$1().createVisit({connectRequest:ao,environmentId:ro})}catch(ao){logger$8.error(ao)}}),getWalletConnectorForWallet=Xr=>{var eo,to;if(!Xr)return;const ro=getWalletConnectorOptions(),{key:no,chain:io}=Xr,oo=(eo=ro.find(so=>no===so.key&&so.walletConnector.connectedChain===io))===null||eo===void 0?void 0:eo.walletConnector;return oo||((to=ro.find(so=>so.key==="fallbackconnector"))===null||to===void 0?void 0:to.walletConnector)},updateUserWalletsFromConnectedWallets=(Xr,eo)=>{const to=[...Xr],ro=new Set;for(const no of eo)ro.add(no.address),to.find(oo=>oo.address===no.address)||to.push(no);return to.filter(no=>ro.has(no.address)||no.isAuthenticated)},useConnectWallet=({authMode:Xr,clearPrimaryWalletId:eo,enableVisitTrackingOnConnectOnly:to,environmentId:ro,primaryWalletId:no,setPrimaryWalletId:io,walletConnectorOptions:oo,handleConnectedWallet:ao,setShowAuthFlow:so,isBridgeFlow:co,user:lo})=>{const[fo,ho,go]=useLocalStorage(CONNECTED_WALLETS_INFO,[]),[yo,vo]=reactExports.useState([]),{setUserWallets:wo,addedWalletsIds:Eo,removedWalletsIds:ko}=useInternalUserWallets(),Ao=reactExports.useCallback(Bo=>{vo(Bo),wo(xo=>updateUserWalletsFromConnectedWallets(xo,Bo))},[wo]),Po=reactExports.useCallback(Bo=>__awaiter$j(void 0,void 0,void 0,function*(){const xo=yo.find(bo=>bo.id===Bo);yield xo==null?void 0:xo.connector.endSession();const uo=fo.filter(bo=>bo.id!==Bo);if(ho(uo),ko.current.push(Bo),Bo!==no)return;const po=uo.length>0;co||!po?eo():io(uo[0].id)}),[eo,yo,fo,co,no,ko,ho,io]),jo=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const Bo=oo.map(uo=>uo.walletConnector);if(!Bo.length)return;const xo=(yield Promise.all(fo.map(uo=>__awaiter$j(void 0,void 0,void 0,function*(){const po=getWalletConnectorByKey(Bo,uo.walletConnectorKey);if(!po)return logger$9.error("Could not find walletConnector: "+uo.walletConnectorKey),yield Po(uo.id),null;isHardwareWalletConnector(po)&&uo.hardwareWallet===HardwareWalletEnum.Ledger&&(po.isHardwareWalletEnabled=!0);const[bo]=yield po.getConnectedAccounts();if(!bo)return yield Po(uo.id),null;const _o=yield po.getAdditionalAddresses(bo),$o=po.connectedChain;return po.createWallet({additionalAddresses:_o,address:bo,chain:$o,connector:po,id:uo.id,isAuthenticated:!1,key:po.key})})))).filter(uo=>!!uo);Ao(xo)}),[fo,Po,Ao,oo]);reactExports.useEffect(()=>{jo()},[fo,oo]);const Mo=reactExports.useCallback(Bo=>{const uo=Bo.map(({id:po})=>po).map(po=>Number(po.replace("connect-wallet-",""))).sort((po,bo)=>po-bo);for(let po=0;po{var uo;const po=[...yo],bo=po.findIndex(_o=>_o.id===Bo);bo<0||(po[bo]=po[bo].connector.createWallet(Object.assign(Object.assign({},po[bo]),{address:(uo=xo.address)!==null&&uo!==void 0?uo:po[bo].address,connector:getWalletConnectorForWallet(po[bo])})),Ao(po))},[yo,Ao]),Do=({walletId:Bo,walletConnectorKey:xo,walletChain:uo,provider:po})=>{const bo=[...fo],_o=oo.map(Ro=>Ro.walletConnector),$o=getWalletConnectorByKey(_o,xo),Co=$o&&isHardwareWalletConnector($o)&&$o.isHardwareWalletEnabled?HardwareWalletEnum.Ledger:void 0;bo.push({hardwareWallet:Co,id:Bo,provider:po,walletChain:uo,walletConnectorKey:xo}),ho(bo)},Fo=(Bo,xo)=>__awaiter$j(void 0,void 0,void 0,function*(){shouldManuallyReconnectOnRefresh(xo)&&(yield xo.connect());const uo=yield xo.getAddress();if(uo&&ao&&!(yield ao({address:uo,chain:xo.connectedChain,connector:xo}))){logger$9.info("Connection was not established because handleConnectedWallet returned false"),Po(Bo),so(!1,{emitCancelAuth:!0});return}No(Bo,{address:uo})}),Xo=(Bo,xo,uo)=>__awaiter$j(void 0,void 0,void 0,function*(){const{applyHandleConnectedWallet:po=!0}=uo??{},bo=yield Bo.getAddress(xo);if(!bo)throw new MissingPublicAddressError;if(ao&&po&&!(yield ao({address:bo,chain:Bo.connectedChain,connector:Bo}))){logger$9.info("Connection was not established because handleConnectedWallet returned false"),so(!1);return}const _o=fo.some(({walletConnectorKey:So})=>So===Bo.key),$o=Bo.connectedChain;if(!_o&&(Xr!=="connect-only"||to)&&createVisit({authMode:Xr,chain:$o||"",environmentId:ro,publicWalletAddress:bo,walletName:Bo.key,walletProvider:getWalletProvider(Bo)}),!isConnectOnly(lo,Xr))return{address:bo,id:""};const Ro=`connect-wallet-${Mo(fo)}`;return no||io(Ro),Eo.current.push(Ro),_o?yield jo():Do({provider:getWalletProvider(Bo),walletAddress:bo,walletChain:$o,walletConnectorKey:Bo.key,walletId:Ro}),{address:bo,id:Ro}}),Lo=reactExports.useCallback(Bo=>yo.find(xo=>xo.id===Bo),[yo]);return{connectWallet:Xo,connectedWallets:yo,connectedWalletsInfo:fo,disconnectWallet:Po,getConnectedWalletById:Lo,refreshConnectedWallet:Fo,removeConnectedWalletsInfo:go}},useFetchWalletsForChainsMap=Xr=>({walletsForChainsMap:reactExports.useMemo(()=>Xr?Object.assign(Object.assign({},defaultWalletsForChains),{primary_chain:Xr.primary_chain,wallets:Object.assign(Object.assign({},defaultWalletsForChains.wallets),!!Xr.wallets&&Xr.wallets)}):defaultWalletsForChains,[Xr])}),useHandleUnlinkWallet=({verifiedCredentials:Xr,environmentId:eo,primaryWalletId:to,secondaryWallets:ro})=>{const{removedWalletsIds:no}=useInternalUserWallets();return reactExports.useCallback(oo=>__awaiter$j(void 0,void 0,void 0,function*(){var ao;const so=(ao=StorageService.getItem(PRIMARY_WALLET_ID))!==null&&ao!==void 0?ao:to;if(oo===so)return;yield unlinkWallet({environmentId:eo,onSuccess:()=>{no.current.push(oo)},primaryWalletId:so,walletId:oo});const co=ro.find(fo=>fo.id===oo);Xr.filter(fo=>fo.walletName===((co==null?void 0:co.connector.key)||"")).length===1&&(yield co==null?void 0:co.connector.endSession())}),[to,eo,ro,Xr,no])},primaryWalletIdValidator=Xr=>typeof Xr=="string"||typeof Xr>"u",usePrimaryWalletId=({environmentId:Xr,user:eo})=>{const[to,ro,no]=useLocalStorage(PRIMARY_WALLET_ID,void 0,primaryWalletIdValidator),io=reactExports.useCallback(oo=>__awaiter$j(void 0,void 0,void 0,function*(){ro(oo),eo&&(yield storeSelectedWallet({environmentId:Xr,walletId:oo}))}),[Xr,ro,eo]);return{clearPrimaryWalletId:no,primaryWalletId:to,setPrimaryWalletId:io}},useWalletEventListeners=({disconnectWallet:Xr,handleLogOut:eo,multiWallet:to,multiWalletWidgetState:ro,primaryWallet:no,secondaryWallets:io,selectedWalletConnector:oo,selectedWalletWithAction:ao,setSelectedWalletConnectorKey:so,setSelectedWalletWithAction:co,setMultiWalletWidgetState:lo,user:fo,setPrimaryWalletId:ho,authMode:go,refreshConnectedWallet:yo,detectNewWalletsForLinking:vo})=>{const wo=reactExports.useCallback((Ao,Po)=>{logger$8.debug("handleAccountChangeWhenAwaitingAccountSwitch",{isPrimaryWallet:Ao,newAddress:Po});const jo=io.find(No=>isSameAddress$1(No.address,Po,No.chain));if(logger$8.logVerboseTroubleshootingMessage("[handleAccountChangeWhenAwaitingAccountSwitch]",{linkedSecondaryWallet:jo}),!jo){lo("awaiting_signature",void 0,"linking_new_wallet"),Ao&&no&&so(no.connector.key);return}if(jo.connector.key==="unknown"){dynamicEvents.emit("triggerConnectAndSign");return}co(null),ho(jo.id),lo("idle")},[lo,no,io,so,co,ho]),Eo=reactExports.useCallback(({accounts:Ao})=>{if(logger$8.debug("calculatePrimaryWalletMultiWalletStateFromAccounts",{accounts:Ao,authMode:go,multiWallet:to,multiWalletWidgetState:ro,primaryWallet:no}),!no)return;const[Po]=Ao;if(!!isSameAddress$1(Po,no.address,no.chain)){lo("idle");return}if(go==="connect-only"){yo(no.id,no.connector);return}if(!to)return;if(ro==="awaiting_account_switch"){wo(!0,Po);return}ro!=="idle"&&(logger$8.error(`Unexpected multiWalletWidgetState (${ro}) and onAccountChange combination. Resetting state to idle.`),lo("idle"));const Mo=io.find(No=>isSameAddress$1(No.address,Po,No.chain));if(Mo){ho(Mo.id);return}fo&&vo&&(lo("detected_new_wallet"),so(no.connector.key))},[go,vo,wo,to,ro,no,yo,io,lo,ho,so,fo]);useInternalDynamicEvents("triggerComputePrimaryWalletMultiWalletStateFromAccounts",Eo),useWalletConnectorEvent(no==null?void 0:no.connector,"accountChange",({accounts:Ao})=>{logger$8.debug("primary wallet account change",{accounts:Ao}),Eo({accounts:Ao})});const ko=reactExports.useMemo(()=>{const Ao=no==null?void 0:no.connector,Po=io.map(({connector:Mo})=>Mo),jo=new Set([...Po,Ao,oo].filter(Mo=>!!Mo));return Ao&&jo.delete(Ao),Array.from(jo)},[io,oo,no==null?void 0:no.connector]);useWalletConnectorEvent(ko,"accountChange",(Ao,Po)=>__awaiter$j(void 0,void 0,void 0,function*(){if(logger$8.debug("secondary wallet account change"),go==="connect-only"&&io.length){const jo=io.filter(({connector:Mo})=>Mo.key===Po.key);for(const Mo of jo)yo(Mo.id,Mo.connector);return}ro==="awaiting_account_switch"&&wo(!1,(ao==null?void 0:ao.wallet.address)||"")})),useWalletConnectorEvent(no==null?void 0:no.connector,"disconnect",()=>{logger$8.debug("primary wallet disconnect"),go==="connect-only"&&eo()}),useWalletConnectorEvent(ko,"disconnect",Ao=>{if(logger$8.debug("secondary wallet disconnect"),go==="connect-only"){const Po=io.filter(({connector:jo})=>jo.key===Ao.key);for(const jo of Po)Xr(jo.id)}})},useTabState=({settingsOverrides:Xr})=>{var eo,to,ro;const no=(eo=Xr==null?void 0:Xr.views)===null||eo===void 0?void 0:eo.find(so=>so.type==="wallet-list"),[io,oo]=reactExports.useState(0),ao=io===null||(to=no==null?void 0:no.tabs)===null||to===void 0?void 0:to.items[io];return{selectedTabIndex:io,selectedTabSettings:ao,setSelectedTabIndex:oo,tabsItems:(ro=no==null?void 0:no.tabs)===null||ro===void 0?void 0:ro.items}},DynamicBridgeWidgetContext=React.createContext(void 0),initialView="wallets",DynamicBridgeWidgetContextProvider=({children:Xr})=>{const eo=reactExports.useRef(null),to=reactExports.useRef(null),[ro,no]=reactExports.useState(initialView),io=reactExports.useCallback(()=>{no(initialView)},[]),oo=reactExports.useCallback(()=>{no("profile")},[]),ao={bridgeWidgetView:ro,events:{onDynamicBridgeWidgetClose:io},goToProfileView:oo,inlineControlsRef:to,setBridgeWidgetView:no,widgetRef:eo};return jsxRuntimeExports.jsx(DynamicBridgeWidgetContext.Provider,{value:ao,children:Xr})},DynamicWidgetCard=reactExports.forwardRef(({children:Xr},eo)=>jsxRuntimeExports.jsx("div",{ref:eo,className:"dynamic-widget-card",children:Xr}));DynamicWidgetCard.displayName="DynamicWidgetCard";const widgetRegistryContext=reactExports.createContext(null),WidgetRegistryContextProvider=({children:Xr})=>{const[eo,to]=reactExports.useState({}),ro=reactExports.useCallback((oo,ao)=>{to(so=>Object.assign(Object.assign({},so),{[oo]:{type:ao}}))},[to]),no=reactExports.useCallback(oo=>{to(ao=>{const so=Object.assign({},ao);return delete so[oo],so})},[to]),io=reactExports.useCallback(oo=>Object.values(eo).some(ao=>ao.type===oo),[eo]);return jsxRuntimeExports.jsx(widgetRegistryContext.Provider,{value:{checkWidgetPresence:io,registerId:ro,removeId:no},children:Xr})},Modal=({onrampUrl:Xr})=>{const{fundingRef:eo,setShowFunding:to}=useFundingContext();return useOnClickOutside(eo,()=>{to(!1)}),jsxRuntimeExports.jsx("div",{className:"fund-wallet__modal","data-testid":"fund-wallet-modal",children:jsxRuntimeExports.jsx("div",{className:"fund-wallet__modal-content",ref:eo,children:jsxRuntimeExports.jsx("iframe",{id:"onramp-iframe",src:Xr,allow:"camera *;geolocation *",title:"Crypto Onramp"})})})},FundWalletView=()=>{const{primaryWallet:Xr}=useInternalDynamicContext(),{showFunding:eo,fundingUrl:to,fundingEnabled:ro}=useFundingContext();return!ro||!eo||!to||!(Xr!=null&&Xr.address)?null:jsxRuntimeExports.jsx(ShadowDOM,{children:jsxRuntimeExports.jsxs(OpacityTransition,{isShown:eo,children:[jsxRuntimeExports.jsx("div",{className:"fund-wallet__backdrop","aria-hidden":"true"}),jsxRuntimeExports.jsx("div",{className:"fund-wallet__modal-container",children:jsxRuntimeExports.jsx(Modal,{onrampUrl:to})})]})})},FundingWidget=()=>jsxRuntimeExports.jsx(FundWalletView,{}),ConnectWithOtpContext=reactExports.createContext(void 0),createEmailHandler=(Xr,{shouldRegisterSessionKeysOnSignin:eo,generateSessionKey:to})=>ro=>__awaiter$j(void 0,void 0,void 0,function*(){const no=yield createEmailVerification({email:ro,environmentId:Xr});let{verificationUUID:io}=no;return{retry:()=>__awaiter$j(void 0,void 0,void 0,function*(){io=(yield retryEmailVerification({email:ro,environmentId:Xr,verificationUUID:io})).verificationUUID}),type:"email",verify:oo=>__awaiter$j(void 0,void 0,void 0,function*(){let ao;eo()&&(ao=(yield to()).publicKey);const so=yield signInWithEmailVerification({environmentId:Xr,sessionPublicKey:ao,verificationToken:oo,verificationUUID:io});return storeAuthTokenAndUser(so),{destination:ro,verified:!!so.jwt}})}}),createMagicHandler=(Xr,eo)=>to=>__awaiter$j(void 0,void 0,void 0,function*(){if(!Xr)throw new Error("OTP wallet connector was not found");return Xr.setEmail(to),eo(Xr),{retry:()=>Xr.retryOneTimePassword(),type:"email",verify:ro=>__awaiter$j(void 0,void 0,void 0,function*(){return{destination:to,verified:yield Xr.verifyOneTimePassword(ro)}})}}),createSmsHandler=Xr=>eo=>__awaiter$j(void 0,void 0,void 0,function*(){const{generateSessionKey:to,shouldRegisterSessionKeysOnSignin:ro}=useEmbeddedWalletSessionKeys(Xr),{verificationUUID:no}=yield createSmsVerification({environmentId:Xr,isoCountryCode:eo.iso2,phoneCountryCode:eo.dialCode,phoneNumber:eo.phone});return{type:"sms",verify:io=>__awaiter$j(void 0,void 0,void 0,function*(){let oo;ro()&&(oo=(yield to()).publicKey);const ao=yield signInWithSmsVerification({environmentId:Xr,sessionPublicKey:oo,verificationToken:io,verificationUUID:no});return storeAuthTokenAndUser(ao),{destination:eo,verified:!!ao.jwt}})}}),mapEmailProviderToProviderEnum={dynamic:ProviderEnum.Dynamic,magicLink:ProviderEnum.MagicLink},allSupportedProviders=Object.values(mapEmailProviderToProviderEnum),findEmailProvider=(Xr,eo)=>__awaiter$j(void 0,void 0,void 0,function*(){const{emailProvider:to}=yield getEmailProvider({email:eo,environmentId:Xr});if(!allSupportedProviders.includes(to))throw new Error("Email provider is not supported");return to}),{Provider:Provider$1}=ConnectWithOtpContext,ConnectWithOtpProvider=({children:Xr})=>{const{walletConnectorOptions:eo,environmentId:to,projectSettings:ro,setCallback:no}=useInternalDynamicContext(),io=useEmbeddedWalletSessionKeys(to),{handleInstalledExtensionClick:oo}=useWalletItemActions(),ao=reactExports.useRef(null),so=(ro==null?void 0:ro.providers)||[],co=eo.map(({walletConnector:vo})=>vo).find(isEmailOTPWalletConnector),lo={[ProviderEnum.Dynamic]:{enabled:isProviderEnabled(so,ProviderEnum.Dynamic),handler:createEmailHandler(to,io)},[ProviderEnum.MagicLink]:{enabled:isProviderEnabled(so,ProviderEnum.MagicLink),handler:createMagicHandler(co,oo)}},fo=(vo,...wo)=>__awaiter$j(void 0,[vo,...wo],void 0,function*(Eo,{provider:ko}={}){if(!isEmailValid(Eo))throw new Error("Email is not valid");const Ao=ko||(yield findEmailProvider(to,Eo));if(!lo[Ao].enabled)throw new Error("Email provider is not enabled");const Po=yield lo[Ao].handler(Eo);ao.current=Po}),ho=vo=>__awaiter$j(void 0,void 0,void 0,function*(){if(!isProviderEnabled(so,ProviderEnum.Sms))throw new Error("SMS provider is not enabled");const Eo=yield createSmsHandler(to)(vo);ao.current=Eo}),go=vo=>__awaiter$j(void 0,void 0,void 0,function*(){if(!ao.current)throw new Error("Verification has not started, use connectWithEmail or connectWithSms before verifying");const{type:wo,verify:Eo}=ao.current,{destination:ko,verified:Ao}=yield Eo(vo);if(wo==="sms"?dynamicEvents.emit("smsVerificationResult",Ao,ko):dynamicEvents.emit("emailVerificationResult",Ao,ko),Ao)no("authSuccess");else throw new Error(`${wo==="sms"?"SMS":"Email"} verification failed`)}),yo=()=>__awaiter$j(void 0,void 0,void 0,function*(){if(!ao.current)throw new Error("Verification has not started, use connectWithEmail or connectWithSms before verifying");if(!ao.current.retry)throw new Error("Re-send is not supported");return ao.current.retry()});return jsxRuntimeExports.jsx(Provider$1,{value:{connectWithEmail:fo,connectWithSms:ho,retryOneTimePassword:yo,verifyOneTimePassword:go},children:Xr})},ERROR_BOUNDARY_CONTEXT_NOT_FOUND="ERROR_BOUNDARY_CONTEXT_NOT_FOUND",ErrorBoundaryContext=reactExports.createContext(null);function assertErrorBoundaryContext(Xr){if(Xr===null||typeof Xr.hasError!="boolean"||typeof Xr.error!="object"||typeof Xr.isDynamicSdkError!="boolean"){const eo=new Error("ErrorBoundaryContext not found");throw eo.cause=ERROR_BOUNDARY_CONTEXT_NOT_FOUND,eo}}class ErrorBoundaryBase extends reactExports.Component{static getDerivedStateFromError(eo){return{error:eo,hasError:!0}}renderOrError(eo,{isDynamicSdkError:to}){try{assertErrorBoundaryContext(this.context),this.context.isDynamicSdkError=to}catch(ro){return logger$8.error(ro),reactExports.createElement(ErrorContainer,null,"ErrorBoundary must be used within ErrorBoundaryContext")}return eo}}ErrorBoundaryBase.contextType=ErrorBoundaryContext;class ErrorBoundaryReporter extends ErrorBoundaryBase{constructor(eo){super(eo),this.state={error:null,hasError:!1}}componentDidCatch(eo,to){var ro;const{onError:no}=this.props;throw!((ro=this.context)===null||ro===void 0)&&ro.isDynamicSdkError&&(no==null||no(eo,to),logger$8.error(eo,{error:{bundleStack:eo.stack,message:eo,stack:to.componentStack}})),eo}render(){const{children:eo}=this.props,{hasError:to,error:ro}=this.state;return to?(assertErrorBoundaryContext(this.context),this.context.error=ro,this.context.hasError=to,null):eo}}const ErrorBoundary=Xr=>{var{children:eo}=Xr,to=__rest$7(Xr,["children"]);return jsxRuntimeExports.jsx(ErrorBoundaryContext.Provider,{value:{error:null,hasError:!1,isDynamicSdkError:!0},children:jsxRuntimeExports.jsx(ErrorBoundaryReporter,Object.assign({},to,{children:eo}))})};class ErrorBoundaryExclude extends ErrorBoundaryBase{render(){const{children:eo}=this.props;return this.renderOrError(eo,{isDynamicSdkError:!1})}}const useResponseHandlers=()=>{const{walletConnectorOptions:Xr,consumeNonce:eo,displaySiweStatement:to,environmentId:ro,projectSettings:no,setIsSingleWalletAccount:io,connectWallet:oo,setShowAuthFlow:ao,setSelectedWalletConnectorKey:so,siweStatement:co,appName:lo,user:fo}=useInternalDynamicContext(),{setView:ho}=useViewContext(),{setErrorMessage:go}=useErrorContext(),{getCaptchaToken:yo}=useCaptchaContext(),vo=useVerifyWallet({consumeNonce:eo,displaySiweStatement:to,environmentId:ro,projectSettings:no,setIsSingleWalletAccount:io}),wo=Xr.map(({walletConnector:jo})=>jo).find(isPhantomRedirectConnector),Eo=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){wo&&(yield wo.getSession(),yield oo(wo),ao(!0,{ignoreIfIsEmbeddedWidget:!0}),ho("pending-signature"),so("phantom"))}),[oo,wo,so,ao,ho]),ko=useTransferWallet(),Ao=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){if(!wo)return;so("phantom");const[jo]=yield wo.getConnectedAccounts();switch(wo.consumeMethod()){case"signAndSendTransaction":{const{signature:No}=wo.extractSignature();wo.emit("signAndSendTransaction",{signature:No});break}case"signAllTransactions":wo.emit("signAllTransactions",{transactions:wo.extractTransactions()});break;case"signTransaction":wo.emit("signTransaction",{transaction:wo.extractTransaction()});break;case"signMessage":{const{signature:No,message:Do}=wo.extractSignature(),Fo=StorageService.getItem(PHANTOM_SIGNATURE_STATE);if(StorageService.removeItem(PHANTOM_SIGNATURE_STATE),(Fo==null?void 0:Fo.verificationType)==="awaiting_transfer"){const Xo=getSiweStatement({appName:lo,siweStatement:co});yield ko({messageToSignOverride:Do,overrideSiweStatement:Xo,publicWalletAddress:jo,signedMessageOverride:No,skipEmptyAccountCheck:Fo.loseOriginalAccountOnTransfer,walletConnector:wo})}else(Fo==null?void 0:Fo.verificationType)==="awaiting_verification"||!fo?(ho("wallet-redirect-view"),yield vo({captchaToken:yo(),messageToSignOverride:Do,publicWalletAddress:jo,signedMessageOverride:No,walletConnector:wo})):wo.emit("signMessage",{signature:No});break}}}),[wo,so,fo,lo,co,ko,ho,vo,yo]),Po=reactExports.useCallback(jo=>{var Mo;if(!wo)return;const No=jo.get("errorCode"),Do=(Mo=jo.get("errorMessage"))!==null&&Mo!==void 0?Mo:void 0;if(!No)return;switch(go(No),jo.delete("errorCode"),jo.delete("errorMessage"),history.replaceState(null,"",`${window.location.origin}${window.location.pathname}?${jo.toString()}`),wo.consumeMethod()){case"signAndSendTransaction":wo.emit("signAndSendTransaction",{errorCode:No,errorMessage:Do});break;case"signAllTransactions":wo.emit("signAllTransactions",{errorCode:No,errorMessage:Do});break;case"signTransaction":wo.emit("signTransaction",{errorCode:No,errorMessage:Do});break;case"signMessage":wo.emit("signMessage",{errorCode:No,errorMessage:Do});break}},[wo,go]);return{handleConnectResponse:Eo,handleErrorResponse:Po,handleUserResponse:Ao,phantomRedirectConnector:wo}},PhantomRedirectContext=reactExports.createContext(void 0),PhantomRedirectContextProvider=({children:Xr})=>{const{sdkHasLoaded:eo}=useInternalDynamicContext(),{phantomRedirectConnector:to,handleConnectResponse:ro,handleUserResponse:no,handleErrorResponse:io}=useResponseHandlers();return reactExports.useEffect(()=>{if(!to||!isMobile$1()||!eo)return;const oo=new URLSearchParams(window.location.search);if(oo.has("errorCode")){io(oo);return}if(oo.has("phantom_encryption_public_key")){ro();return}if(oo.has("data")){no();return}},[ro,no,io,to,eo]),jsxRuntimeExports.jsx(PhantomRedirectContext.Provider,{value:{phantomRedirectConnector:to},children:Xr})},reinitializeContext=reactExports.createContext(void 0),ReinitializeContextProvider=({children:Xr,onReinitialize:eo})=>{const[to,ro]=reactExports.useState(),no=reactExports.useRef(eo);no.current=eo;const io=reactExports.useCallback(()=>{var oo;const ao=randomString(8);(oo=no.current)===null||oo===void 0||oo.call(no,ao),ro(ao)},[]);return jsxRuntimeExports.jsx(reinitializeContext.Provider,{value:{key:to,reinitialize:io},children:reactExports.cloneElement(Xr,{key:to})})},useConnectedWalletsNetworkValidation=()=>{const{connectedWallets:Xr,selectedWalletConnector:eo,setSelectedWalletConnectorKey:to,setShowAuthFlow:ro,bridgeChainsToConnect:no,sdkHasLoaded:io}=useInternalDynamicContext(),{setView:oo}=useViewContext(),ao=useIsLoggedIn(),so=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const fo=[];for(const ho of Xr){const go=no==null?void 0:no.some(wo=>wo.chain===ho.chain),yo=yield ho.connector.getNetwork(),vo=isSupportedNetwork({network:yo,walletConnector:ho.connector});!go&&!vo&&fo.push(ho)}return fo}),[no,Xr]),co=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const fo=yield so();if(!fo.length)return;const[ho]=fo;ho.connector.key!==(eo==null?void 0:eo.key)&&to(ho.connector.key);const go=isProgrammableNetworkSwitchSupported(ho.connector)?"network-not-supported":"network-not-supported-manual";ro(!0),oo(go)}),[so,eo==null?void 0:eo.key,to,ro,oo]),lo=reactExports.useMemo(()=>{const fo=Xr.map(({connector:go})=>go),ho=new Set([...fo].filter(go=>!!go));return Array.from(ho)},[Xr]);useWalletConnectorEvent(lo,"chainChange",({chain:fo})=>{co()}),reactExports.useEffect(()=>{!io||!ao||co()},[io,ao,co])},UseNetworkValidation=()=>(useConnectedWalletsNetworkValidation(),null),isDisplayOrderPriorityForWeb3=Xr=>{if(Xr.length!==2)return!1;const[eo,to]=Xr;return eo==="wallet"&&to==="email"},useDisplayOrderState=Xr=>{const[eo,to]=reactExports.useState(null),ro=reactExports.useMemo(()=>{var no;const io=(no=Xr==null?void 0:Xr.design.modal)===null||no===void 0?void 0:no.displayOrder;return io?isDisplayOrderPriorityForWeb3(io)?"web3":"web2":"web3"},[Xr]);return[eo||ro,to]},useEmailLoginState=(Xr,eo)=>{const[to,ro]=reactExports.useState(null),no=()=>{ro(null)},io=ao=>{ro(ao)},oo=reactExports.useMemo(()=>eo?!1:isEmailProviderEnabled(Xr),[Xr,eo]);return[to??oo,io,no]},useHandleLogout=Xr=>{const eo=reactExports.useRef(Xr);eo.current=Xr;const to=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const ro=eo.current;ro.setSelectedWalletConnectorKey(null),ro.clearAllWalletConnectSessions(),ro.setShowDynamicUserProfile(!1),ro.setShowBridgeWidget(!1),ro.resetLoginWithEmail(),ro.user&&(document.cookie=`${DYNAMIC_AUTH_COOKIE_NAME}=; Max-Age=-99999999; path=/; SameSite=Lax`,revokeSession({environmentId:ro.environmentId,sessionId:ro.user.sessionId})),ro.setLegacyIsVerifying(!1),StorageService.removeItem(AUTH_TOKEN,{priority:["secureStorage","localStorage"]}),StorageService.removeItem(AUTH_MIN_TOKEN$1,{priority:["secureStorage","localStorage"]}),StorageService.removeItem(WALLET_PICKER_SEARCH_KEY),StorageService.removeItem(PHANTOM_SIGNATURE_STATE),StorageService.removeItem(AUTH_EXPIRES_AT),ro.setAuthMode(ro.initialAuthenticationMode),ro.setShowAuthFlow(!1,{emitCancelAuth:!1,ignoreIfIsEmbeddedWidget:!1,initializeWalletConnect:!1,performMultiWalletChecks:!1}),ro.setMultiWalletWidgetState("idle"),ro.removeConnectedWalletsInfo(),ro.removeBridgeOnboardingCompleted(),ro.clearPrimaryWalletId(),ro.removeConnectedNameService(),ro.removeSessionStorageSessionKeys(),dynamicEvents.removeListener("embeddedWalletCreatePasswordCompleted"),dynamicEvents.removeListener("embeddedWalletCreatePasswordFailed"),dynamicEvents.removeListener("embeddedWalletUpdatePasswordCompleted"),dynamicEvents.removeListener("embeddedWalletUpdatePasswordFailed"),dynamicEvents.emit("logout"),setUser(void 0),yield Promise.all(ro.walletConnectors.map(no=>no.endSession())),yield Promise.all(ro.connectedWallets.map(no=>no.connector.endSession()))}),[]);return reactExports.useEffect(()=>(StorageService.events.on("parseFailure",to),()=>{StorageService.events.off("parseFailure",to)}),[to]),to},getWalletVerifiedCredential=(Xr,eo,to)=>eo==null?void 0:eo.find(({address:ro})=>isSameAddress$1(ro||"",Xr||"",to)),useNameService=({currentWallet:Xr,user:eo})=>{const[to,ro,no]=useLocalStorage(CONNECTED_WALLET_NAME_SERVICE,null),io=reactExports.useRef(),oo=reactExports.useRef(),ao=reactExports.useCallback(co=>__awaiter$j(void 0,void 0,void 0,function*(){const{address:lo,connector:fo}=co,ho=yield fo.getNetwork();if(lo===io.current&&ho===oo.current)return;ro(null),io.current=lo,oo.current=ho;let go;try{go=yield co.getNameService()}catch{}if(io.current===lo&&oo.current===ho)return ro({address:lo,avatar:go==null?void 0:go.avatar,name:go==null?void 0:go.name,network:ho}),go}),[ro]);return{getNameService:co=>__awaiter$j(void 0,void 0,void 0,function*(){var lo;if(!Xr)return;const fo=yield Xr.connector.getNetwork(),ho=eo==null?void 0:eo.verifiedCredentials;if(ho){const go=getWalletVerifiedCredential(Xr==null?void 0:Xr.address,ho,Xr.chain);if(go&&(!((lo=go.nameService)===null||lo===void 0)&&lo.name))return go.nameService}if(!(co&&(Xr==null?void 0:Xr.address)!==co))return to&&to.address===(Xr==null?void 0:Xr.address)&&to.network===fo?{avatar:to.avatar,name:to.name}:ao(Xr)}),removeConnectedNameService:no}},useSelectedWalletConnector=({walletConnectorOptions:Xr})=>{const[eo,to]=reactExports.useState(null);return{selectedWalletConnector:reactExports.useMemo(()=>{var no,io;return eo&&(io=(no=Xr.find(({walletConnector:oo})=>oo.key===eo))===null||no===void 0?void 0:no.walletConnector)!==null&&io!==void 0?io:null},[eo,Xr]),setSelectedWalletConnectorKey:to}},useShowAuthFlow=({isAuthenticated:Xr,isRenderingEmbeddedAuthFlow:eo,isMultiWalletEnabled:to,walletConnectorOptions:ro,setShowDynamicUserProfile:no})=>{const[io,oo]=reactExports.useState(!1),{setError:ao}=useErrorContext(),so=reactExports.useCallback((co,lo={})=>{var fo;const{emitCancelAuth:ho,ignoreIfIsEmbeddedWidget:go,initializeWalletConnect:yo,performMultiWalletChecks:vo,clearErrors:wo}=Object.assign({clearErrors:!0,emitCancelAuth:!1,ignoreIfIsEmbeddedWidget:!0,initializeWalletConnect:!0,performMultiWalletChecks:!1},lo);if(logger$8.logVerboseTroubleshootingMessage("setShowAuthFlow",{clearErrors:wo,emitCancelAuth:ho,ignoreIfIsEmbeddedWidget:go,initializeWalletConnect:yo,performMultiWalletChecks:vo}),!io&&co?dynamicEvents.emit("authFlowOpen"):io&&!co&&dynamicEvents.emit("authFlowClose"),co){if(go&&eo.current)return;if(vo&&Xr){if(!to)return no(!0);logger$8.warn("Use setShowLinkNewWalletModal to render the wallet list instead. For more information, see: https://docs.dynamic.xyz/react-sdk/hooks/usedynamiccontext");return}yo&&((fo=ro.find(Eo=>Eo.walletConnector.key==="walletconnect"))===null||fo===void 0||fo.walletConnector.init())}else ho&&io&&dynamicEvents.emit("authFlowCancelled");wo&&ao(void 0),oo(co)},[Xr,to,eo,ao,no,io,ro]);return[io,so]},usePasskeySuccessPopup=()=>{const[Xr,eo]=reactExports.useState(void 0);return{passkeySuccessPopup:Xr,setPasskeySuccessPopup:ro=>{eo(ro),setTimeout(()=>{eo(void 0)},2e3)}}},useTieCallbacksToEvents=({clientCallbacks:Xr,user:eo})=>{useInternalDynamicEvents("emailVerificationResult",(to,ro)=>{var no;return(no=Xr==null?void 0:Xr.onOtpVerificationResult)===null||no===void 0?void 0:no.call(Xr,to,{type:"email",value:ro})}),useInternalDynamicEvents("smsVerificationResult",(to,ro)=>{var no;return(no=Xr==null?void 0:Xr.onOtpVerificationResult)===null||no===void 0?void 0:no.call(Xr,to,{type:"sms",value:ro})}),useInternalDynamicEvents("authFlowCancelled",()=>{var to;return(to=Xr==null?void 0:Xr.onAuthFlowCancel)===null||to===void 0?void 0:to.call(Xr)}),useInternalDynamicEvents("authFlowOpen",()=>{var to;(to=Xr==null?void 0:Xr.onAuthFlowOpen)===null||to===void 0||to.call(Xr)}),useInternalDynamicEvents("authFlowClose",()=>{var to;(to=Xr==null?void 0:Xr.onAuthFlowClose)===null||to===void 0||to.call(Xr)}),useInternalDynamicEvents("walletAdded",(to,ro)=>{var no;dynamicEvents.emit("triggerSessionValidation"),logger$8.debug("[walletAdded]",{userWallets:ro,wallet:to}),(no=Xr==null?void 0:Xr.onWalletAdded)===null||no===void 0||no.call(Xr,{userWallets:ro,wallet:to})}),useInternalDynamicEvents("walletRemoved",(to,ro)=>{var no;logger$8.debug("[walletRemoved]",{userWallets:ro,wallet:to}),(no=Xr==null?void 0:Xr.onWalletRemoved)===null||no===void 0||no.call(Xr,{userWallets:ro,wallet:to})}),useInternalDynamicEvents("embeddedWalletCreated",(to,ro,no)=>{var io;logger$8.debug("[embeddedWalletCreated]",{_wallet:to,jwtVerifiedCredential:ro,user:no}),(io=Xr==null?void 0:Xr.onEmbeddedWalletCreated)===null||io===void 0||io.call(Xr,ro,no)}),useInternalDynamicEvents("logout",()=>{var to;(to=Xr==null?void 0:Xr.onLogout)===null||to===void 0||to.call(Xr,eo)}),useInternalDynamicEvents("authFailure",(to,ro)=>{var no;logger$8.debug("[authFailure]",{data:to,reason:ro}),(no=Xr==null?void 0:Xr.onAuthFailure)===null||no===void 0||no.call(Xr,to,ro)}),useInternalDynamicEvents("authInit",to=>{var ro;logger$8.debug("[authInit]",{data:to}),(ro=Xr==null?void 0:Xr.onAuthInit)===null||ro===void 0||ro.call(Xr,to)})},useMultiWallet=({isBridgeFlow:Xr,multiWalletOverride:eo,multiWalletSettings:to})=>{var ro;return eo!==void 0?eo:(ro=to||Xr)!==null&&ro!==void 0?ro:!1},useMultiAsset=({multiAssetOverride:Xr,multiAssetSettings:eo})=>Xr!==void 0?Xr:eo??!0,useParentDynamicContextGuard=()=>{if(reactExports.useContext(DynamicContext))throw new Error("DynamicContextProvider should not be nested. Please wrap your application in a single DynamicContextProvider.")},useShowFiat=({showFiatOverride:Xr,showFiatSettings:eo})=>Xr!==void 0?Xr:eo??!0,isAuthenticatedWithAWallet=Xr=>{const eo=Xr.verifiedCredentials.find(to=>to.id===Xr.lastVerifiedCredentialId);return(eo==null?void 0:eo.format)===JwtVerifiedCredentialFormatEnum.Blockchain},useCustomerCallbacks=({callbacks:{onAuthSuccess:Xr,onUserProfileUpdate:eo},handleLogOut:to,primaryWallet:ro,user:no,isAuthenticated:io})=>{const[oo,ao]=reactExports.useState([]),so=reactExports.useCallback((lo,fo)=>{switch(lo==null?void 0:lo.callback){case"authSuccess":{try{Xr==null||Xr({handleLogOut:to,isAuthenticated:io,primaryWallet:ro,user:fo}),dynamicEvents.emit("triggerSessionValidation")}catch(ho){logger$8.error("Error calling onAuthSuccess: ",ho)}break}case"userProfileUpdate":{try{eo==null||eo(fo)}catch(ho){logger$8.error("Error calling userProfileUpdate: ",ho)}break}}},[to,io,Xr,eo,ro]);return reactExports.useEffect(()=>{!oo.length||!no||isAuthenticatedWithAWallet(no)&&!ro||(so(oo[0],no),ao(lo=>{const[fo,...ho]=lo;return fo&&(logger$8.debug("Resolved callback: ",fo.callback),logger$8.debug("Callbacks in queue: ",ho.map(go=>go.callback))),ho}))},[oo,so,ro,no]),{setCallback:reactExports.useCallback((lo,fo)=>{ao(ho=>[...ho,{callback:lo,params:fo}])},[])}},useRegisterStorageService=({storagePostfix:Xr})=>{const eo={clear:()=>{},getItem:()=>null,key:()=>null,length:0,removeItem:()=>{},setItem:()=>null},to=isSSR()?eo:window.localStorage,ro=isSSR()?eo:window.sessionStorage;StorageService.getSourceStorage("localStorage")||StorageService.registerSourceStorage("localStorage",createStorageService({postfix:Xr,storage:to})),StorageService.getSourceStorage("sessionStorage")||StorageService.registerSourceStorage("sessionStorage",createStorageService({postfix:Xr,storage:ro}))};var define_process_env_default$5={};const PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID="2762a57b-faa4-41ce-9f16-abff9300e2c9",DynamicContext=reactExports.createContext(void 0),InnerDynamicContextProvider=({children:Xr,theme:eo,settings:to,locale:ro,enableInstrumentation:no=!1})=>{var io,oo,ao,so,co,lo,fo,ho,go,yo,vo,wo,Eo,ko;const{accessDeniedMessagePrimary:Ao,accessDeniedMessageSecondary:Po,accessDeniedButton:jo,defaultPhoneInputIso2:Mo,apiBaseUrl:No,coinbaseWalletPreference:Do,detectNewWalletsForLinking:Fo=!1,enableConnectOnlyFallback:Xo=!1,deepLinkPreference:Lo="native",bridgeChains:Bo,cssOverrides:xo,defaultNumberOfWalletsToShow:uo=DEFAULT_NUMBER_OF_WALLETS_TO_SHOW,flowNetwork:po,initialAuthenticationMode:bo="connect-and-sign",debugError:_o=!1,displaySiweStatement:$o=!0,newToWeb3WalletChainMap:Co,enableVisitTrackingOnConnectOnly:Ro=!0,environmentId:So,walletsFilter:mo,logLevel:To="WARN",mobileExperience:Vo,notInTheListImageUrl:Zo,onboardingImageUrl:Qo,policiesConsentInnerComponent:qo,customPrivacyPolicy:Ho,privacyPolicyUrl:$a,socialMediaLinkText:zo,socialMediaIconUrl:Ko,socialMediaUrl:_c,customTermsOfServices:Cl,termsOfServiceUrl:ga,toolkitEnabled:El,siweStatement:Al,shadowDOMEnabled:Ol=!0,walletConnectors:Wl,socialProvidersFilter:zl,showLockedWalletView:Tl=!1,walletConnectPreferredChains:Ml,walletConnectorExtensions:ou,recommendedWallets:Vl,handlers:Ll}=to;useRegisterStorageService({storagePostfix:to.localStorageSuffix}),initializeStore({environmentId:So,storageSuffix:to.localStorageSuffix}),setChainInfoOverrides((io=to.overrides)===null||io===void 0?void 0:io.chainDisplayValues);const uu=(oo=to.events)!==null&&oo!==void 0?oo:to.eventsCallbacks,ru=resolveNetworkValidationMode({bridgeChains:to.bridgeChains,networkValidationMode:to.networkValidationMode});let{appLogoUrl:tu="https://demo.dynamic.xyz/assets/dynamic-logo.svg",appName:ku="Dynamic Example"}=to;if(!So)throw new MissingEnvironmentIdError;logger$8.setLogLevel(To),logger$9.setLogLevel(To),So===PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID&&logger$8.warn(`WARNING: DYNAMIC is using a test environment ID ${So}. Please sign up on https://app.dynamic.xyz/ to get your production environment ID.`),ApiEndpoint$1.setBaseUrl((ao=define_process_env_default$5.DYNAMIC_API_BASE_URL)!==null&&ao!==void 0?ao:No);const au=Locale.setup(ro),wl=!!Bo,Jo=getDeepLinkPreference(Lo,wl),{selectedTabIndex:Go,setSelectedTabIndex:$l,selectedTabSettings:Zl,tabsItems:Ul}=useTabState({settingsOverrides:to.overrides}),[Gl,Nu,hu]=useLocalStorage(BRIDGE_ONBOARDING_COMPLETED,!1),[cu,Wu]=reactExports.useState(!1),[mu,yu]=reactExports.useState(!1),[Yu,_u]=reactExports.useState(!1),{user:Il,userWithMissingInfo:Nl}=useUser(),Pl=!!Il;Il?logger$8.setMetaData("user",Il):logger$8.setMetaData("user",void 0);const{consumeNonce:Bl}=useFetchNonce(So),[fu,eu]=reactExports.useState(""),[Xl,$u]=reactExports.useState(""),[Yo,_l,{awaiting_account_switch:[Sl],awaiting_signature:[Wo]}]=useMultiWalletWidgetState(),{settings:xl}=useProjectSettings(),Ql=useNetworkConfigurationsFromProjectSettings({cosmosNetworkOverrides:(so=to.overrides)===null||so===void 0?void 0:so.cosmosNetworks,evmNetworksOverrides:(co=to.overrides)===null||co===void 0?void 0:co.evmNetworks,projectSettings:xl});useSendDynamicProps({environmentId:So,settings:to});const Fl=useMultiWallet({isBridgeFlow:wl,multiWalletOverride:(lo=to.overrides)===null||lo===void 0?void 0:lo.multiWallet,multiWalletSettings:(fo=xl==null?void 0:xl.sdk)===null||fo===void 0?void 0:fo.multiWallet}),Jl=useMultiAsset({multiAssetOverride:(ho=to.overrides)===null||ho===void 0?void 0:ho.multiAsset,multiAssetSettings:(go=xl==null?void 0:xl.sdk)===null||go===void 0?void 0:go.enableMultiAsset}),xu=useShowFiat({showFiatOverride:(yo=to.overrides)===null||yo===void 0?void 0:yo.showFiat,showFiatSettings:(vo=xl==null?void 0:xl.sdk)===null||vo===void 0?void 0:vo.showFiat}),[lu,su]=reactExports.useState(!1),Xu=useWalletBookCdn(),{imageUserInAccessList:ju,imageUserNotInAccessList:zu,displayName:Ku,appLogo:Hu}=(xl==null?void 0:xl.general)||{};tu=Hu||tu,ku=Ku||ku;const[Gu,Zu,Vu]=useEmailLoginState((xl==null?void 0:xl.providers)||[],Il),[Ju,Uu]=useDisplayOrderState(xl),[qu,Mu]=useWalletUiUtils({appLogoUrl:tu,appName:ku,hideEmbeddedWalletTransactionUIs:!(!((Eo=(wo=xl==null?void 0:xl.sdk)===null||wo===void 0?void 0:wo.embeddedWallets)===null||Eo===void 0)&&Eo.showEmbeddedWalletActionsUI)});useCreateWalletConnectorOptions({appLogoUrl:tu,appName:ku,coinbaseWalletPreference:Do,deepLinkPreference:Jo,flowNetwork:po,mobileExperience:Vo,networkConfigurations:Ql,projectSettings:xl,walletBook:Xu,walletConnectPreferredChains:Ml,walletConnectorExtensions:ou,walletConnectorsProp:Wl,walletUiUtils:Mu});const Bu=useWalletConnectorOptions(),[Au,Du]=useLocalStorage(AUTH_MODE,bo),{clearPrimaryWalletId:wu,primaryWalletId:vu,setPrimaryWalletId:Cu}=usePrimaryWalletId({environmentId:So,user:Il}),[Eu,Ru]=reactExports.useState(!1),Lu=!!(Au==="connect-and-sign"?Il:Eu),ep=reactExports.useRef(!1),[rp,ip]=useShowAuthFlow({isAuthenticated:Lu,isMultiWalletEnabled:Fl,isRenderingEmbeddedAuthFlow:ep,setShowDynamicUserProfile:Wu,walletConnectorOptions:Bu}),{connectWallet:np,removeConnectedWalletsInfo:nu,connectedWalletsInfo:lp,getConnectedWalletById:yp,connectedWallets:up,disconnectWallet:op,refreshConnectedWallet:bp}=useConnectWallet({authMode:Au,clearPrimaryWalletId:wu,enableVisitTrackingOnConnectOnly:Ro,environmentId:So,handleConnectedWallet:Ll==null?void 0:Ll.handleConnectedWallet,isBridgeFlow:wl,primaryWalletId:vu,setPrimaryWalletId:Cu,setShowAuthFlow:ip,user:Il,walletConnectorOptions:Bu}),dp=reactExports.useMemo(()=>getMissingChains(Bo,lp),[Bo,lp]),{selectedWalletConnector:Ep,setSelectedWalletConnectorKey:pp}=useSelectedWalletConnector({walletConnectorOptions:Bu}),[wp,Ap]=reactExports.useState(null);useSetWalletConnectorVerifiedCredentials(Il??Nl,Bu),useSetWalletConnectorFetchers(Bu,So);const{primaryWallet:fp,showQrcodeModal:Tp,secondaryWallets:Lp,setPrimaryWallet:zp,setShowQrcodeModal:Hp,wallets:r0}=useWalletConnectors({authMode:Au,canHaveMultipleWalletsConnected:Fl,connectedWallets:up,primaryWalletId:vu,setMultiWalletWidgetState:_l,setPrimaryWalletId:Cu,user:Il||Nl,walletConnectorOptions:Bu});reactExports.useEffect(()=>{Ru(!(dp!=null&&dp.length)&&!!fp)},[dp,fp]);const p0=r0.map(Tu=>Tu.connector);useFetchProjectSettings({environmentId:So});const{getNameService:Em,removeConnectedNameService:A0}=useNameService({currentWallet:fp??up[0],user:Il}),{clearAllWalletConnectSessions:n0}=useClearWalletConnectSessions({connectors:p0}),Pm=useHandleLogout({bridgeChains:Bo,clearAllWalletConnectSessions:n0,clearPrimaryWalletId:wu,connectedWallets:up,environmentId:So,events:uu,initialAuthenticationMode:bo,removeBridgeOnboardingCompleted:hu,removeConnectedNameService:A0,removeConnectedWalletsInfo:nu,removeSessionStorageSessionKeys:()=>{StorageService.removeItem(SECURE_ENCLAVE_WALLET_SESSION_KEYS,SECURE_ENCLAVE_WALLET_SESSION_KEYS_STORAGE_OPTIONS),p0.forEach(Tu=>{isSessionKeyCompatibleWalletConnector(Tu)&&typeof(Tu==null?void 0:Tu.removeSessionKeys)=="function"&&(Tu==null||Tu.removeSessionKeys())})},resetLoginWithEmail:Vu,setAuthMode:Du,setLegacyIsVerifying:su,setMultiWalletWidgetState:_l,setSelectedWalletConnectorKey:pp,setShowAuthFlow:ip,setShowBridgeWidget:yu,setShowDynamicUserProfile:Wu,user:Il,walletConnectors:p0});useValidateSession({environmentId:So,handleLogOut:Pm});const{isLoading:g0}=useResetCookieLocalStorage({environmentId:So,projectSettings:xl,setPrimaryWalletId:Cu}),P0=useGlobalLoading({appName:ku,authMode:Au,connectedInfo:lp[0],connectedWallets:up,enableInstrumentation:no,environmentId:So,isLoadingUserFromCookie:g0,primaryWallet:fp,primaryWalletId:vu,projectSettings:xl,user:Il??Nl,walletBook:Xu});useTieCallbacksToEvents({clientCallbacks:uu,user:Il});const Vm=useHandleUnlinkWallet({environmentId:So,primaryWalletId:vu,secondaryWallets:Lp,verifiedCredentials:(Il==null?void 0:Il.verifiedCredentials)||[]}),{isLoading:y0,network:v0}=useWalletConnectorNetwork(fp==null?void 0:fp.connector);useWalletEventListeners({authMode:Au,detectNewWalletsForLinking:Fo,disconnectWallet:op,handleLogOut:Pm,multiWallet:Fl,multiWalletWidgetState:Yo,primaryWallet:fp,refreshConnectedWallet:bp,secondaryWallets:Lp,selectedWalletConnector:Ep,selectedWalletWithAction:wp,setMultiWalletWidgetState:_l,setPrimaryWalletId:Cu,setSelectedWalletConnectorKey:pp,setSelectedWalletWithAction:Ap,user:Il});const{walletsForChainsMap:Um}=useFetchWalletsForChainsMap(Co);reactExports.useEffect(()=>{initExpirationTime(Pm)},[Pm,Pl]);const{setCallback:b0}=useCustomerCallbacks({callbacks:{onAuthSuccess:uu==null?void 0:uu.onAuthSuccess,onUserProfileUpdate:uu==null?void 0:uu.onUserProfileUpdate},handleLogOut:Pm,isAuthenticated:Pl,primaryWallet:fp,user:Il}),O0=reactExports.useCallback(()=>Tu=>{const{dynamicWagmiSettings:_f}=Tu;_f&&sendDynamicProps(So,{dynamicWagmiSettings:{dynamicWagmiSettings:_f}})},[So]),Pp=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){$u(""),su(!1),Il||n0(),_l("idle"),Au!=="connect-only"&&nu(),StorageService.getItem(WALLET_PICKER_SEARCH_KEY)&&StorageService.removeItem(WALLET_PICKER_SEARCH_KEY),StorageService.removeItem(PHANTOM_SIGNATURE_STATE),Ep&&(!fp||fp.connector.key!==Ep.key)&&(yield Ep==null?void 0:Ep.endSession())}),[Il,_l,Au,Ep,fp,n0,nu]),{passkeySuccessPopup:Ip,setPasskeySuccessPopup:Yl}=usePasskeySuccessPopup(),pu=reactExports.useMemo(()=>{var Tu;return{accessDeniedButton:jo,accessDeniedMessagePrimary:Ao,accessDeniedMessageSecondary:Po,accountSwitchState:Sl,appLogoUrl:tu,appName:ku,authMode:Au,authToken:getAuthToken(),authorizationViewDisplayOrder:Ju,awaitingSignatureState:Wo,bridgeChains:Bo,bridgeChainsToConnect:dp,bridgeOnboardingCompleted:Gl,clearStatesOnBackClick:Pp,connectWallet:np,connectedWallets:up,consumeNonce:Bl,cssOverrides:xo,customPrivacyPolicy:Ho,customTermsOfServices:Cl,debugError:_o,defaultNumberOfWalletsToShow:uo,defaultPhoneInputIso2:Mo,desktopUri:Xl,detectNewWalletsForLinking:Fo,disconnectWallet:op,displaySiweStatement:$o,enableConnectOnlyFallback:Xo,environmentId:So,events:uu,getConnectedWalletById:yp,getNameService:Em,handleLogOut:Pm,handleUnlinkWallet:Au==="connect-only"?op:Vm,handlers:Ll,i18nSDKInstance:au,isBridgeFlow:wl,isRenderingEmbeddedAuthFlow:ep,isSingleWalletAccount:Yu,legacyIsVerifying:lu,linkedWallets:Au==="connect-only"||!Il?[]:r0,loadingNetwork:y0,locale:{changeLanguage:Locale.getInstance().changeLanguage},loginWithEmail:Gu,minAuthToken:getMinAuthToken$1(),multiAsset:Jl,multiWallet:Fl,multiWalletWidgetState:Yo,network:v0,networkConfigurations:Ql,networkValidationMode:ru,newToWeb3WalletChainMap:Um,notInTheListImageUrl:zu||Zo,onboardingImageUrl:ju||Qo,overrides:to.overrides,passkeySuccessPopup:Ip,policiesConsentInnerComponent:qo,primaryWallet:fp,primaryWalletId:vu,privacyPolicyUrl:$a,projectSettings:xl,qrcodeUri:fu,recommendedWallets:Vl,redirectUrl:to.redirectUrl,removeBridgeOnboardingCompleted:hu,removeConnectedWalletsInfo:nu,sdkHasLoaded:P0,secondaryWallets:Lp,selectedTabIndex:Go,selectedTabSettings:Zl,selectedWalletConnector:Ep,selectedWalletWithAction:wp,sendWagmiSettings:O0,setAuthMode:Du,setAuthorizationViewDisplayOrder:Uu,setBridgeOnboardingCompleted:Nu,setCallback:b0,setDesktopUri:$u,setIsSingleWalletAccount:_u,setLegacyIsVerifying:su,setLogInWithEmail:Zu,setMultiWalletWidgetState:_l,setPasskeySuccessPopup:Yl,setPrimaryWallet:zp,setPrimaryWalletId:Cu,setQrcodeUri:eu,setSelectedTabIndex:$l,setSelectedWalletConnectorKey:pp,setSelectedWalletWithAction:Ap,setShowAuthFlow:ip,setShowBridgeWidget:yu,setShowDynamicUserProfile:Wu,setShowQrcodeModal:Hp,shadowDOMEnabled:Ol,showAuthFlow:rp,showBridgeWidget:mu,showDynamicUserProfile:cu,showFiat:xu,showLockedWalletView:Tl,showQrcodeModal:Tp,siweStatement:Al,socialMediaIconUrl:((Tu=xl==null?void 0:xl.general)===null||Tu===void 0?void 0:Tu.supportUrls)||Ko,socialMediaLinkText:zo,socialMediaUrl:_c,socialProvidersFilter:zl,socialSettings:to.social,tabsItems:Ul,termsOfServiceUrl:ga,theme:eo,toolkitEnabled:El,user:Il,userWithMissingInfo:Nl,walletConnectorOptions:Bu,walletUiUtils:Mu,walletsFilter:mo}},[jo,Ao,Po,Sl,tu,ku,Au,Ju,Wo,Bo,dp,Gl,Pp,np,up,Bl,xo,Ho,Cl,_o,uo,Mo,Xl,Fo,op,$o,Xo,So,uu,yp,Em,Pm,Vm,Ll,au,wl,Yu,lu,Il,r0,y0,Gu,Jl,Fl,Yo,v0,Ql,ru,Um,zu,Zo,ju,Qo,to.overrides,to.redirectUrl,to.social,Ip,qo,fp,vu,$a,xl,fu,Vl,hu,nu,P0,Lp,Go,Zl,Ep,wp,O0,Du,Uu,Nu,b0,Zu,_l,Yl,zp,Cu,$l,pp,ip,Hp,Ol,rp,mu,cu,xu,Tl,Tp,Al,Ko,zo,_c,zl,Ul,ga,eo,El,Nl,Bu,Mu,mo]);return usePrefetch({as:"image",href:getIconicSpriteUrl$1(),id:"sprite",type:"image/svg+xml"}),usePrefetch({as:"fetch",href:getWalletBookCdnUrl(),id:"wallet-book",type:"application/json"}),usePrefetch({as:"fetch",href:`${ApiEndpoint$1.getBaseUrl()}/sdk/${So}/settings?sdkVersion=${encodeURIComponent(`WalletKit/${VERSION$4}`)}`,id:`project-settings-${So}`,type:"application/json"}),reactExports.useEffect(()=>{!Fl&&Yo!=="awaiting_account_switch"||Il&&Yo!=="idle"&&!cu&&Wu(!0)},[Fl,Yo,cu]),jsxRuntimeExports.jsx(I18nextProvider,{i18n:au,children:jsxRuntimeExports.jsx(DynamicContext.Provider,{value:pu,children:jsxRuntimeExports.jsx(WalletBookContextProvider,{walletBook:Xu,children:jsxRuntimeExports.jsx(ThemeContextProvider,{customerTheme:parseTheme(eo,((ko=xl==null?void 0:xl.design)===null||ko===void 0?void 0:ko.modal)||void 0),designSettings:xl==null?void 0:xl.design,children:jsxRuntimeExports.jsx(LoadingContextProvider,{children:jsxRuntimeExports.jsxs(ViewContextProvider,{initialView:getInitialView({bridgeOnboardingCompleted:Gl,connectedWallets:up,isAuthenticated:Pl||!!fp,isBridgeFlow:wl,isMultiWalletEnabled:Fl}),children:[ru==="always"&&jsxRuntimeExports.jsx(UseNetworkValidation,{}),jsxRuntimeExports.jsx(CaptchaContextProvider,{children:jsxRuntimeExports.jsx(AccountExistsContextProvider,{children:jsxRuntimeExports.jsx(WalletContextProvider,{children:jsxRuntimeExports.jsx(VerificationProvider,{children:jsxRuntimeExports.jsx(PasskeyContextProvider,{children:jsxRuntimeExports.jsx(DynamicWidgetContextProvider,{children:jsxRuntimeExports.jsx(DynamicBridgeWidgetContextProvider,{children:jsxRuntimeExports.jsx(FundingContextProvider,{children:jsxRuntimeExports.jsx(AccessDeniedContextProvider,{children:jsxRuntimeExports.jsx(SendBalanceContextProvider,{children:jsxRuntimeExports.jsx(WalletGroupContextProvider,{children:jsxRuntimeExports.jsx(UserFieldEditorContextProvider,{children:jsxRuntimeExports.jsx(ConnectWithOtpProvider,{children:jsxRuntimeExports.jsx(PhantomRedirectContextProvider,{children:jsxRuntimeExports.jsxs(SocialRedirectContextProvider,{children:[jsxRuntimeExports.jsx(DynamicAuthFlow,{}),jsxRuntimeExports.jsx(Toolkit,{}),jsxRuntimeExports.jsx(FundingWidget,{}),jsxRuntimeExports.jsx(SyncAuthFlow,{}),jsxRuntimeExports.jsx(TelegramAutoLogin,{}),jsxRuntimeExports.jsx(WalletConnectorEvents,{}),qu,jsxRuntimeExports.jsx(ErrorBoundaryExclude,{children:Xr})]})})})})})})})})})})})})})})})]})})})})})})},DynamicContextProvider=Xr=>(Logger$2.setEnvironmentId(Xr.settings.environmentId),Logger$2.setEmitErrors(Xr.emitErrors),useParentDynamicContextGuard(),jsxRuntimeExports.jsx(ReinitializeContextProvider,{onReinitialize:removeStoreInstance,children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(ErrorContextProvider,{children:jsxRuntimeExports.jsx(UserWalletsProvider,{children:jsxRuntimeExports.jsx(FieldsStateProvider,{children:jsxRuntimeExports.jsx(IpConfigurationContextProvider,{children:jsxRuntimeExports.jsx(WidgetRegistryContextProvider,{children:jsxRuntimeExports.jsx(InnerDynamicContextProvider,Object.assign({},Xr))})})})})})})}));assertPackageVersion("@dynamic-labs/sdk-react-core",version$u);function Signup(){const[Xr,eo]=reactExports.useState(1),[to,ro]=reactExports.useState(!1),[no,io]=reactExports.useState(null),[oo,ao]=reactExports.useState([]),[so,co]=reactExports.useState(Array(12).fill("")),{setShowAuthFlow:lo,primaryWallet:fo,handleLogOut:ho}=useDynamicContext(),[go,yo]=reactExports.useState(null),{dispatch:vo}=useGlobalState(),wo=useNavigate();reactExports.useEffect(()=>{if(no!=null&&no.mnemonic){const Do=no.mnemonic.split(" ");co(Do)}},[no]);const Eo=()=>eo(Xr+1),ko=async()=>{if(no){ro(!0);try{await no.registerPushAccount(),vo({type:"INITIALIZE_WALLET",payload:no}),wo("/")}catch(Do){alert(Do)}ro(!1)}},Ao=async()=>{try{const Do=await PushWallet.signUp(config$3.APP_ENV);io(Do),ao(Object.keys(Do.walletToEncDerivedKey))}catch(Do){alert(Do)}},Po=async()=>{const Do=await PushSigner.initialize(fo,"DYNAMIC");await(no==null?void 0:no.connectWalletWithAccount(Do)),ao(Object.keys(no.walletToEncDerivedKey))},jo=()=>jsxRuntimeExports.jsxs("div",{className:"space-y-4 text-center",children:[jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx("button",{onClick:async()=>{yo("mnemonic"),await Ao()},className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64 mx-10",children:"Using Mnemonic"})}),jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsxs("button",{onClick:()=>yo("social"),className:"border border-blue-600 text-blue-600 px-6 py-1 rounded-lg w-64",disabled:!0,children:["Social Signup ",jsxRuntimeExports.jsx("br",{})," Coming Soon 🚀"]})})]}),Mo=()=>{const Do=()=>{const Fo=so.join(" ");navigator.clipboard.writeText(Fo).then(()=>alert("Copied to clipboard")).catch(()=>alert("Failed to copy"))};return jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl mb-6",children:"Store Seed Phrase Safely"}),jsxRuntimeExports.jsx(MnemonicGrid,{words:so,disabled:!0}),jsxRuntimeExports.jsx("button",{className:"border border-blue-600 text-blue-600 px-4 py-2 rounded-lg w-30",onClick:Do,children:"Copy"}),jsxRuntimeExports.jsx("p",{className:"mb-6 mt-20 text-gray-600",children:"Your wallet needs to be registered on the Push network to be able to send transactions on the network."}),jsxRuntimeExports.jsx("button",{className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-40",onClick:Eo,children:"Next"})]})},No=()=>jsxRuntimeExports.jsxs("div",{className:"text-center space-y-6 mt-6",children:[jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center space-y-4",children:fo?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("button",{className:"border border-blue-600 text-blue-600 px-6 py-3 rounded-md",onClick:()=>{ho()},children:["Disconnect ",jsxRuntimeExports.jsx("b",{children:fo.address})]}),jsxRuntimeExports.jsx("button",{className:"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",onClick:Po,children:"Add to Push Account"})]}):jsxRuntimeExports.jsx("button",{className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",onClick:()=>lo(!0),children:"Connect Web3 Account"})}),jsxRuntimeExports.jsx("button",{disabled:to,onClick:ko,className:to?"w-full py-3 bg-grey flex items-center justify-center":"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",children:to?"Registering":jsxRuntimeExports.jsxs("span",{className:"flex items-center",children:[jsxRuntimeExports.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"})}),"Register Push Account"]})})]});return jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"p-8 w-full max-w-4xl",children:[Xr===1&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[!go&&jo(),go==="mnemonic"&&Mo()]}),Xr===2&&jsxRuntimeExports.jsx("div",{className:"space-y-2 text-center",children:oo.map(Do=>jsxRuntimeExports.jsx("div",{className:"inline-flex items-center bg-blue-100 text-blue-800 text-sm font-medium rounded-full px-4 py-2 border border-blue-300",children:jsxRuntimeExports.jsx("span",{className:"font-mono",children:Do})},Do))}),Xr===2&&No()]})})}function Login(){const[Xr,eo]=reactExports.useState(null),[to,ro]=reactExports.useState(Array(12).fill("")),{setShowAuthFlow:no,primaryWallet:io,handleLogOut:oo}=useDynamicContext(),{dispatch:ao}=useGlobalState(),so=useNavigate(),co=(yo,vo)=>{const wo=[...to];wo[yo]=vo,ro(wo)},lo=async()=>{try{let yo;switch(Xr){case"mnemonic":{yo=await PushWallet.logInWithMnemonic(to.join(" "),config$3.APP_ENV);break}case"wallet":{const vo=await PushSigner.initialize(io,"DYNAMIC");yo=await PushWallet.loginWithWallet(vo,config$3.APP_ENV);break}}ao({type:"INITIALIZE_WALLET",payload:yo}),so("/")}catch(yo){alert(yo)}},fo=()=>jsxRuntimeExports.jsxs("div",{className:"space-y-4 text-center",children:[jsxRuntimeExports.jsx("button",{onClick:()=>eo("mnemonic"),className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",children:"Using Mnemonic"}),jsxRuntimeExports.jsx("button",{onClick:()=>eo("wallet"),className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",children:"Using Web3 Account"}),jsxRuntimeExports.jsxs("button",{onClick:()=>eo("social"),className:"border border-blue-600 text-blue-600 px-6 py-1 rounded-lg w-64",disabled:!0,children:["Social Login ",jsxRuntimeExports.jsx("br",{})," Coming Soon 🚀"]})]}),ho=()=>jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(MnemonicGrid,{words:to,disabled:!1,handleMnemonicChange:co}),jsxRuntimeExports.jsxs("button",{onClick:lo,disabled:to.some(yo=>yo===""),className:"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",children:[jsxRuntimeExports.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"})}),"Unlock Push Account"]})]}),go=()=>jsxRuntimeExports.jsxs("div",{className:"text-center space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center space-y-4",children:io?jsxRuntimeExports.jsxs("button",{className:"border border-blue-600 text-blue-600 px-6 py-1 rounded-md",onClick:()=>{oo()},children:["Disconnect ",io.address]}):jsxRuntimeExports.jsx("button",{className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",onClick:()=>no(!0),children:"Connect Web3 Account"})}),jsxRuntimeExports.jsxs("button",{onClick:lo,disabled:!io,className:"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",children:[jsxRuntimeExports.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"})}),"Unlock Push Account"]})]});return jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"p-8 w-full max-w-lg",children:[!Xr&&fo(),Xr==="mnemonic"&&ho(),Xr==="wallet"&&go()]})})}const __vite_import_meta_env__={BASE_URL:"/push-wallet/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_DYNAMIC_ENV_ID:"7a6006b6-fa19-4e7a-abcf-34add623dff5",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"};var define_process_env_default$4={};function getAppBasePath(){if(typeof import.meta<"u"&&__vite_import_meta_env__)return"/push-wallet/";if(typeof process$1$1<"u"&&define_process_env_default$4){if(define_process_env_default$4.VITE_DEV_MODE==="preview")return"/push-wallet/pr-preview/";if(define_process_env_default$4.VITE_DEV_MODE==="testing")return"/push-wallet/"}return"/"}function App(){return jsxRuntimeExports.jsx(GlobalProvider,{children:jsxRuntimeExports.jsxs("div",{className:"min-h-screen flex flex-col",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold mt-8 text-center",children:config$3.APP_NAME}),jsxRuntimeExports.jsx("div",{className:"flex-1 flex items-center justify-center",children:jsxRuntimeExports.jsx(BrowserRouter,{basename:getAppBasePath(),children:jsxRuntimeExports.jsxs(Routes,{children:[jsxRuntimeExports.jsx(Route,{path:"/",element:jsxRuntimeExports.jsx(Home,{})}),jsxRuntimeExports.jsx(Route,{path:"login",element:jsxRuntimeExports.jsx(Login,{})}),jsxRuntimeExports.jsx(Route,{path:"signup",element:jsxRuntimeExports.jsx(Signup,{})}),jsxRuntimeExports.jsx(Route,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"/"})})]})})})]})})}var version$j="3.4.4";function __awaiter$i(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,freeSelf=typeof self=="object"&&self&&self.Object===Object&&self,root$1=freeGlobal||freeSelf||Function("return this")();function getValue$1(Xr,eo){return Xr==null?void 0:Xr[eo]}function isHostObject(Xr){var eo=!1;if(Xr!=null&&typeof Xr.toString!="function")try{eo=!!(Xr+"")}catch{}return eo}var funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root$1["__core-js_shared__"],maskSrcKey=function(){var Xr=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return Xr?"Symbol(src)_1."+Xr:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString$1=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol$1=root$1.Symbol;Symbol$1&&Symbol$1.isConcatSpreadable;getNative(root$1,"Map");getNative(Object,"create");function baseIsNative(Xr){if(!isObject$8(Xr)||isMasked(Xr))return!1;var eo=isFunction(Xr)||isHostObject(Xr)?reIsNative:reIsHostCtor;return eo.test(toSource(Xr))}function getNative(Xr,eo){var to=getValue$1(Xr,eo);return baseIsNative(to)?to:void 0}function isMasked(Xr){return!!maskSrcKey&&maskSrcKey in Xr}function toSource(Xr){if(Xr!=null){try{return funcToString.call(Xr)}catch{}try{return Xr+""}catch{}}return""}function isFunction(Xr){var eo=isObject$8(Xr)?objectToString$1.call(Xr):"";return eo==funcTag||eo==genTag}function isObject$8(Xr){var eo=typeof Xr;return!!Xr&&(eo=="object"||eo=="function")}var store2;function getGlobalMessage(Xr){return store2==null?void 0:store2.get(Xr)}var store3;function getSchemaMessage(Xr){return store3==null?void 0:store3.get(Xr)}var store4;function getSpecificMessage(Xr,eo){var to;return(to=store4==null?void 0:store4.get(Xr))==null?void 0:to.get(eo)}function _stringify(Xr){var to,ro;let eo=typeof Xr;return eo==="object"&&(eo=(Xr&&((ro=(to=Object.getPrototypeOf(Xr))==null?void 0:to.constructor)==null?void 0:ro.name))??"null"),eo==="string"?`"${Xr}"`:eo==="number"||eo==="bigint"||eo==="boolean"?`${Xr}`:eo}function _addIssue(Xr,eo,to,ro,no){const io=no&&"input"in no?no.input:to.value,oo=(no==null?void 0:no.expected)??Xr.expects??null,ao=(no==null?void 0:no.received)??_stringify(io),so={kind:Xr.kind,type:Xr.type,input:io,expected:oo,received:ao,message:`Invalid ${eo}: ${oo?`Expected ${oo} but r`:"R"}eceived ${ao}`,requirement:Xr.requirement,path:no==null?void 0:no.path,issues:no==null?void 0:no.issues,lang:ro.lang,abortEarly:ro.abortEarly,abortPipeEarly:ro.abortPipeEarly},co=Xr.kind==="schema",lo=(no==null?void 0:no.message)??Xr.message??getSpecificMessage(Xr.reference,so.lang)??(co?getSchemaMessage(so.lang):null)??ro.message??getGlobalMessage(so.lang);lo&&(so.message=typeof lo=="function"?lo(so):lo),co&&(to.typed=!1),to.issues?to.issues.push(so):to.issues=[so]}function _isValidObjectKey(Xr,eo){return Object.hasOwn(Xr,eo)&&eo!=="__proto__"&&eo!=="prototype"&&eo!=="constructor"}function getDefault(Xr,eo,to){return typeof Xr.default=="function"?Xr.default(eo,to):Xr.default}function is$7(Xr,eo){return!Xr._run({typed:!1,value:eo},{abortEarly:!0}).issues}function array$3(Xr,eo){return{kind:"schema",type:"array",reference:array$3,expects:"Array",async:!1,item:Xr,message:eo,_run(to,ro){var io;const no=to.value;if(Array.isArray(no)){to.typed=!0,to.value=[];for(let oo=0;ooisNaN(+ro)).map(([,ro])=>ro);return{kind:"schema",type:"enum",reference:enum_,expects:to.map(_stringify).join(" | ")||"never",async:!1,enum:Xr,options:to,message:eo,_run(ro,no){return this.options.includes(ro.value)?ro.typed=!0:_addIssue(this,"type",ro,no),ro}}}function literal$3(Xr,eo){return{kind:"schema",type:"literal",reference:literal$3,expects:_stringify(Xr),async:!1,literal:Xr,message:eo,_run(to,ro){return to.value===this.literal?to.typed=!0:_addIssue(this,"type",to,ro),to}}}function looseObject(Xr,eo){return{kind:"schema",type:"loose_object",reference:looseObject,expects:"Object",async:!1,entries:Xr,message:eo,_run(to,ro){var io;const no=to.value;if(no&&typeof no=="object"){to.typed=!0,to.value={};for(const oo in this.entries){const ao=no[oo],so=this.entries[oo]._run({typed:!1,value:ao},ro);if(so.issues){const co={type:"object",origin:"value",input:no,key:oo,value:ao};for(const lo of so.issues)lo.path?lo.path.unshift(co):lo.path=[co],(io=to.issues)==null||io.push(lo);if(to.issues||(to.issues=so.issues),ro.abortEarly){to.typed=!1;break}}so.typed||(to.typed=!1),(so.value!==void 0||oo in no)&&(to.value[oo]=so.value)}if(!to.issues||!ro.abortEarly)for(const oo in no)_isValidObjectKey(no,oo)&&!(oo in this.entries)&&(to.value[oo]=no[oo])}else _addIssue(this,"type",to,ro);return to}}}function nonOptional(Xr,eo){return{kind:"schema",type:"non_optional",reference:nonOptional,expects:"!undefined",async:!1,wrapped:Xr,message:eo,_run(to,ro){return to.value===void 0?(_addIssue(this,"type",to,ro),to):this.wrapped._run(to,ro)}}}function null_(Xr){return{kind:"schema",type:"null",reference:null_,expects:"null",async:!1,message:Xr,_run(eo,to){return eo.value===null?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function nullish(Xr,...eo){const to={kind:"schema",type:"nullish",reference:nullish,expects:`${Xr.expects} | null | undefined`,async:!1,wrapped:Xr,_run(ro,no){return(ro.value===null||ro.value===void 0)&&("default"in this&&(ro.value=getDefault(this,ro,no)),ro.value===null||ro.value===void 0)?(ro.typed=!0,ro):this.wrapped._run(ro,no)}};return 0 in eo&&(to.default=eo[0]),to}function number$4(Xr){return{kind:"schema",type:"number",reference:number$4,expects:"number",async:!1,message:Xr,_run(eo,to){return typeof eo.value=="number"&&!isNaN(eo.value)?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function object(Xr,eo){return{kind:"schema",type:"object",reference:object,expects:"Object",async:!1,entries:Xr,message:eo,_run(to,ro){var io;const no=to.value;if(no&&typeof no=="object"){to.typed=!0,to.value={};for(const oo in this.entries){const ao=no[oo],so=this.entries[oo]._run({typed:!1,value:ao},ro);if(so.issues){const co={type:"object",origin:"value",input:no,key:oo,value:ao};for(const lo of so.issues)lo.path?lo.path.unshift(co):lo.path=[co],(io=to.issues)==null||io.push(lo);if(to.issues||(to.issues=so.issues),ro.abortEarly){to.typed=!1;break}}so.typed||(to.typed=!1),(so.value!==void 0||oo in no)&&(to.value[oo]=so.value)}}else _addIssue(this,"type",to,ro);return to}}}function optional$4(Xr,...eo){const to={kind:"schema",type:"optional",reference:optional$4,expects:`${Xr.expects} | undefined`,async:!1,wrapped:Xr,_run(ro,no){return ro.value===void 0&&("default"in this&&(ro.value=getDefault(this,ro,no)),ro.value===void 0)?(ro.typed=!0,ro):this.wrapped._run(ro,no)}};return 0 in eo&&(to.default=eo[0]),to}function picklist(Xr,eo){return{kind:"schema",type:"picklist",reference:picklist,expects:Xr.map(_stringify).join(" | ")||"never",async:!1,options:Xr,message:eo,_run(to,ro){return this.options.includes(to.value)?to.typed=!0:_addIssue(this,"type",to,ro),to}}}function string$4(Xr){return{kind:"schema",type:"string",reference:string$4,expects:"string",async:!1,message:Xr,_run(eo,to){return typeof eo.value=="string"?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function undefined_(Xr){return{kind:"schema",type:"undefined",reference:undefined_,expects:"undefined",async:!1,message:Xr,_run(eo,to){return eo.value===void 0?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function _subIssues(Xr){let eo;if(Xr)for(const to of Xr)eo?eo.push(...to.issues):eo=to.issues;return eo}function union$3(Xr,eo){return{kind:"schema",type:"union",reference:union$3,expects:[...new Set(Xr.map(to=>to.expects))].join(" | ")||"never",async:!1,options:Xr,message:eo,_run(to,ro){let no,io,oo;for(const ao of this.options){const so=ao._run({typed:!1,value:to.value},ro);if(so.typed)if(so.issues)io?io.push(so):io=[so];else{no=so;break}else oo?oo.push(so):oo=[so]}if(no)return no;if(io){if(io.length===1)return io[0];_addIssue(this,"type",to,ro,{issues:_subIssues(io)}),to.typed=!0}else{if((oo==null?void 0:oo.length)===1)return oo[0];_addIssue(this,"type",to,ro,{issues:_subIssues(oo)})}return to}}}function unknown$3(){return{kind:"schema",type:"unknown",reference:unknown$3,expects:"unknown",async:!1,_run(Xr){return Xr.typed=!0,Xr}}}var lib$2={},signer={},base64Url={},base64Js={};base64Js.byteLength=byteLength;base64Js.toByteArray=toByteArray;base64Js.fromByteArray=fromByteArray;var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i$6=0,len=code.length;i$60)throw new Error("Invalid string. Length must be a multiple of 4");var to=Xr.indexOf("=");to===-1&&(to=eo);var ro=to===eo?0:4-to%4;return[to,ro]}function byteLength(Xr){var eo=getLens(Xr),to=eo[0],ro=eo[1];return(to+ro)*3/4-ro}function _byteLength(Xr,eo,to){return(eo+to)*3/4-to}function toByteArray(Xr){var eo,to=getLens(Xr),ro=to[0],no=to[1],io=new Arr(_byteLength(Xr,ro,no)),oo=0,ao=no>0?ro-4:ro,so;for(so=0;so>16&255,io[oo++]=eo>>8&255,io[oo++]=eo&255;return no===2&&(eo=revLookup[Xr.charCodeAt(so)]<<2|revLookup[Xr.charCodeAt(so+1)]>>4,io[oo++]=eo&255),no===1&&(eo=revLookup[Xr.charCodeAt(so)]<<10|revLookup[Xr.charCodeAt(so+1)]<<4|revLookup[Xr.charCodeAt(so+2)]>>2,io[oo++]=eo>>8&255,io[oo++]=eo&255),io}function tripletToBase64(Xr){return lookup[Xr>>18&63]+lookup[Xr>>12&63]+lookup[Xr>>6&63]+lookup[Xr&63]}function encodeChunk(Xr,eo,to){for(var ro,no=[],io=eo;ioao?ao:oo+io));return ro===1?(eo=Xr[to-1],no.push(lookup[eo>>2]+lookup[eo<<4&63]+"==")):ro===2&&(eo=(Xr[to-2]<<8)+Xr[to-1],no.push(lookup[eo>>10]+lookup[eo>>4&63]+lookup[eo<<2&63]+"=")),no.join("")}Object.defineProperty(base64Url,"__esModule",{value:!0});base64Url.decode=base64Url.encode=base64Url.unescape=base64Url.escape=base64Url.pad=void 0;const base64_js_1$1=base64Js;function pad(Xr){return`${Xr}${"=".repeat(4-(Xr.length%4||4))}`}base64Url.pad=pad;function escape(Xr){return Xr.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}base64Url.escape=escape;function unescape$1(Xr){return pad(Xr).replace(/-/g,"+").replace(/_/g,"/")}base64Url.unescape=unescape$1;function encode$n(Xr){return escape((0,base64_js_1$1.fromByteArray)(new TextEncoder().encode(Xr)))}base64Url.encode=encode$n;function decode$q(Xr){return new TextDecoder().decode((0,base64_js_1$1.toByteArray)(pad(unescape$1(Xr))))}base64Url.decode=decode$q;var cryptoClients={},secp256k1$1={};const require$$0$a=getAugmentedNamespace(hmac$5);var lib$1={},cryptoBrowserify={},browser$g={exports:{}},safeBuffer$1={exports:{}};const require$$0$9=getAugmentedNamespace(dist$2);/*! safe-buffer. MIT License. Feross Aboukhadijeh */(function(Xr,eo){var to=require$$0$9,ro=to.Buffer;function no(oo,ao){for(var so in oo)ao[so]=oo[so]}ro.from&&ro.alloc&&ro.allocUnsafe&&ro.allocUnsafeSlow?Xr.exports=to:(no(to,eo),eo.Buffer=io);function io(oo,ao,so){return ro(oo,ao,so)}io.prototype=Object.create(ro.prototype),no(ro,io),io.from=function(oo,ao,so){if(typeof oo=="number")throw new TypeError("Argument must not be a number");return ro(oo,ao,so)},io.alloc=function(oo,ao,so){if(typeof oo!="number")throw new TypeError("Argument must be a number");var co=ro(oo);return ao!==void 0?typeof so=="string"?co.fill(ao,so):co.fill(ao):co.fill(0),co},io.allocUnsafe=function(oo){if(typeof oo!="number")throw new TypeError("Argument must be a number");return ro(oo)},io.allocUnsafeSlow=function(oo){if(typeof oo!="number")throw new TypeError("Argument must be a number");return to.SlowBuffer(oo)}})(safeBuffer$1,safeBuffer$1.exports);var safeBufferExports=safeBuffer$1.exports,hasRequiredBrowser$b;function requireBrowser$b(){if(hasRequiredBrowser$b)return browser$g.exports;hasRequiredBrowser$b=1;var Xr=65536,eo=4294967295;function to(){throw new Error(`Secure random number generation is not supported by this browser. +Expected: awaiting_signature`)},useAwaitingSignature=()=>{const[Xr,eo]=reactExports.useState("idle"),to=reactExports.useCallback(()=>{eo("idle")},[eo]),ro=reactExports.useCallback((no,io)=>{validateMultiWalletWidgetState(io),validateStateTransition$1({from:Xr,to:no}),eo(no)},[Xr]);return[Xr,ro,to]},validTransitions={awaiting_account_switch:["awaiting_signature","idle"],awaiting_connection:["idle"],awaiting_signature:["idle"],detected_new_wallet:["awaiting_signature","idle"],idle:["awaiting_account_switch","awaiting_connection","awaiting_signature","detected_new_wallet"]},validateStateTransition=({from:Xr,to:eo})=>{if(Xr!==eo&&!validTransitions[Xr].includes(eo))throw new Error(`Invalid MultiWalletWidget state transition from ${Xr} to ${eo}`);return!0},useMultiWalletWidgetState=()=>{const[Xr,eo]=reactExports.useState("idle"),[to,ro,no]=useAwaitingAccountSwitch(),[io,oo,ao]=useAwaitingSignature(),so=reactExports.useCallback(()=>{no(),ao()},[no,ao]),co=reactExports.useCallback((lo,fo,ho)=>{validateStateTransition({from:Xr,to:lo}),eo(lo),so(),fo&&ro(fo,lo),ho&&oo(ho,lo)},[Xr,so,ro,oo]);return[Xr,co,{awaiting_account_switch:[to,ro],awaiting_signature:[io,oo]}]},useClearWalletConnectSessions=({connectors:Xr})=>{const eo=()=>{if(!(typeof window>"u")){for(const to of StorageService.getKeys())(to.startsWith("walletconnect")||to.startsWith("walletlink")||to.startsWith("wc@2"))&&localStorage.removeItem(to);Xr==null||Xr.forEach(to=>{var ro,no,io;!((no=(ro=to==null?void 0:to.name)===null||ro===void 0?void 0:ro.toLowerCase())===null||no===void 0)&&no.startsWith("turnkey")&&((io=to.getAuthenticatorHandler())===null||io===void 0||io.clear(),StorageService.removeItem(EMBEDDED_WALLET_SESSION_SETTINGS),StorageService.removeItem(EMBEDDED_WALLET_SECURE_BANNER))})}};return reactExports.useEffect(()=>{if(typeof window>"u"||Xr.length===0)return;const to=new Set(Xr.map(ro=>ro.key));for(const ro of StorageService.getKeys())ro.startsWith("walletconnect")&&!to.has(ro.replace("walletconnect-",""))&&localStorage.removeItem(ro)},[Xr]),{clearAllWalletConnectSessions:eo}},revokeSession=Xr=>__awaiter$j(void 0,[Xr],void 0,function*({environmentId:eo,sessionId:to}){try{yield sdkApi$1().revokeSession({environmentId:eo})}catch(ro){const no=yield ro.json();logger$8.error(Error(no.error.message))}}),mapChainToChainEnum=Xr=>{const eo=Object.values(ChainEnum).find(to=>to===Xr);if(!eo)throw new DynamicError(`Invalid chain ${Xr}`);return eo},mapProviderToProviderEnum=Xr=>{const eo=Object.values(WalletProviderEnum).find(to=>to===Xr);if(!eo)throw new DynamicError(`Invalid provider ${Xr}`);return eo},mapAuthModeTypeToEnum=Xr=>{const eo=Object.values(AuthModeEnum).find(to=>to===Xr);if(!eo)throw new DynamicError(`Invalid authMode ${Xr}`);return eo},createVisit=Xr=>__awaiter$j(void 0,[Xr],void 0,function*({authMode:eo,chain:to,environmentId:ro,walletProvider:no,publicWalletAddress:io,walletName:oo}){try{const ao={address:io,authMode:mapAuthModeTypeToEnum(eo),chain:mapChainToChainEnum(to),provider:mapProviderToProviderEnum(no),walletName:oo};yield sdkApi$1().createVisit({connectRequest:ao,environmentId:ro})}catch(ao){logger$8.error(ao)}}),getWalletConnectorForWallet=Xr=>{var eo,to;if(!Xr)return;const ro=getWalletConnectorOptions(),{key:no,chain:io}=Xr,oo=(eo=ro.find(so=>no===so.key&&so.walletConnector.connectedChain===io))===null||eo===void 0?void 0:eo.walletConnector;return oo||((to=ro.find(so=>so.key==="fallbackconnector"))===null||to===void 0?void 0:to.walletConnector)},updateUserWalletsFromConnectedWallets=(Xr,eo)=>{const to=[...Xr],ro=new Set;for(const no of eo)ro.add(no.address),to.find(oo=>oo.address===no.address)||to.push(no);return to.filter(no=>ro.has(no.address)||no.isAuthenticated)},useConnectWallet=({authMode:Xr,clearPrimaryWalletId:eo,enableVisitTrackingOnConnectOnly:to,environmentId:ro,primaryWalletId:no,setPrimaryWalletId:io,walletConnectorOptions:oo,handleConnectedWallet:ao,setShowAuthFlow:so,isBridgeFlow:co,user:lo})=>{const[fo,ho,go]=useLocalStorage(CONNECTED_WALLETS_INFO,[]),[yo,vo]=reactExports.useState([]),{setUserWallets:wo,addedWalletsIds:Eo,removedWalletsIds:ko}=useInternalUserWallets(),Ao=reactExports.useCallback(Bo=>{vo(Bo),wo(xo=>updateUserWalletsFromConnectedWallets(xo,Bo))},[wo]),Po=reactExports.useCallback(Bo=>__awaiter$j(void 0,void 0,void 0,function*(){const xo=yo.find(bo=>bo.id===Bo);yield xo==null?void 0:xo.connector.endSession();const uo=fo.filter(bo=>bo.id!==Bo);if(ho(uo),ko.current.push(Bo),Bo!==no)return;const po=uo.length>0;co||!po?eo():io(uo[0].id)}),[eo,yo,fo,co,no,ko,ho,io]),jo=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const Bo=oo.map(uo=>uo.walletConnector);if(!Bo.length)return;const xo=(yield Promise.all(fo.map(uo=>__awaiter$j(void 0,void 0,void 0,function*(){const po=getWalletConnectorByKey(Bo,uo.walletConnectorKey);if(!po)return logger$9.error("Could not find walletConnector: "+uo.walletConnectorKey),yield Po(uo.id),null;isHardwareWalletConnector(po)&&uo.hardwareWallet===HardwareWalletEnum.Ledger&&(po.isHardwareWalletEnabled=!0);const[bo]=yield po.getConnectedAccounts();if(!bo)return yield Po(uo.id),null;const _o=yield po.getAdditionalAddresses(bo),$o=po.connectedChain;return po.createWallet({additionalAddresses:_o,address:bo,chain:$o,connector:po,id:uo.id,isAuthenticated:!1,key:po.key})})))).filter(uo=>!!uo);Ao(xo)}),[fo,Po,Ao,oo]);reactExports.useEffect(()=>{jo()},[fo,oo]);const Mo=reactExports.useCallback(Bo=>{const uo=Bo.map(({id:po})=>po).map(po=>Number(po.replace("connect-wallet-",""))).sort((po,bo)=>po-bo);for(let po=0;po{var uo;const po=[...yo],bo=po.findIndex(_o=>_o.id===Bo);bo<0||(po[bo]=po[bo].connector.createWallet(Object.assign(Object.assign({},po[bo]),{address:(uo=xo.address)!==null&&uo!==void 0?uo:po[bo].address,connector:getWalletConnectorForWallet(po[bo])})),Ao(po))},[yo,Ao]),Do=({walletId:Bo,walletConnectorKey:xo,walletChain:uo,provider:po})=>{const bo=[...fo],_o=oo.map(Ro=>Ro.walletConnector),$o=getWalletConnectorByKey(_o,xo),Co=$o&&isHardwareWalletConnector($o)&&$o.isHardwareWalletEnabled?HardwareWalletEnum.Ledger:void 0;bo.push({hardwareWallet:Co,id:Bo,provider:po,walletChain:uo,walletConnectorKey:xo}),ho(bo)},Fo=(Bo,xo)=>__awaiter$j(void 0,void 0,void 0,function*(){shouldManuallyReconnectOnRefresh(xo)&&(yield xo.connect());const uo=yield xo.getAddress();if(uo&&ao&&!(yield ao({address:uo,chain:xo.connectedChain,connector:xo}))){logger$9.info("Connection was not established because handleConnectedWallet returned false"),Po(Bo),so(!1,{emitCancelAuth:!0});return}No(Bo,{address:uo})}),Xo=(Bo,xo,uo)=>__awaiter$j(void 0,void 0,void 0,function*(){const{applyHandleConnectedWallet:po=!0}=uo??{},bo=yield Bo.getAddress(xo);if(!bo)throw new MissingPublicAddressError;if(ao&&po&&!(yield ao({address:bo,chain:Bo.connectedChain,connector:Bo}))){logger$9.info("Connection was not established because handleConnectedWallet returned false"),so(!1);return}const _o=fo.some(({walletConnectorKey:So})=>So===Bo.key),$o=Bo.connectedChain;if(!_o&&(Xr!=="connect-only"||to)&&createVisit({authMode:Xr,chain:$o||"",environmentId:ro,publicWalletAddress:bo,walletName:Bo.key,walletProvider:getWalletProvider(Bo)}),!isConnectOnly(lo,Xr))return{address:bo,id:""};const Ro=`connect-wallet-${Mo(fo)}`;return no||io(Ro),Eo.current.push(Ro),_o?yield jo():Do({provider:getWalletProvider(Bo),walletAddress:bo,walletChain:$o,walletConnectorKey:Bo.key,walletId:Ro}),{address:bo,id:Ro}}),Lo=reactExports.useCallback(Bo=>yo.find(xo=>xo.id===Bo),[yo]);return{connectWallet:Xo,connectedWallets:yo,connectedWalletsInfo:fo,disconnectWallet:Po,getConnectedWalletById:Lo,refreshConnectedWallet:Fo,removeConnectedWalletsInfo:go}},useFetchWalletsForChainsMap=Xr=>({walletsForChainsMap:reactExports.useMemo(()=>Xr?Object.assign(Object.assign({},defaultWalletsForChains),{primary_chain:Xr.primary_chain,wallets:Object.assign(Object.assign({},defaultWalletsForChains.wallets),!!Xr.wallets&&Xr.wallets)}):defaultWalletsForChains,[Xr])}),useHandleUnlinkWallet=({verifiedCredentials:Xr,environmentId:eo,primaryWalletId:to,secondaryWallets:ro})=>{const{removedWalletsIds:no}=useInternalUserWallets();return reactExports.useCallback(oo=>__awaiter$j(void 0,void 0,void 0,function*(){var ao;const so=(ao=StorageService.getItem(PRIMARY_WALLET_ID))!==null&&ao!==void 0?ao:to;if(oo===so)return;yield unlinkWallet({environmentId:eo,onSuccess:()=>{no.current.push(oo)},primaryWalletId:so,walletId:oo});const co=ro.find(fo=>fo.id===oo);Xr.filter(fo=>fo.walletName===((co==null?void 0:co.connector.key)||"")).length===1&&(yield co==null?void 0:co.connector.endSession())}),[to,eo,ro,Xr,no])},primaryWalletIdValidator=Xr=>typeof Xr=="string"||typeof Xr>"u",usePrimaryWalletId=({environmentId:Xr,user:eo})=>{const[to,ro,no]=useLocalStorage(PRIMARY_WALLET_ID,void 0,primaryWalletIdValidator),io=reactExports.useCallback(oo=>__awaiter$j(void 0,void 0,void 0,function*(){ro(oo),eo&&(yield storeSelectedWallet({environmentId:Xr,walletId:oo}))}),[Xr,ro,eo]);return{clearPrimaryWalletId:no,primaryWalletId:to,setPrimaryWalletId:io}},useWalletEventListeners=({disconnectWallet:Xr,handleLogOut:eo,multiWallet:to,multiWalletWidgetState:ro,primaryWallet:no,secondaryWallets:io,selectedWalletConnector:oo,selectedWalletWithAction:ao,setSelectedWalletConnectorKey:so,setSelectedWalletWithAction:co,setMultiWalletWidgetState:lo,user:fo,setPrimaryWalletId:ho,authMode:go,refreshConnectedWallet:yo,detectNewWalletsForLinking:vo})=>{const wo=reactExports.useCallback((Ao,Po)=>{logger$8.debug("handleAccountChangeWhenAwaitingAccountSwitch",{isPrimaryWallet:Ao,newAddress:Po});const jo=io.find(No=>isSameAddress$1(No.address,Po,No.chain));if(logger$8.logVerboseTroubleshootingMessage("[handleAccountChangeWhenAwaitingAccountSwitch]",{linkedSecondaryWallet:jo}),!jo){lo("awaiting_signature",void 0,"linking_new_wallet"),Ao&&no&&so(no.connector.key);return}if(jo.connector.key==="unknown"){dynamicEvents.emit("triggerConnectAndSign");return}co(null),ho(jo.id),lo("idle")},[lo,no,io,so,co,ho]),Eo=reactExports.useCallback(({accounts:Ao})=>{if(logger$8.debug("calculatePrimaryWalletMultiWalletStateFromAccounts",{accounts:Ao,authMode:go,multiWallet:to,multiWalletWidgetState:ro,primaryWallet:no}),!no)return;const[Po]=Ao;if(!!isSameAddress$1(Po,no.address,no.chain)){lo("idle");return}if(go==="connect-only"){yo(no.id,no.connector);return}if(!to)return;if(ro==="awaiting_account_switch"){wo(!0,Po);return}ro!=="idle"&&(logger$8.error(`Unexpected multiWalletWidgetState (${ro}) and onAccountChange combination. Resetting state to idle.`),lo("idle"));const Mo=io.find(No=>isSameAddress$1(No.address,Po,No.chain));if(Mo){ho(Mo.id);return}fo&&vo&&(lo("detected_new_wallet"),so(no.connector.key))},[go,vo,wo,to,ro,no,yo,io,lo,ho,so,fo]);useInternalDynamicEvents("triggerComputePrimaryWalletMultiWalletStateFromAccounts",Eo),useWalletConnectorEvent(no==null?void 0:no.connector,"accountChange",({accounts:Ao})=>{logger$8.debug("primary wallet account change",{accounts:Ao}),Eo({accounts:Ao})});const ko=reactExports.useMemo(()=>{const Ao=no==null?void 0:no.connector,Po=io.map(({connector:Mo})=>Mo),jo=new Set([...Po,Ao,oo].filter(Mo=>!!Mo));return Ao&&jo.delete(Ao),Array.from(jo)},[io,oo,no==null?void 0:no.connector]);useWalletConnectorEvent(ko,"accountChange",(Ao,Po)=>__awaiter$j(void 0,void 0,void 0,function*(){if(logger$8.debug("secondary wallet account change"),go==="connect-only"&&io.length){const jo=io.filter(({connector:Mo})=>Mo.key===Po.key);for(const Mo of jo)yo(Mo.id,Mo.connector);return}ro==="awaiting_account_switch"&&wo(!1,(ao==null?void 0:ao.wallet.address)||"")})),useWalletConnectorEvent(no==null?void 0:no.connector,"disconnect",()=>{logger$8.debug("primary wallet disconnect"),go==="connect-only"&&eo()}),useWalletConnectorEvent(ko,"disconnect",Ao=>{if(logger$8.debug("secondary wallet disconnect"),go==="connect-only"){const Po=io.filter(({connector:jo})=>jo.key===Ao.key);for(const jo of Po)Xr(jo.id)}})},useTabState=({settingsOverrides:Xr})=>{var eo,to,ro;const no=(eo=Xr==null?void 0:Xr.views)===null||eo===void 0?void 0:eo.find(so=>so.type==="wallet-list"),[io,oo]=reactExports.useState(0),ao=io===null||(to=no==null?void 0:no.tabs)===null||to===void 0?void 0:to.items[io];return{selectedTabIndex:io,selectedTabSettings:ao,setSelectedTabIndex:oo,tabsItems:(ro=no==null?void 0:no.tabs)===null||ro===void 0?void 0:ro.items}},DynamicBridgeWidgetContext=React.createContext(void 0),initialView="wallets",DynamicBridgeWidgetContextProvider=({children:Xr})=>{const eo=reactExports.useRef(null),to=reactExports.useRef(null),[ro,no]=reactExports.useState(initialView),io=reactExports.useCallback(()=>{no(initialView)},[]),oo=reactExports.useCallback(()=>{no("profile")},[]),ao={bridgeWidgetView:ro,events:{onDynamicBridgeWidgetClose:io},goToProfileView:oo,inlineControlsRef:to,setBridgeWidgetView:no,widgetRef:eo};return jsxRuntimeExports.jsx(DynamicBridgeWidgetContext.Provider,{value:ao,children:Xr})},DynamicWidgetCard=reactExports.forwardRef(({children:Xr},eo)=>jsxRuntimeExports.jsx("div",{ref:eo,className:"dynamic-widget-card",children:Xr}));DynamicWidgetCard.displayName="DynamicWidgetCard";const widgetRegistryContext=reactExports.createContext(null),WidgetRegistryContextProvider=({children:Xr})=>{const[eo,to]=reactExports.useState({}),ro=reactExports.useCallback((oo,ao)=>{to(so=>Object.assign(Object.assign({},so),{[oo]:{type:ao}}))},[to]),no=reactExports.useCallback(oo=>{to(ao=>{const so=Object.assign({},ao);return delete so[oo],so})},[to]),io=reactExports.useCallback(oo=>Object.values(eo).some(ao=>ao.type===oo),[eo]);return jsxRuntimeExports.jsx(widgetRegistryContext.Provider,{value:{checkWidgetPresence:io,registerId:ro,removeId:no},children:Xr})},Modal=({onrampUrl:Xr})=>{const{fundingRef:eo,setShowFunding:to}=useFundingContext();return useOnClickOutside(eo,()=>{to(!1)}),jsxRuntimeExports.jsx("div",{className:"fund-wallet__modal","data-testid":"fund-wallet-modal",children:jsxRuntimeExports.jsx("div",{className:"fund-wallet__modal-content",ref:eo,children:jsxRuntimeExports.jsx("iframe",{id:"onramp-iframe",src:Xr,allow:"camera *;geolocation *",title:"Crypto Onramp"})})})},FundWalletView=()=>{const{primaryWallet:Xr}=useInternalDynamicContext(),{showFunding:eo,fundingUrl:to,fundingEnabled:ro}=useFundingContext();return!ro||!eo||!to||!(Xr!=null&&Xr.address)?null:jsxRuntimeExports.jsx(ShadowDOM,{children:jsxRuntimeExports.jsxs(OpacityTransition,{isShown:eo,children:[jsxRuntimeExports.jsx("div",{className:"fund-wallet__backdrop","aria-hidden":"true"}),jsxRuntimeExports.jsx("div",{className:"fund-wallet__modal-container",children:jsxRuntimeExports.jsx(Modal,{onrampUrl:to})})]})})},FundingWidget=()=>jsxRuntimeExports.jsx(FundWalletView,{}),ConnectWithOtpContext=reactExports.createContext(void 0),createEmailHandler=(Xr,{shouldRegisterSessionKeysOnSignin:eo,generateSessionKey:to})=>ro=>__awaiter$j(void 0,void 0,void 0,function*(){const no=yield createEmailVerification({email:ro,environmentId:Xr});let{verificationUUID:io}=no;return{retry:()=>__awaiter$j(void 0,void 0,void 0,function*(){io=(yield retryEmailVerification({email:ro,environmentId:Xr,verificationUUID:io})).verificationUUID}),type:"email",verify:oo=>__awaiter$j(void 0,void 0,void 0,function*(){let ao;eo()&&(ao=(yield to()).publicKey);const so=yield signInWithEmailVerification({environmentId:Xr,sessionPublicKey:ao,verificationToken:oo,verificationUUID:io});return storeAuthTokenAndUser(so),{destination:ro,verified:!!so.jwt}})}}),createMagicHandler=(Xr,eo)=>to=>__awaiter$j(void 0,void 0,void 0,function*(){if(!Xr)throw new Error("OTP wallet connector was not found");return Xr.setEmail(to),eo(Xr),{retry:()=>Xr.retryOneTimePassword(),type:"email",verify:ro=>__awaiter$j(void 0,void 0,void 0,function*(){return{destination:to,verified:yield Xr.verifyOneTimePassword(ro)}})}}),createSmsHandler=Xr=>eo=>__awaiter$j(void 0,void 0,void 0,function*(){const{generateSessionKey:to,shouldRegisterSessionKeysOnSignin:ro}=useEmbeddedWalletSessionKeys(Xr),{verificationUUID:no}=yield createSmsVerification({environmentId:Xr,isoCountryCode:eo.iso2,phoneCountryCode:eo.dialCode,phoneNumber:eo.phone});return{type:"sms",verify:io=>__awaiter$j(void 0,void 0,void 0,function*(){let oo;ro()&&(oo=(yield to()).publicKey);const ao=yield signInWithSmsVerification({environmentId:Xr,sessionPublicKey:oo,verificationToken:io,verificationUUID:no});return storeAuthTokenAndUser(ao),{destination:eo,verified:!!ao.jwt}})}}),mapEmailProviderToProviderEnum={dynamic:ProviderEnum.Dynamic,magicLink:ProviderEnum.MagicLink},allSupportedProviders=Object.values(mapEmailProviderToProviderEnum),findEmailProvider=(Xr,eo)=>__awaiter$j(void 0,void 0,void 0,function*(){const{emailProvider:to}=yield getEmailProvider({email:eo,environmentId:Xr});if(!allSupportedProviders.includes(to))throw new Error("Email provider is not supported");return to}),{Provider:Provider$1}=ConnectWithOtpContext,ConnectWithOtpProvider=({children:Xr})=>{const{walletConnectorOptions:eo,environmentId:to,projectSettings:ro,setCallback:no}=useInternalDynamicContext(),io=useEmbeddedWalletSessionKeys(to),{handleInstalledExtensionClick:oo}=useWalletItemActions(),ao=reactExports.useRef(null),so=(ro==null?void 0:ro.providers)||[],co=eo.map(({walletConnector:vo})=>vo).find(isEmailOTPWalletConnector),lo={[ProviderEnum.Dynamic]:{enabled:isProviderEnabled(so,ProviderEnum.Dynamic),handler:createEmailHandler(to,io)},[ProviderEnum.MagicLink]:{enabled:isProviderEnabled(so,ProviderEnum.MagicLink),handler:createMagicHandler(co,oo)}},fo=(vo,...wo)=>__awaiter$j(void 0,[vo,...wo],void 0,function*(Eo,{provider:ko}={}){if(!isEmailValid(Eo))throw new Error("Email is not valid");const Ao=ko||(yield findEmailProvider(to,Eo));if(!lo[Ao].enabled)throw new Error("Email provider is not enabled");const Po=yield lo[Ao].handler(Eo);ao.current=Po}),ho=vo=>__awaiter$j(void 0,void 0,void 0,function*(){if(!isProviderEnabled(so,ProviderEnum.Sms))throw new Error("SMS provider is not enabled");const Eo=yield createSmsHandler(to)(vo);ao.current=Eo}),go=vo=>__awaiter$j(void 0,void 0,void 0,function*(){if(!ao.current)throw new Error("Verification has not started, use connectWithEmail or connectWithSms before verifying");const{type:wo,verify:Eo}=ao.current,{destination:ko,verified:Ao}=yield Eo(vo);if(wo==="sms"?dynamicEvents.emit("smsVerificationResult",Ao,ko):dynamicEvents.emit("emailVerificationResult",Ao,ko),Ao)no("authSuccess");else throw new Error(`${wo==="sms"?"SMS":"Email"} verification failed`)}),yo=()=>__awaiter$j(void 0,void 0,void 0,function*(){if(!ao.current)throw new Error("Verification has not started, use connectWithEmail or connectWithSms before verifying");if(!ao.current.retry)throw new Error("Re-send is not supported");return ao.current.retry()});return jsxRuntimeExports.jsx(Provider$1,{value:{connectWithEmail:fo,connectWithSms:ho,retryOneTimePassword:yo,verifyOneTimePassword:go},children:Xr})},ERROR_BOUNDARY_CONTEXT_NOT_FOUND="ERROR_BOUNDARY_CONTEXT_NOT_FOUND",ErrorBoundaryContext=reactExports.createContext(null);function assertErrorBoundaryContext(Xr){if(Xr===null||typeof Xr.hasError!="boolean"||typeof Xr.error!="object"||typeof Xr.isDynamicSdkError!="boolean"){const eo=new Error("ErrorBoundaryContext not found");throw eo.cause=ERROR_BOUNDARY_CONTEXT_NOT_FOUND,eo}}class ErrorBoundaryBase extends reactExports.Component{static getDerivedStateFromError(eo){return{error:eo,hasError:!0}}renderOrError(eo,{isDynamicSdkError:to}){try{assertErrorBoundaryContext(this.context),this.context.isDynamicSdkError=to}catch(ro){return logger$8.error(ro),reactExports.createElement(ErrorContainer,null,"ErrorBoundary must be used within ErrorBoundaryContext")}return eo}}ErrorBoundaryBase.contextType=ErrorBoundaryContext;class ErrorBoundaryReporter extends ErrorBoundaryBase{constructor(eo){super(eo),this.state={error:null,hasError:!1}}componentDidCatch(eo,to){var ro;const{onError:no}=this.props;throw!((ro=this.context)===null||ro===void 0)&&ro.isDynamicSdkError&&(no==null||no(eo,to),logger$8.error(eo,{error:{bundleStack:eo.stack,message:eo,stack:to.componentStack}})),eo}render(){const{children:eo}=this.props,{hasError:to,error:ro}=this.state;return to?(assertErrorBoundaryContext(this.context),this.context.error=ro,this.context.hasError=to,null):eo}}const ErrorBoundary=Xr=>{var{children:eo}=Xr,to=__rest$7(Xr,["children"]);return jsxRuntimeExports.jsx(ErrorBoundaryContext.Provider,{value:{error:null,hasError:!1,isDynamicSdkError:!0},children:jsxRuntimeExports.jsx(ErrorBoundaryReporter,Object.assign({},to,{children:eo}))})};class ErrorBoundaryExclude extends ErrorBoundaryBase{render(){const{children:eo}=this.props;return this.renderOrError(eo,{isDynamicSdkError:!1})}}const useResponseHandlers=()=>{const{walletConnectorOptions:Xr,consumeNonce:eo,displaySiweStatement:to,environmentId:ro,projectSettings:no,setIsSingleWalletAccount:io,connectWallet:oo,setShowAuthFlow:ao,setSelectedWalletConnectorKey:so,siweStatement:co,appName:lo,user:fo}=useInternalDynamicContext(),{setView:ho}=useViewContext(),{setErrorMessage:go}=useErrorContext(),{getCaptchaToken:yo}=useCaptchaContext(),vo=useVerifyWallet({consumeNonce:eo,displaySiweStatement:to,environmentId:ro,projectSettings:no,setIsSingleWalletAccount:io}),wo=Xr.map(({walletConnector:jo})=>jo).find(isPhantomRedirectConnector),Eo=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){wo&&(yield wo.getSession(),yield oo(wo),ao(!0,{ignoreIfIsEmbeddedWidget:!0}),ho("pending-signature"),so("phantom"))}),[oo,wo,so,ao,ho]),ko=useTransferWallet(),Ao=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){if(!wo)return;so("phantom");const[jo]=yield wo.getConnectedAccounts();switch(wo.consumeMethod()){case"signAndSendTransaction":{const{signature:No}=wo.extractSignature();wo.emit("signAndSendTransaction",{signature:No});break}case"signAllTransactions":wo.emit("signAllTransactions",{transactions:wo.extractTransactions()});break;case"signTransaction":wo.emit("signTransaction",{transaction:wo.extractTransaction()});break;case"signMessage":{const{signature:No,message:Do}=wo.extractSignature(),Fo=StorageService.getItem(PHANTOM_SIGNATURE_STATE);if(StorageService.removeItem(PHANTOM_SIGNATURE_STATE),(Fo==null?void 0:Fo.verificationType)==="awaiting_transfer"){const Xo=getSiweStatement({appName:lo,siweStatement:co});yield ko({messageToSignOverride:Do,overrideSiweStatement:Xo,publicWalletAddress:jo,signedMessageOverride:No,skipEmptyAccountCheck:Fo.loseOriginalAccountOnTransfer,walletConnector:wo})}else(Fo==null?void 0:Fo.verificationType)==="awaiting_verification"||!fo?(ho("wallet-redirect-view"),yield vo({captchaToken:yo(),messageToSignOverride:Do,publicWalletAddress:jo,signedMessageOverride:No,walletConnector:wo})):wo.emit("signMessage",{signature:No});break}}}),[wo,so,fo,lo,co,ko,ho,vo,yo]),Po=reactExports.useCallback(jo=>{var Mo;if(!wo)return;const No=jo.get("errorCode"),Do=(Mo=jo.get("errorMessage"))!==null&&Mo!==void 0?Mo:void 0;if(!No)return;switch(go(No),jo.delete("errorCode"),jo.delete("errorMessage"),history.replaceState(null,"",`${window.location.origin}${window.location.pathname}?${jo.toString()}`),wo.consumeMethod()){case"signAndSendTransaction":wo.emit("signAndSendTransaction",{errorCode:No,errorMessage:Do});break;case"signAllTransactions":wo.emit("signAllTransactions",{errorCode:No,errorMessage:Do});break;case"signTransaction":wo.emit("signTransaction",{errorCode:No,errorMessage:Do});break;case"signMessage":wo.emit("signMessage",{errorCode:No,errorMessage:Do});break}},[wo,go]);return{handleConnectResponse:Eo,handleErrorResponse:Po,handleUserResponse:Ao,phantomRedirectConnector:wo}},PhantomRedirectContext=reactExports.createContext(void 0),PhantomRedirectContextProvider=({children:Xr})=>{const{sdkHasLoaded:eo}=useInternalDynamicContext(),{phantomRedirectConnector:to,handleConnectResponse:ro,handleUserResponse:no,handleErrorResponse:io}=useResponseHandlers();return reactExports.useEffect(()=>{if(!to||!isMobile$1()||!eo)return;const oo=new URLSearchParams(window.location.search);if(oo.has("errorCode")){io(oo);return}if(oo.has("phantom_encryption_public_key")){ro();return}if(oo.has("data")){no();return}},[ro,no,io,to,eo]),jsxRuntimeExports.jsx(PhantomRedirectContext.Provider,{value:{phantomRedirectConnector:to},children:Xr})},reinitializeContext=reactExports.createContext(void 0),ReinitializeContextProvider=({children:Xr,onReinitialize:eo})=>{const[to,ro]=reactExports.useState(),no=reactExports.useRef(eo);no.current=eo;const io=reactExports.useCallback(()=>{var oo;const ao=randomString(8);(oo=no.current)===null||oo===void 0||oo.call(no,ao),ro(ao)},[]);return jsxRuntimeExports.jsx(reinitializeContext.Provider,{value:{key:to,reinitialize:io},children:reactExports.cloneElement(Xr,{key:to})})},useConnectedWalletsNetworkValidation=()=>{const{connectedWallets:Xr,selectedWalletConnector:eo,setSelectedWalletConnectorKey:to,setShowAuthFlow:ro,bridgeChainsToConnect:no,sdkHasLoaded:io}=useInternalDynamicContext(),{setView:oo}=useViewContext(),ao=useIsLoggedIn(),so=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const fo=[];for(const ho of Xr){const go=no==null?void 0:no.some(wo=>wo.chain===ho.chain),yo=yield ho.connector.getNetwork(),vo=isSupportedNetwork({network:yo,walletConnector:ho.connector});!go&&!vo&&fo.push(ho)}return fo}),[no,Xr]),co=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const fo=yield so();if(!fo.length)return;const[ho]=fo;ho.connector.key!==(eo==null?void 0:eo.key)&&to(ho.connector.key);const go=isProgrammableNetworkSwitchSupported(ho.connector)?"network-not-supported":"network-not-supported-manual";ro(!0),oo(go)}),[so,eo==null?void 0:eo.key,to,ro,oo]),lo=reactExports.useMemo(()=>{const fo=Xr.map(({connector:go})=>go),ho=new Set([...fo].filter(go=>!!go));return Array.from(ho)},[Xr]);useWalletConnectorEvent(lo,"chainChange",({chain:fo})=>{co()}),reactExports.useEffect(()=>{!io||!ao||co()},[io,ao,co])},UseNetworkValidation=()=>(useConnectedWalletsNetworkValidation(),null),isDisplayOrderPriorityForWeb3=Xr=>{if(Xr.length!==2)return!1;const[eo,to]=Xr;return eo==="wallet"&&to==="email"},useDisplayOrderState=Xr=>{const[eo,to]=reactExports.useState(null),ro=reactExports.useMemo(()=>{var no;const io=(no=Xr==null?void 0:Xr.design.modal)===null||no===void 0?void 0:no.displayOrder;return io?isDisplayOrderPriorityForWeb3(io)?"web3":"web2":"web3"},[Xr]);return[eo||ro,to]},useEmailLoginState=(Xr,eo)=>{const[to,ro]=reactExports.useState(null),no=()=>{ro(null)},io=ao=>{ro(ao)},oo=reactExports.useMemo(()=>eo?!1:isEmailProviderEnabled(Xr),[Xr,eo]);return[to??oo,io,no]},useHandleLogout=Xr=>{const eo=reactExports.useRef(Xr);eo.current=Xr;const to=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){const ro=eo.current;ro.setSelectedWalletConnectorKey(null),ro.clearAllWalletConnectSessions(),ro.setShowDynamicUserProfile(!1),ro.setShowBridgeWidget(!1),ro.resetLoginWithEmail(),ro.user&&(document.cookie=`${DYNAMIC_AUTH_COOKIE_NAME}=; Max-Age=-99999999; path=/; SameSite=Lax`,revokeSession({environmentId:ro.environmentId,sessionId:ro.user.sessionId})),ro.setLegacyIsVerifying(!1),StorageService.removeItem(AUTH_TOKEN,{priority:["secureStorage","localStorage"]}),StorageService.removeItem(AUTH_MIN_TOKEN$1,{priority:["secureStorage","localStorage"]}),StorageService.removeItem(WALLET_PICKER_SEARCH_KEY),StorageService.removeItem(PHANTOM_SIGNATURE_STATE),StorageService.removeItem(AUTH_EXPIRES_AT),ro.setAuthMode(ro.initialAuthenticationMode),ro.setShowAuthFlow(!1,{emitCancelAuth:!1,ignoreIfIsEmbeddedWidget:!1,initializeWalletConnect:!1,performMultiWalletChecks:!1}),ro.setMultiWalletWidgetState("idle"),ro.removeConnectedWalletsInfo(),ro.removeBridgeOnboardingCompleted(),ro.clearPrimaryWalletId(),ro.removeConnectedNameService(),ro.removeSessionStorageSessionKeys(),dynamicEvents.removeListener("embeddedWalletCreatePasswordCompleted"),dynamicEvents.removeListener("embeddedWalletCreatePasswordFailed"),dynamicEvents.removeListener("embeddedWalletUpdatePasswordCompleted"),dynamicEvents.removeListener("embeddedWalletUpdatePasswordFailed"),dynamicEvents.emit("logout"),setUser(void 0),yield Promise.all(ro.walletConnectors.map(no=>no.endSession())),yield Promise.all(ro.connectedWallets.map(no=>no.connector.endSession()))}),[]);return reactExports.useEffect(()=>(StorageService.events.on("parseFailure",to),()=>{StorageService.events.off("parseFailure",to)}),[to]),to},getWalletVerifiedCredential=(Xr,eo,to)=>eo==null?void 0:eo.find(({address:ro})=>isSameAddress$1(ro||"",Xr||"",to)),useNameService=({currentWallet:Xr,user:eo})=>{const[to,ro,no]=useLocalStorage(CONNECTED_WALLET_NAME_SERVICE,null),io=reactExports.useRef(),oo=reactExports.useRef(),ao=reactExports.useCallback(co=>__awaiter$j(void 0,void 0,void 0,function*(){const{address:lo,connector:fo}=co,ho=yield fo.getNetwork();if(lo===io.current&&ho===oo.current)return;ro(null),io.current=lo,oo.current=ho;let go;try{go=yield co.getNameService()}catch{}if(io.current===lo&&oo.current===ho)return ro({address:lo,avatar:go==null?void 0:go.avatar,name:go==null?void 0:go.name,network:ho}),go}),[ro]);return{getNameService:co=>__awaiter$j(void 0,void 0,void 0,function*(){var lo;if(!Xr)return;const fo=yield Xr.connector.getNetwork(),ho=eo==null?void 0:eo.verifiedCredentials;if(ho){const go=getWalletVerifiedCredential(Xr==null?void 0:Xr.address,ho,Xr.chain);if(go&&(!((lo=go.nameService)===null||lo===void 0)&&lo.name))return go.nameService}if(!(co&&(Xr==null?void 0:Xr.address)!==co))return to&&to.address===(Xr==null?void 0:Xr.address)&&to.network===fo?{avatar:to.avatar,name:to.name}:ao(Xr)}),removeConnectedNameService:no}},useSelectedWalletConnector=({walletConnectorOptions:Xr})=>{const[eo,to]=reactExports.useState(null);return{selectedWalletConnector:reactExports.useMemo(()=>{var no,io;return eo&&(io=(no=Xr.find(({walletConnector:oo})=>oo.key===eo))===null||no===void 0?void 0:no.walletConnector)!==null&&io!==void 0?io:null},[eo,Xr]),setSelectedWalletConnectorKey:to}},useShowAuthFlow=({isAuthenticated:Xr,isRenderingEmbeddedAuthFlow:eo,isMultiWalletEnabled:to,walletConnectorOptions:ro,setShowDynamicUserProfile:no})=>{const[io,oo]=reactExports.useState(!1),{setError:ao}=useErrorContext(),so=reactExports.useCallback((co,lo={})=>{var fo;const{emitCancelAuth:ho,ignoreIfIsEmbeddedWidget:go,initializeWalletConnect:yo,performMultiWalletChecks:vo,clearErrors:wo}=Object.assign({clearErrors:!0,emitCancelAuth:!1,ignoreIfIsEmbeddedWidget:!0,initializeWalletConnect:!0,performMultiWalletChecks:!1},lo);if(logger$8.logVerboseTroubleshootingMessage("setShowAuthFlow",{clearErrors:wo,emitCancelAuth:ho,ignoreIfIsEmbeddedWidget:go,initializeWalletConnect:yo,performMultiWalletChecks:vo}),!io&&co?dynamicEvents.emit("authFlowOpen"):io&&!co&&dynamicEvents.emit("authFlowClose"),co){if(go&&eo.current)return;if(vo&&Xr){if(!to)return no(!0);logger$8.warn("Use setShowLinkNewWalletModal to render the wallet list instead. For more information, see: https://docs.dynamic.xyz/react-sdk/hooks/usedynamiccontext");return}yo&&((fo=ro.find(Eo=>Eo.walletConnector.key==="walletconnect"))===null||fo===void 0||fo.walletConnector.init())}else ho&&io&&dynamicEvents.emit("authFlowCancelled");wo&&ao(void 0),oo(co)},[Xr,to,eo,ao,no,io,ro]);return[io,so]},usePasskeySuccessPopup=()=>{const[Xr,eo]=reactExports.useState(void 0);return{passkeySuccessPopup:Xr,setPasskeySuccessPopup:ro=>{eo(ro),setTimeout(()=>{eo(void 0)},2e3)}}},useTieCallbacksToEvents=({clientCallbacks:Xr,user:eo})=>{useInternalDynamicEvents("emailVerificationResult",(to,ro)=>{var no;return(no=Xr==null?void 0:Xr.onOtpVerificationResult)===null||no===void 0?void 0:no.call(Xr,to,{type:"email",value:ro})}),useInternalDynamicEvents("smsVerificationResult",(to,ro)=>{var no;return(no=Xr==null?void 0:Xr.onOtpVerificationResult)===null||no===void 0?void 0:no.call(Xr,to,{type:"sms",value:ro})}),useInternalDynamicEvents("authFlowCancelled",()=>{var to;return(to=Xr==null?void 0:Xr.onAuthFlowCancel)===null||to===void 0?void 0:to.call(Xr)}),useInternalDynamicEvents("authFlowOpen",()=>{var to;(to=Xr==null?void 0:Xr.onAuthFlowOpen)===null||to===void 0||to.call(Xr)}),useInternalDynamicEvents("authFlowClose",()=>{var to;(to=Xr==null?void 0:Xr.onAuthFlowClose)===null||to===void 0||to.call(Xr)}),useInternalDynamicEvents("walletAdded",(to,ro)=>{var no;dynamicEvents.emit("triggerSessionValidation"),logger$8.debug("[walletAdded]",{userWallets:ro,wallet:to}),(no=Xr==null?void 0:Xr.onWalletAdded)===null||no===void 0||no.call(Xr,{userWallets:ro,wallet:to})}),useInternalDynamicEvents("walletRemoved",(to,ro)=>{var no;logger$8.debug("[walletRemoved]",{userWallets:ro,wallet:to}),(no=Xr==null?void 0:Xr.onWalletRemoved)===null||no===void 0||no.call(Xr,{userWallets:ro,wallet:to})}),useInternalDynamicEvents("embeddedWalletCreated",(to,ro,no)=>{var io;logger$8.debug("[embeddedWalletCreated]",{_wallet:to,jwtVerifiedCredential:ro,user:no}),(io=Xr==null?void 0:Xr.onEmbeddedWalletCreated)===null||io===void 0||io.call(Xr,ro,no)}),useInternalDynamicEvents("logout",()=>{var to;(to=Xr==null?void 0:Xr.onLogout)===null||to===void 0||to.call(Xr,eo)}),useInternalDynamicEvents("authFailure",(to,ro)=>{var no;logger$8.debug("[authFailure]",{data:to,reason:ro}),(no=Xr==null?void 0:Xr.onAuthFailure)===null||no===void 0||no.call(Xr,to,ro)}),useInternalDynamicEvents("authInit",to=>{var ro;logger$8.debug("[authInit]",{data:to}),(ro=Xr==null?void 0:Xr.onAuthInit)===null||ro===void 0||ro.call(Xr,to)})},useMultiWallet=({isBridgeFlow:Xr,multiWalletOverride:eo,multiWalletSettings:to})=>{var ro;return eo!==void 0?eo:(ro=to||Xr)!==null&&ro!==void 0?ro:!1},useMultiAsset=({multiAssetOverride:Xr,multiAssetSettings:eo})=>Xr!==void 0?Xr:eo??!0,useParentDynamicContextGuard=()=>{if(reactExports.useContext(DynamicContext))throw new Error("DynamicContextProvider should not be nested. Please wrap your application in a single DynamicContextProvider.")},useShowFiat=({showFiatOverride:Xr,showFiatSettings:eo})=>Xr!==void 0?Xr:eo??!0,isAuthenticatedWithAWallet=Xr=>{const eo=Xr.verifiedCredentials.find(to=>to.id===Xr.lastVerifiedCredentialId);return(eo==null?void 0:eo.format)===JwtVerifiedCredentialFormatEnum.Blockchain},useCustomerCallbacks=({callbacks:{onAuthSuccess:Xr,onUserProfileUpdate:eo},handleLogOut:to,primaryWallet:ro,user:no,isAuthenticated:io})=>{const[oo,ao]=reactExports.useState([]),so=reactExports.useCallback((lo,fo)=>{switch(lo==null?void 0:lo.callback){case"authSuccess":{try{Xr==null||Xr({handleLogOut:to,isAuthenticated:io,primaryWallet:ro,user:fo}),dynamicEvents.emit("triggerSessionValidation")}catch(ho){logger$8.error("Error calling onAuthSuccess: ",ho)}break}case"userProfileUpdate":{try{eo==null||eo(fo)}catch(ho){logger$8.error("Error calling userProfileUpdate: ",ho)}break}}},[to,io,Xr,eo,ro]);return reactExports.useEffect(()=>{!oo.length||!no||isAuthenticatedWithAWallet(no)&&!ro||(so(oo[0],no),ao(lo=>{const[fo,...ho]=lo;return fo&&(logger$8.debug("Resolved callback: ",fo.callback),logger$8.debug("Callbacks in queue: ",ho.map(go=>go.callback))),ho}))},[oo,so,ro,no]),{setCallback:reactExports.useCallback((lo,fo)=>{ao(ho=>[...ho,{callback:lo,params:fo}])},[])}},useRegisterStorageService=({storagePostfix:Xr})=>{const eo={clear:()=>{},getItem:()=>null,key:()=>null,length:0,removeItem:()=>{},setItem:()=>null},to=isSSR()?eo:window.localStorage,ro=isSSR()?eo:window.sessionStorage;StorageService.getSourceStorage("localStorage")||StorageService.registerSourceStorage("localStorage",createStorageService({postfix:Xr,storage:to})),StorageService.getSourceStorage("sessionStorage")||StorageService.registerSourceStorage("sessionStorage",createStorageService({postfix:Xr,storage:ro}))};var define_process_env_default$5={};const PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID="2762a57b-faa4-41ce-9f16-abff9300e2c9",DynamicContext=reactExports.createContext(void 0),InnerDynamicContextProvider=({children:Xr,theme:eo,settings:to,locale:ro,enableInstrumentation:no=!1})=>{var io,oo,ao,so,co,lo,fo,ho,go,yo,vo,wo,Eo,ko;const{accessDeniedMessagePrimary:Ao,accessDeniedMessageSecondary:Po,accessDeniedButton:jo,defaultPhoneInputIso2:Mo,apiBaseUrl:No,coinbaseWalletPreference:Do,detectNewWalletsForLinking:Fo=!1,enableConnectOnlyFallback:Xo=!1,deepLinkPreference:Lo="native",bridgeChains:Bo,cssOverrides:xo,defaultNumberOfWalletsToShow:uo=DEFAULT_NUMBER_OF_WALLETS_TO_SHOW,flowNetwork:po,initialAuthenticationMode:bo="connect-and-sign",debugError:_o=!1,displaySiweStatement:$o=!0,newToWeb3WalletChainMap:Co,enableVisitTrackingOnConnectOnly:Ro=!0,environmentId:So,walletsFilter:mo,logLevel:To="WARN",mobileExperience:Vo,notInTheListImageUrl:Zo,onboardingImageUrl:Qo,policiesConsentInnerComponent:qo,customPrivacyPolicy:Ho,privacyPolicyUrl:$a,socialMediaLinkText:zo,socialMediaIconUrl:Ko,socialMediaUrl:_c,customTermsOfServices:Cl,termsOfServiceUrl:ga,toolkitEnabled:El,siweStatement:Al,shadowDOMEnabled:Ol=!0,walletConnectors:Wl,socialProvidersFilter:zl,showLockedWalletView:Tl=!1,walletConnectPreferredChains:Ml,walletConnectorExtensions:ou,recommendedWallets:Vl,handlers:Ll}=to;useRegisterStorageService({storagePostfix:to.localStorageSuffix}),initializeStore({environmentId:So,storageSuffix:to.localStorageSuffix}),setChainInfoOverrides((io=to.overrides)===null||io===void 0?void 0:io.chainDisplayValues);const uu=(oo=to.events)!==null&&oo!==void 0?oo:to.eventsCallbacks,ru=resolveNetworkValidationMode({bridgeChains:to.bridgeChains,networkValidationMode:to.networkValidationMode});let{appLogoUrl:tu="https://demo.dynamic.xyz/assets/dynamic-logo.svg",appName:ku="Dynamic Example"}=to;if(!So)throw new MissingEnvironmentIdError;logger$8.setLogLevel(To),logger$9.setLogLevel(To),So===PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID&&logger$8.warn(`WARNING: DYNAMIC is using a test environment ID ${So}. Please sign up on https://app.dynamic.xyz/ to get your production environment ID.`),ApiEndpoint$1.setBaseUrl((ao=define_process_env_default$5.DYNAMIC_API_BASE_URL)!==null&&ao!==void 0?ao:No);const au=Locale.setup(ro),wl=!!Bo,Jo=getDeepLinkPreference(Lo,wl),{selectedTabIndex:Go,setSelectedTabIndex:$l,selectedTabSettings:Zl,tabsItems:Ul}=useTabState({settingsOverrides:to.overrides}),[Gl,Nu,hu]=useLocalStorage(BRIDGE_ONBOARDING_COMPLETED,!1),[cu,Wu]=reactExports.useState(!1),[mu,yu]=reactExports.useState(!1),[Yu,_u]=reactExports.useState(!1),{user:Il,userWithMissingInfo:Nl}=useUser(),Pl=!!Il;Il?logger$8.setMetaData("user",Il):logger$8.setMetaData("user",void 0);const{consumeNonce:Bl}=useFetchNonce(So),[fu,eu]=reactExports.useState(""),[Xl,$u]=reactExports.useState(""),[Yo,_l,{awaiting_account_switch:[Sl],awaiting_signature:[Wo]}]=useMultiWalletWidgetState(),{settings:xl}=useProjectSettings(),Ql=useNetworkConfigurationsFromProjectSettings({cosmosNetworkOverrides:(so=to.overrides)===null||so===void 0?void 0:so.cosmosNetworks,evmNetworksOverrides:(co=to.overrides)===null||co===void 0?void 0:co.evmNetworks,projectSettings:xl});useSendDynamicProps({environmentId:So,settings:to});const Fl=useMultiWallet({isBridgeFlow:wl,multiWalletOverride:(lo=to.overrides)===null||lo===void 0?void 0:lo.multiWallet,multiWalletSettings:(fo=xl==null?void 0:xl.sdk)===null||fo===void 0?void 0:fo.multiWallet}),Jl=useMultiAsset({multiAssetOverride:(ho=to.overrides)===null||ho===void 0?void 0:ho.multiAsset,multiAssetSettings:(go=xl==null?void 0:xl.sdk)===null||go===void 0?void 0:go.enableMultiAsset}),xu=useShowFiat({showFiatOverride:(yo=to.overrides)===null||yo===void 0?void 0:yo.showFiat,showFiatSettings:(vo=xl==null?void 0:xl.sdk)===null||vo===void 0?void 0:vo.showFiat}),[lu,su]=reactExports.useState(!1),Xu=useWalletBookCdn(),{imageUserInAccessList:ju,imageUserNotInAccessList:zu,displayName:Ku,appLogo:Hu}=(xl==null?void 0:xl.general)||{};tu=Hu||tu,ku=Ku||ku;const[Gu,Zu,Vu]=useEmailLoginState((xl==null?void 0:xl.providers)||[],Il),[Ju,Uu]=useDisplayOrderState(xl),[qu,Mu]=useWalletUiUtils({appLogoUrl:tu,appName:ku,hideEmbeddedWalletTransactionUIs:!(!((Eo=(wo=xl==null?void 0:xl.sdk)===null||wo===void 0?void 0:wo.embeddedWallets)===null||Eo===void 0)&&Eo.showEmbeddedWalletActionsUI)});useCreateWalletConnectorOptions({appLogoUrl:tu,appName:ku,coinbaseWalletPreference:Do,deepLinkPreference:Jo,flowNetwork:po,mobileExperience:Vo,networkConfigurations:Ql,projectSettings:xl,walletBook:Xu,walletConnectPreferredChains:Ml,walletConnectorExtensions:ou,walletConnectorsProp:Wl,walletUiUtils:Mu});const Bu=useWalletConnectorOptions(),[Au,Du]=useLocalStorage(AUTH_MODE,bo),{clearPrimaryWalletId:wu,primaryWalletId:vu,setPrimaryWalletId:Cu}=usePrimaryWalletId({environmentId:So,user:Il}),[Eu,Ru]=reactExports.useState(!1),Lu=!!(Au==="connect-and-sign"?Il:Eu),ep=reactExports.useRef(!1),[rp,ip]=useShowAuthFlow({isAuthenticated:Lu,isMultiWalletEnabled:Fl,isRenderingEmbeddedAuthFlow:ep,setShowDynamicUserProfile:Wu,walletConnectorOptions:Bu}),{connectWallet:np,removeConnectedWalletsInfo:nu,connectedWalletsInfo:lp,getConnectedWalletById:yp,connectedWallets:up,disconnectWallet:op,refreshConnectedWallet:bp}=useConnectWallet({authMode:Au,clearPrimaryWalletId:wu,enableVisitTrackingOnConnectOnly:Ro,environmentId:So,handleConnectedWallet:Ll==null?void 0:Ll.handleConnectedWallet,isBridgeFlow:wl,primaryWalletId:vu,setPrimaryWalletId:Cu,setShowAuthFlow:ip,user:Il,walletConnectorOptions:Bu}),dp=reactExports.useMemo(()=>getMissingChains(Bo,lp),[Bo,lp]),{selectedWalletConnector:Ep,setSelectedWalletConnectorKey:pp}=useSelectedWalletConnector({walletConnectorOptions:Bu}),[wp,Ap]=reactExports.useState(null);useSetWalletConnectorVerifiedCredentials(Il??Nl,Bu),useSetWalletConnectorFetchers(Bu,So);const{primaryWallet:fp,showQrcodeModal:Tp,secondaryWallets:Lp,setPrimaryWallet:zp,setShowQrcodeModal:Hp,wallets:r0}=useWalletConnectors({authMode:Au,canHaveMultipleWalletsConnected:Fl,connectedWallets:up,primaryWalletId:vu,setMultiWalletWidgetState:_l,setPrimaryWalletId:Cu,user:Il||Nl,walletConnectorOptions:Bu});reactExports.useEffect(()=>{Ru(!(dp!=null&&dp.length)&&!!fp)},[dp,fp]);const p0=r0.map(Tu=>Tu.connector);useFetchProjectSettings({environmentId:So});const{getNameService:Em,removeConnectedNameService:A0}=useNameService({currentWallet:fp??up[0],user:Il}),{clearAllWalletConnectSessions:n0}=useClearWalletConnectSessions({connectors:p0}),Pm=useHandleLogout({bridgeChains:Bo,clearAllWalletConnectSessions:n0,clearPrimaryWalletId:wu,connectedWallets:up,environmentId:So,events:uu,initialAuthenticationMode:bo,removeBridgeOnboardingCompleted:hu,removeConnectedNameService:A0,removeConnectedWalletsInfo:nu,removeSessionStorageSessionKeys:()=>{StorageService.removeItem(SECURE_ENCLAVE_WALLET_SESSION_KEYS,SECURE_ENCLAVE_WALLET_SESSION_KEYS_STORAGE_OPTIONS),p0.forEach(Tu=>{isSessionKeyCompatibleWalletConnector(Tu)&&typeof(Tu==null?void 0:Tu.removeSessionKeys)=="function"&&(Tu==null||Tu.removeSessionKeys())})},resetLoginWithEmail:Vu,setAuthMode:Du,setLegacyIsVerifying:su,setMultiWalletWidgetState:_l,setSelectedWalletConnectorKey:pp,setShowAuthFlow:ip,setShowBridgeWidget:yu,setShowDynamicUserProfile:Wu,user:Il,walletConnectors:p0});useValidateSession({environmentId:So,handleLogOut:Pm});const{isLoading:g0}=useResetCookieLocalStorage({environmentId:So,projectSettings:xl,setPrimaryWalletId:Cu}),P0=useGlobalLoading({appName:ku,authMode:Au,connectedInfo:lp[0],connectedWallets:up,enableInstrumentation:no,environmentId:So,isLoadingUserFromCookie:g0,primaryWallet:fp,primaryWalletId:vu,projectSettings:xl,user:Il??Nl,walletBook:Xu});useTieCallbacksToEvents({clientCallbacks:uu,user:Il});const Vm=useHandleUnlinkWallet({environmentId:So,primaryWalletId:vu,secondaryWallets:Lp,verifiedCredentials:(Il==null?void 0:Il.verifiedCredentials)||[]}),{isLoading:y0,network:v0}=useWalletConnectorNetwork(fp==null?void 0:fp.connector);useWalletEventListeners({authMode:Au,detectNewWalletsForLinking:Fo,disconnectWallet:op,handleLogOut:Pm,multiWallet:Fl,multiWalletWidgetState:Yo,primaryWallet:fp,refreshConnectedWallet:bp,secondaryWallets:Lp,selectedWalletConnector:Ep,selectedWalletWithAction:wp,setMultiWalletWidgetState:_l,setPrimaryWalletId:Cu,setSelectedWalletConnectorKey:pp,setSelectedWalletWithAction:Ap,user:Il});const{walletsForChainsMap:Um}=useFetchWalletsForChainsMap(Co);reactExports.useEffect(()=>{initExpirationTime(Pm)},[Pm,Pl]);const{setCallback:b0}=useCustomerCallbacks({callbacks:{onAuthSuccess:uu==null?void 0:uu.onAuthSuccess,onUserProfileUpdate:uu==null?void 0:uu.onUserProfileUpdate},handleLogOut:Pm,isAuthenticated:Pl,primaryWallet:fp,user:Il}),O0=reactExports.useCallback(()=>Tu=>{const{dynamicWagmiSettings:_f}=Tu;_f&&sendDynamicProps(So,{dynamicWagmiSettings:{dynamicWagmiSettings:_f}})},[So]),Pp=reactExports.useCallback(()=>__awaiter$j(void 0,void 0,void 0,function*(){$u(""),su(!1),Il||n0(),_l("idle"),Au!=="connect-only"&&nu(),StorageService.getItem(WALLET_PICKER_SEARCH_KEY)&&StorageService.removeItem(WALLET_PICKER_SEARCH_KEY),StorageService.removeItem(PHANTOM_SIGNATURE_STATE),Ep&&(!fp||fp.connector.key!==Ep.key)&&(yield Ep==null?void 0:Ep.endSession())}),[Il,_l,Au,Ep,fp,n0,nu]),{passkeySuccessPopup:Ip,setPasskeySuccessPopup:Yl}=usePasskeySuccessPopup(),pu=reactExports.useMemo(()=>{var Tu;return{accessDeniedButton:jo,accessDeniedMessagePrimary:Ao,accessDeniedMessageSecondary:Po,accountSwitchState:Sl,appLogoUrl:tu,appName:ku,authMode:Au,authToken:getAuthToken(),authorizationViewDisplayOrder:Ju,awaitingSignatureState:Wo,bridgeChains:Bo,bridgeChainsToConnect:dp,bridgeOnboardingCompleted:Gl,clearStatesOnBackClick:Pp,connectWallet:np,connectedWallets:up,consumeNonce:Bl,cssOverrides:xo,customPrivacyPolicy:Ho,customTermsOfServices:Cl,debugError:_o,defaultNumberOfWalletsToShow:uo,defaultPhoneInputIso2:Mo,desktopUri:Xl,detectNewWalletsForLinking:Fo,disconnectWallet:op,displaySiweStatement:$o,enableConnectOnlyFallback:Xo,environmentId:So,events:uu,getConnectedWalletById:yp,getNameService:Em,handleLogOut:Pm,handleUnlinkWallet:Au==="connect-only"?op:Vm,handlers:Ll,i18nSDKInstance:au,isBridgeFlow:wl,isRenderingEmbeddedAuthFlow:ep,isSingleWalletAccount:Yu,legacyIsVerifying:lu,linkedWallets:Au==="connect-only"||!Il?[]:r0,loadingNetwork:y0,locale:{changeLanguage:Locale.getInstance().changeLanguage},loginWithEmail:Gu,minAuthToken:getMinAuthToken$1(),multiAsset:Jl,multiWallet:Fl,multiWalletWidgetState:Yo,network:v0,networkConfigurations:Ql,networkValidationMode:ru,newToWeb3WalletChainMap:Um,notInTheListImageUrl:zu||Zo,onboardingImageUrl:ju||Qo,overrides:to.overrides,passkeySuccessPopup:Ip,policiesConsentInnerComponent:qo,primaryWallet:fp,primaryWalletId:vu,privacyPolicyUrl:$a,projectSettings:xl,qrcodeUri:fu,recommendedWallets:Vl,redirectUrl:to.redirectUrl,removeBridgeOnboardingCompleted:hu,removeConnectedWalletsInfo:nu,sdkHasLoaded:P0,secondaryWallets:Lp,selectedTabIndex:Go,selectedTabSettings:Zl,selectedWalletConnector:Ep,selectedWalletWithAction:wp,sendWagmiSettings:O0,setAuthMode:Du,setAuthorizationViewDisplayOrder:Uu,setBridgeOnboardingCompleted:Nu,setCallback:b0,setDesktopUri:$u,setIsSingleWalletAccount:_u,setLegacyIsVerifying:su,setLogInWithEmail:Zu,setMultiWalletWidgetState:_l,setPasskeySuccessPopup:Yl,setPrimaryWallet:zp,setPrimaryWalletId:Cu,setQrcodeUri:eu,setSelectedTabIndex:$l,setSelectedWalletConnectorKey:pp,setSelectedWalletWithAction:Ap,setShowAuthFlow:ip,setShowBridgeWidget:yu,setShowDynamicUserProfile:Wu,setShowQrcodeModal:Hp,shadowDOMEnabled:Ol,showAuthFlow:rp,showBridgeWidget:mu,showDynamicUserProfile:cu,showFiat:xu,showLockedWalletView:Tl,showQrcodeModal:Tp,siweStatement:Al,socialMediaIconUrl:((Tu=xl==null?void 0:xl.general)===null||Tu===void 0?void 0:Tu.supportUrls)||Ko,socialMediaLinkText:zo,socialMediaUrl:_c,socialProvidersFilter:zl,socialSettings:to.social,tabsItems:Ul,termsOfServiceUrl:ga,theme:eo,toolkitEnabled:El,user:Il,userWithMissingInfo:Nl,walletConnectorOptions:Bu,walletUiUtils:Mu,walletsFilter:mo}},[jo,Ao,Po,Sl,tu,ku,Au,Ju,Wo,Bo,dp,Gl,Pp,np,up,Bl,xo,Ho,Cl,_o,uo,Mo,Xl,Fo,op,$o,Xo,So,uu,yp,Em,Pm,Vm,Ll,au,wl,Yu,lu,Il,r0,y0,Gu,Jl,Fl,Yo,v0,Ql,ru,Um,zu,Zo,ju,Qo,to.overrides,to.redirectUrl,to.social,Ip,qo,fp,vu,$a,xl,fu,Vl,hu,nu,P0,Lp,Go,Zl,Ep,wp,O0,Du,Uu,Nu,b0,Zu,_l,Yl,zp,Cu,$l,pp,ip,Hp,Ol,rp,mu,cu,xu,Tl,Tp,Al,Ko,zo,_c,zl,Ul,ga,eo,El,Nl,Bu,Mu,mo]);return usePrefetch({as:"image",href:getIconicSpriteUrl$1(),id:"sprite",type:"image/svg+xml"}),usePrefetch({as:"fetch",href:getWalletBookCdnUrl(),id:"wallet-book",type:"application/json"}),usePrefetch({as:"fetch",href:`${ApiEndpoint$1.getBaseUrl()}/sdk/${So}/settings?sdkVersion=${encodeURIComponent(`WalletKit/${VERSION$4}`)}`,id:`project-settings-${So}`,type:"application/json"}),reactExports.useEffect(()=>{!Fl&&Yo!=="awaiting_account_switch"||Il&&Yo!=="idle"&&!cu&&Wu(!0)},[Fl,Yo,cu]),jsxRuntimeExports.jsx(I18nextProvider,{i18n:au,children:jsxRuntimeExports.jsx(DynamicContext.Provider,{value:pu,children:jsxRuntimeExports.jsx(WalletBookContextProvider,{walletBook:Xu,children:jsxRuntimeExports.jsx(ThemeContextProvider,{customerTheme:parseTheme(eo,((ko=xl==null?void 0:xl.design)===null||ko===void 0?void 0:ko.modal)||void 0),designSettings:xl==null?void 0:xl.design,children:jsxRuntimeExports.jsx(LoadingContextProvider,{children:jsxRuntimeExports.jsxs(ViewContextProvider,{initialView:getInitialView({bridgeOnboardingCompleted:Gl,connectedWallets:up,isAuthenticated:Pl||!!fp,isBridgeFlow:wl,isMultiWalletEnabled:Fl}),children:[ru==="always"&&jsxRuntimeExports.jsx(UseNetworkValidation,{}),jsxRuntimeExports.jsx(CaptchaContextProvider,{children:jsxRuntimeExports.jsx(AccountExistsContextProvider,{children:jsxRuntimeExports.jsx(WalletContextProvider,{children:jsxRuntimeExports.jsx(VerificationProvider,{children:jsxRuntimeExports.jsx(PasskeyContextProvider,{children:jsxRuntimeExports.jsx(DynamicWidgetContextProvider,{children:jsxRuntimeExports.jsx(DynamicBridgeWidgetContextProvider,{children:jsxRuntimeExports.jsx(FundingContextProvider,{children:jsxRuntimeExports.jsx(AccessDeniedContextProvider,{children:jsxRuntimeExports.jsx(SendBalanceContextProvider,{children:jsxRuntimeExports.jsx(WalletGroupContextProvider,{children:jsxRuntimeExports.jsx(UserFieldEditorContextProvider,{children:jsxRuntimeExports.jsx(ConnectWithOtpProvider,{children:jsxRuntimeExports.jsx(PhantomRedirectContextProvider,{children:jsxRuntimeExports.jsxs(SocialRedirectContextProvider,{children:[jsxRuntimeExports.jsx(DynamicAuthFlow,{}),jsxRuntimeExports.jsx(Toolkit,{}),jsxRuntimeExports.jsx(FundingWidget,{}),jsxRuntimeExports.jsx(SyncAuthFlow,{}),jsxRuntimeExports.jsx(TelegramAutoLogin,{}),jsxRuntimeExports.jsx(WalletConnectorEvents,{}),qu,jsxRuntimeExports.jsx(ErrorBoundaryExclude,{children:Xr})]})})})})})})})})})})})})})})})]})})})})})})},DynamicContextProvider=Xr=>(Logger$2.setEnvironmentId(Xr.settings.environmentId),Logger$2.setEmitErrors(Xr.emitErrors),useParentDynamicContextGuard(),jsxRuntimeExports.jsx(ReinitializeContextProvider,{onReinitialize:removeStoreInstance,children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(ErrorContextProvider,{children:jsxRuntimeExports.jsx(UserWalletsProvider,{children:jsxRuntimeExports.jsx(FieldsStateProvider,{children:jsxRuntimeExports.jsx(IpConfigurationContextProvider,{children:jsxRuntimeExports.jsx(WidgetRegistryContextProvider,{children:jsxRuntimeExports.jsx(InnerDynamicContextProvider,Object.assign({},Xr))})})})})})})}));assertPackageVersion("@dynamic-labs/sdk-react-core",version$u);function Signup(){const[Xr,eo]=reactExports.useState(1),[to,ro]=reactExports.useState(!1),[no,io]=reactExports.useState(null),[oo,ao]=reactExports.useState([]),[so,co]=reactExports.useState(Array(12).fill("")),{setShowAuthFlow:lo,primaryWallet:fo,handleLogOut:ho}=useDynamicContext(),[go,yo]=reactExports.useState(null),{dispatch:vo}=useGlobalState(),wo=useNavigate();reactExports.useEffect(()=>{if(no!=null&&no.mnemonic){const Do=no.mnemonic.split(" ");co(Do)}},[no]);const Eo=()=>eo(Xr+1),ko=async()=>{if(no){ro(!0);try{await no.registerPushAccount(),vo({type:"INITIALIZE_WALLET",payload:no}),wo("/")}catch(Do){alert(Do)}ro(!1)}},Ao=async()=>{try{const Do=await PushWallet.signUp(config$3.APP_ENV);io(Do),ao(Object.keys(Do.walletToEncDerivedKey))}catch(Do){alert(Do)}},Po=async()=>{const Do=await PushSigner.initialize(fo,"DYNAMIC");await(no==null?void 0:no.connectWalletWithAccount(Do)),ao(Object.keys(no.walletToEncDerivedKey))},jo=()=>jsxRuntimeExports.jsxs("div",{className:"space-y-4 text-center",children:[jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx("button",{onClick:async()=>{yo("mnemonic"),await Ao()},className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64 mx-10",children:"Using Mnemonic"})}),jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsxs("button",{onClick:()=>yo("social"),className:"border border-blue-600 text-blue-600 px-6 py-1 rounded-lg w-64",disabled:!0,children:["Social Signup ",jsxRuntimeExports.jsx("br",{})," Coming Soon 🚀"]})})]}),Mo=()=>{const Do=()=>{const Fo=so.join(" ");navigator.clipboard.writeText(Fo).then(()=>alert("Copied to clipboard")).catch(()=>alert("Failed to copy"))};return jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl mb-6",children:"Store Seed Phrase Safely"}),jsxRuntimeExports.jsx(MnemonicGrid,{words:so,disabled:!0}),jsxRuntimeExports.jsx("button",{className:"border border-blue-600 text-blue-600 px-4 py-2 rounded-lg w-30",onClick:Do,children:"Copy"}),jsxRuntimeExports.jsx("p",{className:"mb-6 mt-20 text-gray-600",children:"Your wallet needs to be registered on the Push network to be able to send transactions on the network."}),jsxRuntimeExports.jsx("button",{className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-40",onClick:Eo,children:"Next"})]})},No=()=>jsxRuntimeExports.jsxs("div",{className:"text-center space-y-6 mt-6",children:[jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center space-y-4",children:fo?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("button",{className:"border border-blue-600 text-blue-600 px-6 py-3 rounded-md",onClick:()=>{ho()},children:["Disconnect ",jsxRuntimeExports.jsx("b",{children:fo.address})]}),jsxRuntimeExports.jsx("button",{className:"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",onClick:Po,children:"Add to Push Account"})]}):jsxRuntimeExports.jsx("button",{className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",onClick:()=>lo(!0),children:"Connect Web3 Account"})}),jsxRuntimeExports.jsx("button",{disabled:to,onClick:ko,className:to?"w-full py-3 bg-grey flex items-center justify-center":"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",children:to?"Registering":jsxRuntimeExports.jsxs("span",{className:"flex items-center",children:[jsxRuntimeExports.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"})}),"Register Push Account"]})})]});return jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"p-8 w-full max-w-4xl",children:[Xr===1&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[!go&&jo(),go==="mnemonic"&&Mo()]}),Xr===2&&jsxRuntimeExports.jsx("div",{className:"space-y-2 text-center",children:oo.map(Do=>jsxRuntimeExports.jsx("div",{className:"inline-flex items-center bg-blue-100 text-blue-800 text-sm font-medium rounded-full px-4 py-2 border border-blue-300",children:jsxRuntimeExports.jsx("span",{className:"font-mono",children:Do})},Do))}),Xr===2&&No()]})})}function Login(){const[Xr,eo]=reactExports.useState(null),[to,ro]=reactExports.useState(Array(12).fill("")),{setShowAuthFlow:no,primaryWallet:io,handleLogOut:oo}=useDynamicContext(),{dispatch:ao}=useGlobalState(),so=useNavigate(),co=(yo,vo)=>{const wo=[...to];wo[yo]=vo,ro(wo)},lo=async()=>{try{let yo;switch(Xr){case"mnemonic":{yo=await PushWallet.logInWithMnemonic(to.join(" "),config$3.APP_ENV);break}case"wallet":{const vo=await PushSigner.initialize(io,"DYNAMIC");yo=await PushWallet.loginWithWallet(vo,config$3.APP_ENV);break}}ao({type:"INITIALIZE_WALLET",payload:yo}),so("/")}catch(yo){alert(yo)}},fo=()=>jsxRuntimeExports.jsxs("div",{className:"space-y-4 text-center",children:[jsxRuntimeExports.jsx("button",{onClick:()=>eo("mnemonic"),className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",children:"Using Mnemonic"}),jsxRuntimeExports.jsx("button",{onClick:()=>eo("wallet"),className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",children:"Using Web3 Account"}),jsxRuntimeExports.jsxs("button",{onClick:()=>eo("social"),className:"border border-blue-600 text-blue-600 px-6 py-1 rounded-lg w-64",disabled:!0,children:["Social Login ",jsxRuntimeExports.jsx("br",{})," Coming Soon 🚀"]})]}),ho=()=>jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(MnemonicGrid,{words:to,disabled:!1,handleMnemonicChange:co}),jsxRuntimeExports.jsxs("button",{onClick:lo,disabled:to.some(yo=>yo===""),className:"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",children:[jsxRuntimeExports.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"})}),"Unlock Push Account"]})]}),go=()=>jsxRuntimeExports.jsxs("div",{className:"text-center space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center space-y-4",children:io?jsxRuntimeExports.jsxs("button",{className:"border border-blue-600 text-blue-600 px-6 py-1 rounded-md",onClick:()=>{oo()},children:["Disconnect ",io.address]}):jsxRuntimeExports.jsx("button",{className:"bg-blue-600 text-white px-6 py-3 rounded-lg w-64",onClick:()=>no(!0),children:"Connect Web3 Account"})}),jsxRuntimeExports.jsxs("button",{onClick:lo,disabled:!io,className:"w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center",children:[jsxRuntimeExports.jsx("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"})}),"Unlock Push Account"]})]});return jsxRuntimeExports.jsx("div",{className:"flex flex-col items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"p-8 w-full max-w-lg",children:[!Xr&&fo(),Xr==="mnemonic"&&ho(),Xr==="wallet"&&go()]})})}const __vite_import_meta_env__={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_DYNAMIC_ENV_ID:"7a6006b6-fa19-4e7a-abcf-34add623dff5",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"};var define_process_env_default$4={};function getAppBasePath(){if(typeof import.meta<"u"&&__vite_import_meta_env__)return"/push-wallet/";if(typeof process$1$1<"u"&&define_process_env_default$4){if(define_process_env_default$4.VITE_DEV_MODE==="preview")return"/push-wallet/pr-preview/";if(define_process_env_default$4.VITE_DEV_MODE==="testing")return"/push-wallet/"}return"/"}function App(){return jsxRuntimeExports.jsx(GlobalProvider,{children:jsxRuntimeExports.jsxs("div",{className:"min-h-screen flex flex-col",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold mt-8 text-center",children:config$3.APP_NAME}),jsxRuntimeExports.jsx("div",{className:"flex-1 flex items-center justify-center",children:jsxRuntimeExports.jsx(BrowserRouter,{basename:getAppBasePath(),children:jsxRuntimeExports.jsxs(Routes,{children:[jsxRuntimeExports.jsx(Route,{path:"/",element:jsxRuntimeExports.jsx(Home,{})}),jsxRuntimeExports.jsx(Route,{path:"login",element:jsxRuntimeExports.jsx(Login,{})}),jsxRuntimeExports.jsx(Route,{path:"signup",element:jsxRuntimeExports.jsx(Signup,{})}),jsxRuntimeExports.jsx(Route,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"/"})})]})})})]})})}var version$j="3.4.4";function __awaiter$i(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,freeSelf=typeof self=="object"&&self&&self.Object===Object&&self,root$1=freeGlobal||freeSelf||Function("return this")();function getValue$1(Xr,eo){return Xr==null?void 0:Xr[eo]}function isHostObject(Xr){var eo=!1;if(Xr!=null&&typeof Xr.toString!="function")try{eo=!!(Xr+"")}catch{}return eo}var funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root$1["__core-js_shared__"],maskSrcKey=function(){var Xr=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return Xr?"Symbol(src)_1."+Xr:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString$1=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol$1=root$1.Symbol;Symbol$1&&Symbol$1.isConcatSpreadable;getNative(root$1,"Map");getNative(Object,"create");function baseIsNative(Xr){if(!isObject$8(Xr)||isMasked(Xr))return!1;var eo=isFunction(Xr)||isHostObject(Xr)?reIsNative:reIsHostCtor;return eo.test(toSource(Xr))}function getNative(Xr,eo){var to=getValue$1(Xr,eo);return baseIsNative(to)?to:void 0}function isMasked(Xr){return!!maskSrcKey&&maskSrcKey in Xr}function toSource(Xr){if(Xr!=null){try{return funcToString.call(Xr)}catch{}try{return Xr+""}catch{}}return""}function isFunction(Xr){var eo=isObject$8(Xr)?objectToString$1.call(Xr):"";return eo==funcTag||eo==genTag}function isObject$8(Xr){var eo=typeof Xr;return!!Xr&&(eo=="object"||eo=="function")}var store2;function getGlobalMessage(Xr){return store2==null?void 0:store2.get(Xr)}var store3;function getSchemaMessage(Xr){return store3==null?void 0:store3.get(Xr)}var store4;function getSpecificMessage(Xr,eo){var to;return(to=store4==null?void 0:store4.get(Xr))==null?void 0:to.get(eo)}function _stringify(Xr){var to,ro;let eo=typeof Xr;return eo==="object"&&(eo=(Xr&&((ro=(to=Object.getPrototypeOf(Xr))==null?void 0:to.constructor)==null?void 0:ro.name))??"null"),eo==="string"?`"${Xr}"`:eo==="number"||eo==="bigint"||eo==="boolean"?`${Xr}`:eo}function _addIssue(Xr,eo,to,ro,no){const io=no&&"input"in no?no.input:to.value,oo=(no==null?void 0:no.expected)??Xr.expects??null,ao=(no==null?void 0:no.received)??_stringify(io),so={kind:Xr.kind,type:Xr.type,input:io,expected:oo,received:ao,message:`Invalid ${eo}: ${oo?`Expected ${oo} but r`:"R"}eceived ${ao}`,requirement:Xr.requirement,path:no==null?void 0:no.path,issues:no==null?void 0:no.issues,lang:ro.lang,abortEarly:ro.abortEarly,abortPipeEarly:ro.abortPipeEarly},co=Xr.kind==="schema",lo=(no==null?void 0:no.message)??Xr.message??getSpecificMessage(Xr.reference,so.lang)??(co?getSchemaMessage(so.lang):null)??ro.message??getGlobalMessage(so.lang);lo&&(so.message=typeof lo=="function"?lo(so):lo),co&&(to.typed=!1),to.issues?to.issues.push(so):to.issues=[so]}function _isValidObjectKey(Xr,eo){return Object.hasOwn(Xr,eo)&&eo!=="__proto__"&&eo!=="prototype"&&eo!=="constructor"}function getDefault(Xr,eo,to){return typeof Xr.default=="function"?Xr.default(eo,to):Xr.default}function is$7(Xr,eo){return!Xr._run({typed:!1,value:eo},{abortEarly:!0}).issues}function array$3(Xr,eo){return{kind:"schema",type:"array",reference:array$3,expects:"Array",async:!1,item:Xr,message:eo,_run(to,ro){var io;const no=to.value;if(Array.isArray(no)){to.typed=!0,to.value=[];for(let oo=0;ooisNaN(+ro)).map(([,ro])=>ro);return{kind:"schema",type:"enum",reference:enum_,expects:to.map(_stringify).join(" | ")||"never",async:!1,enum:Xr,options:to,message:eo,_run(ro,no){return this.options.includes(ro.value)?ro.typed=!0:_addIssue(this,"type",ro,no),ro}}}function literal$3(Xr,eo){return{kind:"schema",type:"literal",reference:literal$3,expects:_stringify(Xr),async:!1,literal:Xr,message:eo,_run(to,ro){return to.value===this.literal?to.typed=!0:_addIssue(this,"type",to,ro),to}}}function looseObject(Xr,eo){return{kind:"schema",type:"loose_object",reference:looseObject,expects:"Object",async:!1,entries:Xr,message:eo,_run(to,ro){var io;const no=to.value;if(no&&typeof no=="object"){to.typed=!0,to.value={};for(const oo in this.entries){const ao=no[oo],so=this.entries[oo]._run({typed:!1,value:ao},ro);if(so.issues){const co={type:"object",origin:"value",input:no,key:oo,value:ao};for(const lo of so.issues)lo.path?lo.path.unshift(co):lo.path=[co],(io=to.issues)==null||io.push(lo);if(to.issues||(to.issues=so.issues),ro.abortEarly){to.typed=!1;break}}so.typed||(to.typed=!1),(so.value!==void 0||oo in no)&&(to.value[oo]=so.value)}if(!to.issues||!ro.abortEarly)for(const oo in no)_isValidObjectKey(no,oo)&&!(oo in this.entries)&&(to.value[oo]=no[oo])}else _addIssue(this,"type",to,ro);return to}}}function nonOptional(Xr,eo){return{kind:"schema",type:"non_optional",reference:nonOptional,expects:"!undefined",async:!1,wrapped:Xr,message:eo,_run(to,ro){return to.value===void 0?(_addIssue(this,"type",to,ro),to):this.wrapped._run(to,ro)}}}function null_(Xr){return{kind:"schema",type:"null",reference:null_,expects:"null",async:!1,message:Xr,_run(eo,to){return eo.value===null?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function nullish(Xr,...eo){const to={kind:"schema",type:"nullish",reference:nullish,expects:`${Xr.expects} | null | undefined`,async:!1,wrapped:Xr,_run(ro,no){return(ro.value===null||ro.value===void 0)&&("default"in this&&(ro.value=getDefault(this,ro,no)),ro.value===null||ro.value===void 0)?(ro.typed=!0,ro):this.wrapped._run(ro,no)}};return 0 in eo&&(to.default=eo[0]),to}function number$4(Xr){return{kind:"schema",type:"number",reference:number$4,expects:"number",async:!1,message:Xr,_run(eo,to){return typeof eo.value=="number"&&!isNaN(eo.value)?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function object(Xr,eo){return{kind:"schema",type:"object",reference:object,expects:"Object",async:!1,entries:Xr,message:eo,_run(to,ro){var io;const no=to.value;if(no&&typeof no=="object"){to.typed=!0,to.value={};for(const oo in this.entries){const ao=no[oo],so=this.entries[oo]._run({typed:!1,value:ao},ro);if(so.issues){const co={type:"object",origin:"value",input:no,key:oo,value:ao};for(const lo of so.issues)lo.path?lo.path.unshift(co):lo.path=[co],(io=to.issues)==null||io.push(lo);if(to.issues||(to.issues=so.issues),ro.abortEarly){to.typed=!1;break}}so.typed||(to.typed=!1),(so.value!==void 0||oo in no)&&(to.value[oo]=so.value)}}else _addIssue(this,"type",to,ro);return to}}}function optional$4(Xr,...eo){const to={kind:"schema",type:"optional",reference:optional$4,expects:`${Xr.expects} | undefined`,async:!1,wrapped:Xr,_run(ro,no){return ro.value===void 0&&("default"in this&&(ro.value=getDefault(this,ro,no)),ro.value===void 0)?(ro.typed=!0,ro):this.wrapped._run(ro,no)}};return 0 in eo&&(to.default=eo[0]),to}function picklist(Xr,eo){return{kind:"schema",type:"picklist",reference:picklist,expects:Xr.map(_stringify).join(" | ")||"never",async:!1,options:Xr,message:eo,_run(to,ro){return this.options.includes(to.value)?to.typed=!0:_addIssue(this,"type",to,ro),to}}}function string$4(Xr){return{kind:"schema",type:"string",reference:string$4,expects:"string",async:!1,message:Xr,_run(eo,to){return typeof eo.value=="string"?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function undefined_(Xr){return{kind:"schema",type:"undefined",reference:undefined_,expects:"undefined",async:!1,message:Xr,_run(eo,to){return eo.value===void 0?eo.typed=!0:_addIssue(this,"type",eo,to),eo}}}function _subIssues(Xr){let eo;if(Xr)for(const to of Xr)eo?eo.push(...to.issues):eo=to.issues;return eo}function union$3(Xr,eo){return{kind:"schema",type:"union",reference:union$3,expects:[...new Set(Xr.map(to=>to.expects))].join(" | ")||"never",async:!1,options:Xr,message:eo,_run(to,ro){let no,io,oo;for(const ao of this.options){const so=ao._run({typed:!1,value:to.value},ro);if(so.typed)if(so.issues)io?io.push(so):io=[so];else{no=so;break}else oo?oo.push(so):oo=[so]}if(no)return no;if(io){if(io.length===1)return io[0];_addIssue(this,"type",to,ro,{issues:_subIssues(io)}),to.typed=!0}else{if((oo==null?void 0:oo.length)===1)return oo[0];_addIssue(this,"type",to,ro,{issues:_subIssues(oo)})}return to}}}function unknown$3(){return{kind:"schema",type:"unknown",reference:unknown$3,expects:"unknown",async:!1,_run(Xr){return Xr.typed=!0,Xr}}}var lib$2={},signer={},base64Url={},base64Js={};base64Js.byteLength=byteLength;base64Js.toByteArray=toByteArray;base64Js.fromByteArray=fromByteArray;var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i$6=0,len=code.length;i$60)throw new Error("Invalid string. Length must be a multiple of 4");var to=Xr.indexOf("=");to===-1&&(to=eo);var ro=to===eo?0:4-to%4;return[to,ro]}function byteLength(Xr){var eo=getLens(Xr),to=eo[0],ro=eo[1];return(to+ro)*3/4-ro}function _byteLength(Xr,eo,to){return(eo+to)*3/4-to}function toByteArray(Xr){var eo,to=getLens(Xr),ro=to[0],no=to[1],io=new Arr(_byteLength(Xr,ro,no)),oo=0,ao=no>0?ro-4:ro,so;for(so=0;so>16&255,io[oo++]=eo>>8&255,io[oo++]=eo&255;return no===2&&(eo=revLookup[Xr.charCodeAt(so)]<<2|revLookup[Xr.charCodeAt(so+1)]>>4,io[oo++]=eo&255),no===1&&(eo=revLookup[Xr.charCodeAt(so)]<<10|revLookup[Xr.charCodeAt(so+1)]<<4|revLookup[Xr.charCodeAt(so+2)]>>2,io[oo++]=eo>>8&255,io[oo++]=eo&255),io}function tripletToBase64(Xr){return lookup[Xr>>18&63]+lookup[Xr>>12&63]+lookup[Xr>>6&63]+lookup[Xr&63]}function encodeChunk(Xr,eo,to){for(var ro,no=[],io=eo;ioao?ao:oo+io));return ro===1?(eo=Xr[to-1],no.push(lookup[eo>>2]+lookup[eo<<4&63]+"==")):ro===2&&(eo=(Xr[to-2]<<8)+Xr[to-1],no.push(lookup[eo>>10]+lookup[eo>>4&63]+lookup[eo<<2&63]+"=")),no.join("")}Object.defineProperty(base64Url,"__esModule",{value:!0});base64Url.decode=base64Url.encode=base64Url.unescape=base64Url.escape=base64Url.pad=void 0;const base64_js_1$1=base64Js;function pad(Xr){return`${Xr}${"=".repeat(4-(Xr.length%4||4))}`}base64Url.pad=pad;function escape(Xr){return Xr.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}base64Url.escape=escape;function unescape$1(Xr){return pad(Xr).replace(/-/g,"+").replace(/_/g,"/")}base64Url.unescape=unescape$1;function encode$n(Xr){return escape((0,base64_js_1$1.fromByteArray)(new TextEncoder().encode(Xr)))}base64Url.encode=encode$n;function decode$q(Xr){return new TextDecoder().decode((0,base64_js_1$1.toByteArray)(pad(unescape$1(Xr))))}base64Url.decode=decode$q;var cryptoClients={},secp256k1$1={};const require$$0$a=getAugmentedNamespace(hmac$5);var lib$1={},cryptoBrowserify={},browser$g={exports:{}},safeBuffer$1={exports:{}};const require$$0$9=getAugmentedNamespace(dist$2);/*! safe-buffer. MIT License. Feross Aboukhadijeh */(function(Xr,eo){var to=require$$0$9,ro=to.Buffer;function no(oo,ao){for(var so in oo)ao[so]=oo[so]}ro.from&&ro.alloc&&ro.allocUnsafe&&ro.allocUnsafeSlow?Xr.exports=to:(no(to,eo),eo.Buffer=io);function io(oo,ao,so){return ro(oo,ao,so)}io.prototype=Object.create(ro.prototype),no(ro,io),io.from=function(oo,ao,so){if(typeof oo=="number")throw new TypeError("Argument must not be a number");return ro(oo,ao,so)},io.alloc=function(oo,ao,so){if(typeof oo!="number")throw new TypeError("Argument must be a number");var co=ro(oo);return ao!==void 0?typeof so=="string"?co.fill(ao,so):co.fill(ao):co.fill(0),co},io.allocUnsafe=function(oo){if(typeof oo!="number")throw new TypeError("Argument must be a number");return ro(oo)},io.allocUnsafeSlow=function(oo){if(typeof oo!="number")throw new TypeError("Argument must be a number");return to.SlowBuffer(oo)}})(safeBuffer$1,safeBuffer$1.exports);var safeBufferExports=safeBuffer$1.exports,hasRequiredBrowser$b;function requireBrowser$b(){if(hasRequiredBrowser$b)return browser$g.exports;hasRequiredBrowser$b=1;var Xr=65536,eo=4294967295;function to(){throw new Error(`Secure random number generation is not supported by this browser. Use Chrome, Firefox or Internet Explorer 11`)}var ro=safeBufferExports.Buffer,no=commonjsGlobal.crypto||commonjsGlobal.msCrypto;no&&no.getRandomValues?browser$g.exports=io:browser$g.exports=to;function io(oo,ao){if(oo>eo)throw new RangeError("requested too many random bytes");var so=ro.allocUnsafe(oo);if(oo>0)if(oo>Xr)for(var co=0;co0&&(oo=to[0]),oo instanceof Error)throw oo;var ao=new Error("Unhandled error."+(oo?" ("+oo.message+")":""));throw ao.context=oo,ao}var so=io[eo];if(so===void 0)return!1;if(typeof so=="function")ReflectApply(so,this,to);else for(var co=so.length,lo=arrayClone(so,co),ro=0;ro0&&oo.length>no&&!oo.warned){oo.warned=!0;var ao=new Error("Possible EventEmitter memory leak detected. "+oo.length+" "+String(eo)+" listeners added. Use emitter.setMaxListeners() to increase limit");ao.name="MaxListenersExceededWarning",ao.emitter=Xr,ao.type=eo,ao.count=oo.length,ProcessEmitWarning(ao)}return Xr}EventEmitter.prototype.addListener=function(eo,to){return _addListener(this,eo,to,!1)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function(eo,to){return _addListener(this,eo,to,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(Xr,eo,to){var ro={fired:!1,wrapFn:void 0,target:Xr,type:eo,listener:to},no=onceWrapper.bind(ro);return no.listener=to,ro.wrapFn=no,no}EventEmitter.prototype.once=function(eo,to){return checkListener(to),this.on(eo,_onceWrap(this,eo,to)),this};EventEmitter.prototype.prependOnceListener=function(eo,to){return checkListener(to),this.prependListener(eo,_onceWrap(this,eo,to)),this};EventEmitter.prototype.removeListener=function(eo,to){var ro,no,io,oo,ao;if(checkListener(to),no=this._events,no===void 0)return this;if(ro=no[eo],ro===void 0)return this;if(ro===to||ro.listener===to)--this._eventsCount===0?this._events=Object.create(null):(delete no[eo],no.removeListener&&this.emit("removeListener",eo,ro.listener||to));else if(typeof ro!="function"){for(io=-1,oo=ro.length-1;oo>=0;oo--)if(ro[oo]===to||ro[oo].listener===to){ao=ro[oo].listener,io=oo;break}if(io<0)return this;io===0?ro.shift():spliceOne(ro,io),ro.length===1&&(no[eo]=ro[0]),no.removeListener!==void 0&&this.emit("removeListener",eo,ao||to)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function(eo){var to,ro,no;if(ro=this._events,ro===void 0)return this;if(ro.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):ro[eo]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete ro[eo]),this;if(arguments.length===0){var io=Object.keys(ro),oo;for(no=0;no=0;no--)this.removeListener(eo,to[no]);return this};function _listeners(Xr,eo,to){var ro=Xr._events;if(ro===void 0)return[];var no=ro[eo];return no===void 0?[]:typeof no=="function"?to?[no.listener||no]:[no]:to?unwrapListeners(no):arrayClone(no,no.length)}EventEmitter.prototype.listeners=function(eo){return _listeners(this,eo,!0)};EventEmitter.prototype.rawListeners=function(eo){return _listeners(this,eo,!1)};EventEmitter.listenerCount=function(Xr,eo){return typeof Xr.listenerCount=="function"?Xr.listenerCount(eo):listenerCount.call(Xr,eo)};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(Xr){var eo=this._events;if(eo!==void 0){var to=eo[Xr];if(typeof to=="function")return 1;if(to!==void 0)return to.length}return 0}EventEmitter.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(Xr,eo){for(var to=new Array(eo),ro=0;ro"u"||!vo?Xr:vo(Uint8Array),ko={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?Xr:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Xr:ArrayBuffer,"%ArrayIteratorPrototype%":go&&vo?vo([][Symbol.iterator]()):Xr,"%AsyncFromSyncIteratorPrototype%":Xr,"%AsyncFunction%":wo,"%AsyncGenerator%":wo,"%AsyncGeneratorFunction%":wo,"%AsyncIteratorPrototype%":wo,"%Atomics%":typeof Atomics>"u"?Xr:Atomics,"%BigInt%":typeof BigInt>"u"?Xr:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Xr:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Xr:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Xr:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":eo,"%eval%":eval,"%EvalError%":to,"%Float32Array%":typeof Float32Array>"u"?Xr:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Xr:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Xr:FinalizationRegistry,"%Function%":so,"%GeneratorFunction%":wo,"%Int8Array%":typeof Int8Array>"u"?Xr:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Xr:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Xr:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":go&&vo?vo(vo([][Symbol.iterator]())):Xr,"%JSON%":typeof JSON=="object"?JSON:Xr,"%Map%":typeof Map>"u"?Xr:Map,"%MapIteratorPrototype%":typeof Map>"u"||!go||!vo?Xr:vo(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Xr:Promise,"%Proxy%":typeof Proxy>"u"?Xr:Proxy,"%RangeError%":ro,"%ReferenceError%":no,"%Reflect%":typeof Reflect>"u"?Xr:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Xr:Set,"%SetIteratorPrototype%":typeof Set>"u"||!go||!vo?Xr:vo(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Xr:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":go&&vo?vo(""[Symbol.iterator]()):Xr,"%Symbol%":go?Symbol:Xr,"%SyntaxError%":io,"%ThrowTypeError%":ho,"%TypedArray%":Eo,"%TypeError%":oo,"%Uint8Array%":typeof Uint8Array>"u"?Xr:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Xr:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Xr:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Xr:Uint32Array,"%URIError%":ao,"%WeakMap%":typeof WeakMap>"u"?Xr:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Xr:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Xr:WeakSet};if(vo)try{null.error}catch(_o){var Ao=vo(vo(_o));ko["%Error.prototype%"]=Ao}var Po=function _o($o){var Co;if($o==="%AsyncFunction%")Co=co("async function () {}");else if($o==="%GeneratorFunction%")Co=co("function* () {}");else if($o==="%AsyncGeneratorFunction%")Co=co("async function* () {}");else if($o==="%AsyncGenerator%"){var Ro=_o("%AsyncGeneratorFunction%");Ro&&(Co=Ro.prototype)}else if($o==="%AsyncIteratorPrototype%"){var So=_o("%AsyncGenerator%");So&&vo&&(Co=vo(So.prototype))}return ko[$o]=Co,Co},jo={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Mo=requireFunctionBind(),No=requireHasown(),Do=Mo.call(Function.call,Array.prototype.concat),Fo=Mo.call(Function.apply,Array.prototype.splice),Xo=Mo.call(Function.call,String.prototype.replace),Lo=Mo.call(Function.call,String.prototype.slice),Bo=Mo.call(Function.call,RegExp.prototype.exec),xo=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,uo=/\\(\\)?/g,po=function($o){var Co=Lo($o,0,1),Ro=Lo($o,-1);if(Co==="%"&&Ro!=="%")throw new io("invalid intrinsic syntax, expected closing `%`");if(Ro==="%"&&Co!=="%")throw new io("invalid intrinsic syntax, expected opening `%`");var So=[];return Xo($o,xo,function(mo,To,Vo,Zo){So[So.length]=Vo?Xo(Zo,uo,"$1"):To||mo}),So},bo=function($o,Co){var Ro=$o,So;if(No(jo,Ro)&&(So=jo[Ro],Ro="%"+So[0]+"%"),No(ko,Ro)){var mo=ko[Ro];if(mo===wo&&(mo=Po(Ro)),typeof mo>"u"&&!Co)throw new oo("intrinsic "+$o+" exists, but is not available. Please file an issue!");return{alias:So,name:Ro,value:mo}}throw new io("intrinsic "+$o+" does not exist!")};return getIntrinsic=function($o,Co){if(typeof $o!="string"||$o.length===0)throw new oo("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof Co!="boolean")throw new oo('"allowMissing" argument must be a boolean');if(Bo(/^%?[^%]*%?$/,$o)===null)throw new io("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var Ro=po($o),So=Ro.length>0?Ro[0]:"",mo=bo("%"+So+"%",Co),To=mo.name,Vo=mo.value,Zo=!1,Qo=mo.alias;Qo&&(So=Qo[0],Fo(Ro,Do([0,1],Qo)));for(var qo=1,Ho=!0;qo=Ro.length){var _c=lo(Vo,$a);Ho=!!_c,Ho&&"get"in _c&&!("originalValue"in _c.get)?Vo=_c.get:Vo=Vo[$a]}else Ho=No(Vo,$a),Vo=Vo[$a];Ho&&!Zo&&(ko[To]=Vo)}}return Vo},getIntrinsic}var callBind={exports:{}},esDefineProperty,hasRequiredEsDefineProperty;function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var Xr=requireGetIntrinsic(),eo=Xr("%Object.defineProperty%",!0)||!1;if(eo)try{eo({},"a",{value:1})}catch{eo=!1}return esDefineProperty=eo,esDefineProperty}var gopd,hasRequiredGopd;function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var Xr=requireGetIntrinsic(),eo=Xr("%Object.getOwnPropertyDescriptor%",!0);if(eo)try{eo([],"length")}catch{eo=null}return gopd=eo,gopd}var defineDataProperty,hasRequiredDefineDataProperty;function requireDefineDataProperty(){if(hasRequiredDefineDataProperty)return defineDataProperty;hasRequiredDefineDataProperty=1;var Xr=requireEsDefineProperty(),eo=requireSyntax(),to=requireType(),ro=requireGopd();return defineDataProperty=function(io,oo,ao){if(!io||typeof io!="object"&&typeof io!="function")throw new to("`obj` must be an object or a function`");if(typeof oo!="string"&&typeof oo!="symbol")throw new to("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new to("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new to("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new to("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new to("`loose`, if provided, must be a boolean");var so=arguments.length>3?arguments[3]:null,co=arguments.length>4?arguments[4]:null,lo=arguments.length>5?arguments[5]:null,fo=arguments.length>6?arguments[6]:!1,ho=!!ro&&ro(io,oo);if(Xr)Xr(io,oo,{configurable:lo===null&&ho?ho.configurable:!lo,enumerable:so===null&&ho?ho.enumerable:!so,value:ao,writable:co===null&&ho?ho.writable:!co});else if(fo||!so&&!co&&!lo)io[oo]=ao;else throw new eo("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},defineDataProperty}var hasPropertyDescriptors_1,hasRequiredHasPropertyDescriptors;function requireHasPropertyDescriptors(){if(hasRequiredHasPropertyDescriptors)return hasPropertyDescriptors_1;hasRequiredHasPropertyDescriptors=1;var Xr=requireEsDefineProperty(),eo=function(){return!!Xr};return eo.hasArrayLengthDefineBug=function(){if(!Xr)return null;try{return Xr([],"length",{value:1}).length!==1}catch{return!0}},hasPropertyDescriptors_1=eo,hasPropertyDescriptors_1}var setFunctionLength,hasRequiredSetFunctionLength;function requireSetFunctionLength(){if(hasRequiredSetFunctionLength)return setFunctionLength;hasRequiredSetFunctionLength=1;var Xr=requireGetIntrinsic(),eo=requireDefineDataProperty(),to=requireHasPropertyDescriptors()(),ro=requireGopd(),no=requireType(),io=Xr("%Math.floor%");return setFunctionLength=function(ao,so){if(typeof ao!="function")throw new no("`fn` is not a function");if(typeof so!="number"||so<0||so>4294967295||io(so)!==so)throw new no("`length` must be a positive 32-bit integer");var co=arguments.length>2&&!!arguments[2],lo=!0,fo=!0;if("length"in ao&&ro){var ho=ro(ao,"length");ho&&!ho.configurable&&(lo=!1),ho&&!ho.writable&&(fo=!1)}return(lo||fo||!co)&&(to?eo(ao,"length",so,!0,!0):eo(ao,"length",so)),ao},setFunctionLength}var hasRequiredCallBind;function requireCallBind(){return hasRequiredCallBind||(hasRequiredCallBind=1,function(Xr){var eo=requireFunctionBind(),to=requireGetIntrinsic(),ro=requireSetFunctionLength(),no=requireType(),io=to("%Function.prototype.apply%"),oo=to("%Function.prototype.call%"),ao=to("%Reflect.apply%",!0)||eo.call(oo,io),so=requireEsDefineProperty(),co=to("%Math.max%");Xr.exports=function(ho){if(typeof ho!="function")throw new no("a function is required");var go=ao(eo,oo,arguments);return ro(go,1+co(0,ho.length-(arguments.length-1)),!0)};var lo=function(){return ao(eo,io,arguments)};so?so(Xr.exports,"apply",{value:lo}):Xr.exports.apply=lo}(callBind)),callBind.exports}var callBound,hasRequiredCallBound;function requireCallBound(){if(hasRequiredCallBound)return callBound;hasRequiredCallBound=1;var Xr=requireGetIntrinsic(),eo=requireCallBind(),to=eo(Xr("String.prototype.indexOf"));return callBound=function(no,io){var oo=Xr(no,!!io);return typeof oo=="function"&&to(no,".prototype.")>-1?eo(oo):oo},callBound}var isArguments,hasRequiredIsArguments;function requireIsArguments(){if(hasRequiredIsArguments)return isArguments;hasRequiredIsArguments=1;var Xr=requireShams()(),eo=requireCallBound(),to=eo("Object.prototype.toString"),ro=function(ao){return Xr&&ao&&typeof ao=="object"&&Symbol.toStringTag in ao?!1:to(ao)==="[object Arguments]"},no=function(ao){return ro(ao)?!0:ao!==null&&typeof ao=="object"&&typeof ao.length=="number"&&ao.length>=0&&to(ao)!=="[object Array]"&&to(ao.callee)==="[object Function]"},io=function(){return ro(arguments)}();return ro.isLegacyArguments=no,isArguments=io?ro:no,isArguments}var isGeneratorFunction,hasRequiredIsGeneratorFunction;function requireIsGeneratorFunction(){if(hasRequiredIsGeneratorFunction)return isGeneratorFunction;hasRequiredIsGeneratorFunction=1;var Xr=Object.prototype.toString,eo=Function.prototype.toString,to=/^\s*(?:function)?\*/,ro=requireShams()(),no=Object.getPrototypeOf,io=function(){if(!ro)return!1;try{return Function("return function*() {}")()}catch{}},oo;return isGeneratorFunction=function(so){if(typeof so!="function")return!1;if(to.test(eo.call(so)))return!0;if(!ro){var co=Xr.call(so);return co==="[object GeneratorFunction]"}if(!no)return!1;if(typeof oo>"u"){var lo=io();oo=lo?no(lo):!1}return no(so)===oo},isGeneratorFunction}var isCallable,hasRequiredIsCallable;function requireIsCallable(){if(hasRequiredIsCallable)return isCallable;hasRequiredIsCallable=1;var Xr=Function.prototype.toString,eo=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,to,ro;if(typeof eo=="function"&&typeof Object.defineProperty=="function")try{to=Object.defineProperty({},"length",{get:function(){throw ro}}),ro={},eo(function(){throw 42},null,to)}catch(ko){ko!==ro&&(eo=null)}else eo=null;var no=/^\s*class\b/,io=function(Ao){try{var Po=Xr.call(Ao);return no.test(Po)}catch{return!1}},oo=function(Ao){try{return io(Ao)?!1:(Xr.call(Ao),!0)}catch{return!1}},ao=Object.prototype.toString,so="[object Object]",co="[object Function]",lo="[object GeneratorFunction]",fo="[object HTMLAllCollection]",ho="[object HTML document.all class]",go="[object HTMLCollection]",yo=typeof Symbol=="function"&&!!Symbol.toStringTag,vo=!(0 in[,]),wo=function(){return!1};if(typeof document=="object"){var Eo=document.all;ao.call(Eo)===ao.call(document.all)&&(wo=function(Ao){if((vo||!Ao)&&(typeof Ao>"u"||typeof Ao=="object"))try{var Po=ao.call(Ao);return(Po===fo||Po===ho||Po===go||Po===so)&&Ao("")==null}catch{}return!1})}return isCallable=eo?function(Ao){if(wo(Ao))return!0;if(!Ao||typeof Ao!="function"&&typeof Ao!="object")return!1;try{eo(Ao,null,to)}catch(Po){if(Po!==ro)return!1}return!io(Ao)&&oo(Ao)}:function(Ao){if(wo(Ao))return!0;if(!Ao||typeof Ao!="function"&&typeof Ao!="object")return!1;if(yo)return oo(Ao);if(io(Ao))return!1;var Po=ao.call(Ao);return Po!==co&&Po!==lo&&!/^\[object HTML/.test(Po)?!1:oo(Ao)},isCallable}var forEach_1,hasRequiredForEach;function requireForEach(){if(hasRequiredForEach)return forEach_1;hasRequiredForEach=1;var Xr=requireIsCallable(),eo=Object.prototype.toString,to=Object.prototype.hasOwnProperty,ro=function(so,co,lo){for(var fo=0,ho=so.length;fo=3&&(fo=lo),eo.call(so)==="[object Array]"?ro(so,co,fo):typeof so=="string"?no(so,co,fo):io(so,co,fo)};return forEach_1=oo,forEach_1}var possibleTypedArrayNames,hasRequiredPossibleTypedArrayNames;function requirePossibleTypedArrayNames(){return hasRequiredPossibleTypedArrayNames||(hasRequiredPossibleTypedArrayNames=1,possibleTypedArrayNames=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),possibleTypedArrayNames}var availableTypedArrays,hasRequiredAvailableTypedArrays;function requireAvailableTypedArrays(){if(hasRequiredAvailableTypedArrays)return availableTypedArrays;hasRequiredAvailableTypedArrays=1;var Xr=requirePossibleTypedArrayNames(),eo=typeof globalThis>"u"?commonjsGlobal:globalThis;return availableTypedArrays=function(){for(var ro=[],no=0;no"u"?commonjsGlobal:globalThis,so=eo(),co=ro("String.prototype.slice"),lo=Object.getPrototypeOf,fo=ro("Array.prototype.indexOf",!0)||function(wo,Eo){for(var ko=0;ko-1?Eo:Eo!=="Object"?!1:yo(wo)}return no?go(wo):null},whichTypedArray}var isTypedArray,hasRequiredIsTypedArray;function requireIsTypedArray(){if(hasRequiredIsTypedArray)return isTypedArray;hasRequiredIsTypedArray=1;var Xr=requireWhichTypedArray();return isTypedArray=function(to){return!!Xr(to)},isTypedArray}var hasRequiredTypes$2;function requireTypes$2(){return hasRequiredTypes$2||(hasRequiredTypes$2=1,function(Xr){var eo=requireIsArguments(),to=requireIsGeneratorFunction(),ro=requireWhichTypedArray(),no=requireIsTypedArray();function io(zl){return zl.call.bind(zl)}var oo=typeof BigInt<"u",ao=typeof Symbol<"u",so=io(Object.prototype.toString),co=io(Number.prototype.valueOf),lo=io(String.prototype.valueOf),fo=io(Boolean.prototype.valueOf);if(oo)var ho=io(BigInt.prototype.valueOf);if(ao)var go=io(Symbol.prototype.valueOf);function yo(zl,Tl){if(typeof zl!="object")return!1;try{return Tl(zl),!0}catch{return!1}}Xr.isArgumentsObject=eo,Xr.isGeneratorFunction=to,Xr.isTypedArray=no;function vo(zl){return typeof Promise<"u"&&zl instanceof Promise||zl!==null&&typeof zl=="object"&&typeof zl.then=="function"&&typeof zl.catch=="function"}Xr.isPromise=vo;function wo(zl){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(zl):no(zl)||To(zl)}Xr.isArrayBufferView=wo;function Eo(zl){return ro(zl)==="Uint8Array"}Xr.isUint8Array=Eo;function ko(zl){return ro(zl)==="Uint8ClampedArray"}Xr.isUint8ClampedArray=ko;function Ao(zl){return ro(zl)==="Uint16Array"}Xr.isUint16Array=Ao;function Po(zl){return ro(zl)==="Uint32Array"}Xr.isUint32Array=Po;function jo(zl){return ro(zl)==="Int8Array"}Xr.isInt8Array=jo;function Mo(zl){return ro(zl)==="Int16Array"}Xr.isInt16Array=Mo;function No(zl){return ro(zl)==="Int32Array"}Xr.isInt32Array=No;function Do(zl){return ro(zl)==="Float32Array"}Xr.isFloat32Array=Do;function Fo(zl){return ro(zl)==="Float64Array"}Xr.isFloat64Array=Fo;function Xo(zl){return ro(zl)==="BigInt64Array"}Xr.isBigInt64Array=Xo;function Lo(zl){return ro(zl)==="BigUint64Array"}Xr.isBigUint64Array=Lo;function Bo(zl){return so(zl)==="[object Map]"}Bo.working=typeof Map<"u"&&Bo(new Map);function xo(zl){return typeof Map>"u"?!1:Bo.working?Bo(zl):zl instanceof Map}Xr.isMap=xo;function uo(zl){return so(zl)==="[object Set]"}uo.working=typeof Set<"u"&&uo(new Set);function po(zl){return typeof Set>"u"?!1:uo.working?uo(zl):zl instanceof Set}Xr.isSet=po;function bo(zl){return so(zl)==="[object WeakMap]"}bo.working=typeof WeakMap<"u"&&bo(new WeakMap);function _o(zl){return typeof WeakMap>"u"?!1:bo.working?bo(zl):zl instanceof WeakMap}Xr.isWeakMap=_o;function $o(zl){return so(zl)==="[object WeakSet]"}$o.working=typeof WeakSet<"u"&&$o(new WeakSet);function Co(zl){return $o(zl)}Xr.isWeakSet=Co;function Ro(zl){return so(zl)==="[object ArrayBuffer]"}Ro.working=typeof ArrayBuffer<"u"&&Ro(new ArrayBuffer);function So(zl){return typeof ArrayBuffer>"u"?!1:Ro.working?Ro(zl):zl instanceof ArrayBuffer}Xr.isArrayBuffer=So;function mo(zl){return so(zl)==="[object DataView]"}mo.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&mo(new DataView(new ArrayBuffer(1),0,1));function To(zl){return typeof DataView>"u"?!1:mo.working?mo(zl):zl instanceof DataView}Xr.isDataView=To;var Vo=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function Zo(zl){return so(zl)==="[object SharedArrayBuffer]"}function Qo(zl){return typeof Vo>"u"?!1:(typeof Zo.working>"u"&&(Zo.working=Zo(new Vo)),Zo.working?Zo(zl):zl instanceof Vo)}Xr.isSharedArrayBuffer=Qo;function qo(zl){return so(zl)==="[object AsyncFunction]"}Xr.isAsyncFunction=qo;function Ho(zl){return so(zl)==="[object Map Iterator]"}Xr.isMapIterator=Ho;function $a(zl){return so(zl)==="[object Set Iterator]"}Xr.isSetIterator=$a;function zo(zl){return so(zl)==="[object Generator]"}Xr.isGeneratorObject=zo;function Ko(zl){return so(zl)==="[object WebAssembly.Module]"}Xr.isWebAssemblyCompiledModule=Ko;function _c(zl){return yo(zl,co)}Xr.isNumberObject=_c;function Cl(zl){return yo(zl,lo)}Xr.isStringObject=Cl;function ga(zl){return yo(zl,fo)}Xr.isBooleanObject=ga;function El(zl){return oo&&yo(zl,ho)}Xr.isBigIntObject=El;function Al(zl){return ao&&yo(zl,go)}Xr.isSymbolObject=Al;function Ol(zl){return _c(zl)||Cl(zl)||ga(zl)||El(zl)||Al(zl)}Xr.isBoxedPrimitive=Ol;function Wl(zl){return typeof Uint8Array<"u"&&(So(zl)||Qo(zl))}Xr.isAnyArrayBuffer=Wl,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(zl){Object.defineProperty(Xr,zl,{enumerable:!1,value:function(){throw new Error(zl+" is not supported in userland")}})})}(types$8)),types$8}var isBufferBrowser,hasRequiredIsBufferBrowser;function requireIsBufferBrowser(){return hasRequiredIsBufferBrowser||(hasRequiredIsBufferBrowser=1,isBufferBrowser=function(eo){return eo&&typeof eo=="object"&&typeof eo.copy=="function"&&typeof eo.fill=="function"&&typeof eo.readUInt8=="function"}),isBufferBrowser}var hasRequiredUtil$1;function requireUtil$1(){return hasRequiredUtil$1||(hasRequiredUtil$1=1,function(Xr){var eo={},to=Object.getOwnPropertyDescriptors||function(Vo){for(var Zo=Object.keys(Vo),Qo={},qo=0;qo=qo)return zo;switch(zo){case"%s":return String(Qo[Zo++]);case"%d":return Number(Qo[Zo++]);case"%j":try{return JSON.stringify(Qo[Zo++])}catch{return"[Circular]"}default:return zo}}),$a=Qo[Zo];Zo"u")return function(){return Xr.deprecate(To,Vo).apply(this,arguments)};var Zo=!1;function Qo(){if(!Zo){if(process$1$1.throwDeprecation)throw new Error(Vo);process$1$1.traceDeprecation?console.trace(Vo):console.error(Vo),Zo=!0}return To.apply(this,arguments)}return Qo};var no={},io=/^$/;if(eo.NODE_DEBUG){var oo=eo.NODE_DEBUG;oo=oo.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),io=new RegExp("^"+oo+"$","i")}Xr.debuglog=function(To){if(To=To.toUpperCase(),!no[To])if(io.test(To)){var Vo=process$1$1.pid;no[To]=function(){var Zo=Xr.format.apply(Xr,arguments);console.error("%s %d: %s",To,Vo,Zo)}}else no[To]=function(){};return no[To]};function ao(To,Vo){var Zo={seen:[],stylize:co};return arguments.length>=3&&(Zo.depth=arguments[2]),arguments.length>=4&&(Zo.colors=arguments[3]),ko(Vo)?Zo.showHidden=Vo:Vo&&Xr._extend(Zo,Vo),Do(Zo.showHidden)&&(Zo.showHidden=!1),Do(Zo.depth)&&(Zo.depth=2),Do(Zo.colors)&&(Zo.colors=!1),Do(Zo.customInspect)&&(Zo.customInspect=!0),Zo.colors&&(Zo.stylize=so),fo(Zo,To,Zo.depth)}Xr.inspect=ao,ao.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},ao.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function so(To,Vo){var Zo=ao.styles[Vo];return Zo?"\x1B["+ao.colors[Zo][0]+"m"+To+"\x1B["+ao.colors[Zo][1]+"m":To}function co(To,Vo){return To}function lo(To){var Vo={};return To.forEach(function(Zo,Qo){Vo[Zo]=!0}),Vo}function fo(To,Vo,Zo){if(To.customInspect&&Vo&&xo(Vo.inspect)&&Vo.inspect!==Xr.inspect&&!(Vo.constructor&&Vo.constructor.prototype===Vo)){var Qo=Vo.inspect(Zo,To);return Mo(Qo)||(Qo=fo(To,Qo,Zo)),Qo}var qo=ho(To,Vo);if(qo)return qo;var Ho=Object.keys(Vo),$a=lo(Ho);if(To.showHidden&&(Ho=Object.getOwnPropertyNames(Vo)),Bo(Vo)&&(Ho.indexOf("message")>=0||Ho.indexOf("description")>=0))return go(Vo);if(Ho.length===0){if(xo(Vo)){var zo=Vo.name?": "+Vo.name:"";return To.stylize("[Function"+zo+"]","special")}if(Fo(Vo))return To.stylize(RegExp.prototype.toString.call(Vo),"regexp");if(Lo(Vo))return To.stylize(Date.prototype.toString.call(Vo),"date");if(Bo(Vo))return go(Vo)}var Ko="",_c=!1,Cl=["{","}"];if(Eo(Vo)&&(_c=!0,Cl=["[","]"]),xo(Vo)){var ga=Vo.name?": "+Vo.name:"";Ko=" [Function"+ga+"]"}if(Fo(Vo)&&(Ko=" "+RegExp.prototype.toString.call(Vo)),Lo(Vo)&&(Ko=" "+Date.prototype.toUTCString.call(Vo)),Bo(Vo)&&(Ko=" "+go(Vo)),Ho.length===0&&(!_c||Vo.length==0))return Cl[0]+Ko+Cl[1];if(Zo<0)return Fo(Vo)?To.stylize(RegExp.prototype.toString.call(Vo),"regexp"):To.stylize("[Object]","special");To.seen.push(Vo);var El;return _c?El=yo(To,Vo,Zo,$a,Ho):El=Ho.map(function(Al){return vo(To,Vo,Zo,$a,Al,_c)}),To.seen.pop(),wo(El,Ko,Cl)}function ho(To,Vo){if(Do(Vo))return To.stylize("undefined","undefined");if(Mo(Vo)){var Zo="'"+JSON.stringify(Vo).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return To.stylize(Zo,"string")}if(jo(Vo))return To.stylize(""+Vo,"number");if(ko(Vo))return To.stylize(""+Vo,"boolean");if(Ao(Vo))return To.stylize("null","null")}function go(To){return"["+Error.prototype.toString.call(To)+"]"}function yo(To,Vo,Zo,Qo,qo){for(var Ho=[],$a=0,zo=Vo.length;$a-1&&(Ho?zo=zo.split(` `).map(function(_c){return" "+_c}).join(` @@ -2251,7 +2251,7 @@ PERFORMANCE OF THIS SOFTWARE. `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var payments$3={},embed={},script$1={},bip66$1={};Object.defineProperty(bip66$1,"__esModule",{value:!0});bip66$1.encode=bip66$1.decode=bip66$1.check=void 0;function check$d(Xr){if(Xr.length<8||Xr.length>72||Xr[0]!==48||Xr[1]!==Xr.length-2||Xr[2]!==2)return!1;const eo=Xr[3];if(eo===0||5+eo>=Xr.length||Xr[4+eo]!==2)return!1;const to=Xr[5+eo];return!(to===0||6+eo+to!==Xr.length||Xr[4]&128||eo>1&&Xr[4]===0&&!(Xr[5]&128)||Xr[eo+6]&128||to>1&&Xr[eo+6]===0&&!(Xr[eo+7]&128))}bip66$1.check=check$d;function decode$o(Xr){if(Xr.length<8)throw new Error("DER sequence length is too short");if(Xr.length>72)throw new Error("DER sequence length is too long");if(Xr[0]!==48)throw new Error("Expected DER sequence");if(Xr[1]!==Xr.length-2)throw new Error("DER sequence length is invalid");if(Xr[2]!==2)throw new Error("Expected DER integer");const eo=Xr[3];if(eo===0)throw new Error("R length is zero");if(5+eo>=Xr.length)throw new Error("R length is too long");if(Xr[4+eo]!==2)throw new Error("Expected DER integer (2)");const to=Xr[5+eo];if(to===0)throw new Error("S length is zero");if(6+eo+to!==Xr.length)throw new Error("S length is invalid");if(Xr[4]&128)throw new Error("R value is negative");if(eo>1&&Xr[4]===0&&!(Xr[5]&128))throw new Error("R value excessively padded");if(Xr[eo+6]&128)throw new Error("S value is negative");if(to>1&&Xr[eo+6]===0&&!(Xr[eo+7]&128))throw new Error("S value excessively padded");return{r:Xr.slice(4,4+eo),s:Xr.slice(6+eo)}}bip66$1.decode=decode$o;function encode$m(Xr,eo){const to=Xr.length,ro=eo.length;if(to===0)throw new Error("R length is zero");if(ro===0)throw new Error("S length is zero");if(to>33)throw new Error("R length is too long");if(ro>33)throw new Error("S length is too long");if(Xr[0]&128)throw new Error("R value is negative");if(eo[0]&128)throw new Error("S value is negative");if(to>1&&Xr[0]===0&&!(Xr[1]&128))throw new Error("R value excessively padded");if(ro>1&&eo[0]===0&&!(eo[1]&128))throw new Error("S value excessively padded");const no=Buffer$3.allocUnsafe(6+to+ro);return no[0]=48,no[1]=no.length-2,no[2]=2,no[3]=Xr.length,Xr.copy(no,4),no[4+to]=2,no[5+to]=eo.length,eo.copy(no,6+to),no}bip66$1.encode=encode$m;var ops={};Object.defineProperty(ops,"__esModule",{value:!0});ops.REVERSE_OPS=ops.OPS=void 0;const OPS$8={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};ops.OPS=OPS$8;const REVERSE_OPS={};ops.REVERSE_OPS=REVERSE_OPS;for(const Xr of Object.keys(OPS$8)){const eo=OPS$8[Xr];REVERSE_OPS[eo]=Xr}var push_data={};Object.defineProperty(push_data,"__esModule",{value:!0});push_data.decode=push_data.encode=push_data.encodingLength=void 0;const ops_1=ops;function encodingLength$2(Xr){return XrXr.length)return null;ro=Xr.readUInt8(eo+1),no=2}else if(to===ops_1.OPS.OP_PUSHDATA2){if(eo+3>Xr.length)return null;ro=Xr.readUInt16LE(eo+1),no=3}else{if(eo+5>Xr.length)return null;if(to!==ops_1.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");ro=Xr.readUInt32LE(eo+1),no=5}return{opcode:to,number:ro,size:no}}push_data.decode=decode$n;var script_number={};Object.defineProperty(script_number,"__esModule",{value:!0});script_number.encode=script_number.decode=void 0;function decode$m(Xr,eo,to){eo=eo||4,to=to===void 0?!0:to;const ro=Xr.length;if(ro===0)return 0;if(ro>eo)throw new TypeError("Script number overflow");if(to&&!(Xr[ro-1]&127)&&(ro<=1||!(Xr[ro-2]&128)))throw new Error("Non-minimally encoded script number");if(ro===5){const io=Xr.readUInt32LE(0),oo=Xr.readUInt8(4);return oo&128?-((oo&-129)*4294967296+io):oo*4294967296+io}let no=0;for(let io=0;io2147483647?5:Xr>8388607?4:Xr>32767?3:Xr>127?2:Xr>0?1:0}function encode$k(Xr){let eo=Math.abs(Xr);const to=scriptNumSize(eo),ro=Buffer$3.allocUnsafe(to),no=Xr<0;for(let io=0;io>=8;return ro[to-1]&128?ro.writeUInt8(no?128:0,to-1):no&&(ro[to-1]|=128),ro}script_number.encode=encode$k;var script_signature={},types$7={},types$6={Array:function(Xr){return Xr!=null&&Xr.constructor===Array},Boolean:function(Xr){return typeof Xr=="boolean"},Function:function(Xr){return typeof Xr=="function"},Nil:function(Xr){return Xr==null},Number:function(Xr){return typeof Xr=="number"},Object:function(Xr){return typeof Xr=="object"},String:function(Xr){return typeof Xr=="string"},"":function(){return!0}};types$6.Null=types$6.Nil;for(var typeName$1 in types$6)types$6[typeName$1].toJSON=(function(Xr){return Xr}).bind(null,typeName$1);var native$2=types$6,native$1=native$2;function getTypeName(Xr){return Xr.name||Xr.toString().match(/function (.*?)\s*\(/)[1]}function getValueTypeName$1(Xr){return native$1.Nil(Xr)?"":getTypeName(Xr.constructor)}function getValue(Xr){return native$1.Function(Xr)?"":native$1.String(Xr)?JSON.stringify(Xr):Xr&&native$1.Object(Xr)?"":Xr}function captureStackTrace(Xr,eo){Error.captureStackTrace&&Error.captureStackTrace(Xr,eo)}function tfJSON$1(Xr){return native$1.Function(Xr)?Xr.toJSON?Xr.toJSON():getTypeName(Xr):native$1.Array(Xr)?"Array":Xr&&native$1.Object(Xr)?"Object":Xr!==void 0?Xr:""}function tfErrorString(Xr,eo,to){var ro=getValue(eo);return"Expected "+tfJSON$1(Xr)+", got"+(to!==""?" "+to:"")+(ro!==""?" "+ro:"")}function TfTypeError$1(Xr,eo,to){to=to||getValueTypeName$1(eo),this.message=tfErrorString(Xr,eo,to),captureStackTrace(this,TfTypeError$1),this.__type=Xr,this.__value=eo,this.__valueTypeName=to}TfTypeError$1.prototype=Object.create(Error.prototype);TfTypeError$1.prototype.constructor=TfTypeError$1;function tfPropertyErrorString(Xr,eo,to,ro,no){var io='" of type ';return eo==="key"&&(io='" with key type '),tfErrorString('property "'+tfJSON$1(to)+io+tfJSON$1(Xr),ro,no)}function TfPropertyTypeError$1(Xr,eo,to,ro,no){Xr?(no=no||getValueTypeName$1(ro),this.message=tfPropertyErrorString(Xr,to,eo,ro,no)):this.message='Unexpected property "'+eo+'"',captureStackTrace(this,TfTypeError$1),this.__label=to,this.__property=eo,this.__type=Xr,this.__value=ro,this.__valueTypeName=no}TfPropertyTypeError$1.prototype=Object.create(Error.prototype);TfPropertyTypeError$1.prototype.constructor=TfTypeError$1;function tfCustomError(Xr,eo){return new TfTypeError$1(Xr,{},eo)}function tfSubError$1(Xr,eo,to){return Xr instanceof TfPropertyTypeError$1?(eo=eo+"."+Xr.__property,Xr=new TfPropertyTypeError$1(Xr.__type,eo,Xr.__label,Xr.__value,Xr.__valueTypeName)):Xr instanceof TfTypeError$1&&(Xr=new TfPropertyTypeError$1(Xr.__type,eo,to,Xr.__value,Xr.__valueTypeName)),captureStackTrace(Xr),Xr}var errors$2={TfTypeError:TfTypeError$1,TfPropertyTypeError:TfPropertyTypeError$1,tfCustomError,tfSubError:tfSubError$1,tfJSON:tfJSON$1,getValueTypeName:getValueTypeName$1},extra,hasRequiredExtra;function requireExtra(){if(hasRequiredExtra)return extra;hasRequiredExtra=1;var Xr=native$2,eo=errors$2;function to(Mo){return Buffer$3.isBuffer(Mo)}function ro(Mo){return typeof Mo=="string"&&/^([0-9a-f]{2})+$/i.test(Mo)}function no(Mo,No){var Do=Mo.toJSON();function Fo(Xo){if(!Mo(Xo))return!1;if(Xo.length===No)return!0;throw eo.tfCustomError(Do+"(Length: "+No+")",Do+"(Length: "+Xo.length+")")}return Fo.toJSON=function(){return Do},Fo}var io=no.bind(null,Xr.Array),oo=no.bind(null,to),ao=no.bind(null,ro),so=no.bind(null,Xr.String);function co(Mo,No,Do){Do=Do||Xr.Number;function Fo(Xo,Lo){return Do(Xo,Lo)&&Xo>Mo&&Xo>24===Mo}function go(Mo){return Mo<<16>>16===Mo}function yo(Mo){return(Mo|0)===Mo}function vo(Mo){return typeof Mo=="number"&&Mo>=-lo&&Mo<=lo&&Math.floor(Mo)===Mo}function wo(Mo){return(Mo&255)===Mo}function Eo(Mo){return(Mo&65535)===Mo}function ko(Mo){return Mo>>>0===Mo}function Ao(Mo){return typeof Mo=="number"&&Mo>=0&&Mo<=lo&&Math.floor(Mo)===Mo}var Po={ArrayN:io,Buffer:to,BufferN:oo,Finite:fo,Hex:ro,HexN:ao,Int8:ho,Int16:go,Int32:yo,Int53:vo,Range:co,StringN:so,UInt8:wo,UInt16:Eo,UInt32:ko,UInt53:Ao};for(var jo in Po)Po[jo].toJSON=(function(Mo){return Mo}).bind(null,jo);return extra=Po,extra}var ERRORS=errors$2,NATIVE=native$2,tfJSON=ERRORS.tfJSON,TfTypeError=ERRORS.TfTypeError,TfPropertyTypeError=ERRORS.TfPropertyTypeError,tfSubError=ERRORS.tfSubError,getValueTypeName=ERRORS.getValueTypeName,TYPES={arrayOf:function Xr(eo,to){eo=compile(eo),to=to||{};function ro(no,io){return!NATIVE.Array(no)||NATIVE.Nil(no)||to.minLength!==void 0&&no.lengthto.maxLength||to.length!==void 0&&no.length!==to.length?!1:no.every(function(oo,ao){try{return typeforce$4(eo,oo,io)}catch(so){throw tfSubError(so,ao)}})}return ro.toJSON=function(){var no="["+tfJSON(eo)+"]";return to.length!==void 0?no+="{"+to.length+"}":(to.minLength!==void 0||to.maxLength!==void 0)&&(no+="{"+(to.minLength===void 0?0:to.minLength)+","+(to.maxLength===void 0?1/0:to.maxLength)+"}"),no},ro},maybe:function Xr(eo){eo=compile(eo);function to(ro,no){return NATIVE.Nil(ro)||eo(ro,no,Xr)}return to.toJSON=function(){return"?"+tfJSON(eo)},to},map:function Xr(eo,to){eo=compile(eo),to&&(to=compile(to));function ro(no,io){if(!NATIVE.Object(no)||NATIVE.Nil(no))return!1;for(var oo in no){try{to&&typeforce$4(to,oo,io)}catch(so){throw tfSubError(so,oo,"key")}try{var ao=no[oo];typeforce$4(eo,ao,io)}catch(so){throw tfSubError(so,oo)}}return!0}return to?ro.toJSON=function(){return"{"+tfJSON(to)+": "+tfJSON(eo)+"}"}:ro.toJSON=function(){return"{"+tfJSON(eo)+"}"},ro},object:function Xr(eo){var to={};for(var ro in eo)to[ro]=compile(eo[ro]);function no(io,oo){if(!NATIVE.Object(io)||NATIVE.Nil(io))return!1;var ao;try{for(ao in to){var so=to[ao],co=io[ao];typeforce$4(so,co,oo)}}catch(lo){throw tfSubError(lo,ao)}if(oo){for(ao in io)if(!to[ao])throw new TfPropertyTypeError(void 0,ao)}return!0}return no.toJSON=function(){return tfJSON(to)},no},anyOf:function Xr(){var eo=[].slice.call(arguments).map(compile);function to(ro,no){return eo.some(function(io){try{return typeforce$4(io,ro,no)}catch{return!1}})}return to.toJSON=function(){return eo.map(tfJSON).join("|")},to},allOf:function Xr(){var eo=[].slice.call(arguments).map(compile);function to(ro,no){return eo.every(function(io){try{return typeforce$4(io,ro,no)}catch{return!1}})}return to.toJSON=function(){return eo.map(tfJSON).join(" & ")},to},quacksLike:function Xr(eo){function to(ro){return eo===getValueTypeName(ro)}return to.toJSON=function(){return eo},to},tuple:function Xr(){var eo=[].slice.call(arguments).map(compile);function to(ro,no){return NATIVE.Nil(ro)||NATIVE.Nil(ro.length)||no&&ro.length!==eo.length?!1:eo.every(function(io,oo){try{return typeforce$4(io,ro[oo],no)}catch(ao){throw tfSubError(ao,oo)}})}return to.toJSON=function(){return"("+eo.map(tfJSON).join(", ")+")"},to},value:function Xr(eo){function to(ro){return ro===eo}return to.toJSON=function(){return eo},to}};TYPES.oneOf=TYPES.anyOf;function compile(Xr){if(NATIVE.String(Xr))return Xr[0]==="?"?TYPES.maybe(Xr.slice(1)):NATIVE[Xr]||TYPES.quacksLike(Xr);if(Xr&&NATIVE.Object(Xr)){if(NATIVE.Array(Xr)){if(Xr.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return TYPES.arrayOf(Xr[0])}return TYPES.object(Xr)}else if(NATIVE.Function(Xr))return Xr;return TYPES.value(Xr)}function typeforce$4(Xr,eo,to,ro){if(NATIVE.Function(Xr)){if(Xr(eo,to))return!0;throw new TfTypeError(ro||Xr,eo)}return typeforce$4(compile(Xr),eo,to)}for(var typeName in NATIVE)typeforce$4[typeName]=NATIVE[typeName];for(typeName in TYPES)typeforce$4[typeName]=TYPES[typeName];var EXTRA$1=requireExtra();for(typeName in EXTRA$1)typeforce$4[typeName]=EXTRA$1[typeName];typeforce$4.compile=compile;typeforce$4.TfTypeError=TfTypeError;typeforce$4.TfPropertyTypeError=TfPropertyTypeError;var typeforce_1=typeforce$4;(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.oneOf=Xr.Null=Xr.BufferN=Xr.Function=Xr.UInt32=Xr.UInt8=Xr.tuple=Xr.maybe=Xr.Hex=Xr.Buffer=Xr.String=Xr.Boolean=Xr.Array=Xr.Number=Xr.Hash256bit=Xr.Hash160bit=Xr.Buffer256bit=Xr.isTaptree=Xr.isTapleaf=Xr.TAPLEAF_VERSION_MASK=Xr.Network=Xr.ECPoint=Xr.Satoshi=Xr.Signer=Xr.BIP32Path=Xr.UInt31=Xr.isPoint=Xr.typeforce=void 0;const eo=require$$0$9;Xr.typeforce=typeforce_1;const to=eo.Buffer.alloc(32,0),ro=eo.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function no(go){if(!eo.Buffer.isBuffer(go)||go.length<33)return!1;const yo=go[0],vo=go.slice(1,33);if(vo.compare(to)===0||vo.compare(ro)>=0)return!1;if((yo===2||yo===3)&&go.length===33)return!0;const wo=go.slice(33);return wo.compare(to)===0||wo.compare(ro)>=0?!1:yo===4&&go.length===65}Xr.isPoint=no;const io=Math.pow(2,31)-1;function oo(go){return Xr.typeforce.UInt32(go)&&go<=io}Xr.UInt31=oo;function ao(go){return Xr.typeforce.String(go)&&!!go.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}Xr.BIP32Path=ao,ao.toJSON=()=>"BIP32 derivation path";function so(go){return(Xr.typeforce.Buffer(go.publicKey)||typeof go.getPublicKey=="function")&&typeof go.sign=="function"}Xr.Signer=so;const co=21*1e14;function lo(go){return Xr.typeforce.UInt53(go)&&go<=co}Xr.Satoshi=lo,Xr.ECPoint=Xr.typeforce.quacksLike("Point"),Xr.Network=Xr.typeforce.compile({messagePrefix:Xr.typeforce.oneOf(Xr.typeforce.Buffer,Xr.typeforce.String),bip32:{public:Xr.typeforce.UInt32,private:Xr.typeforce.UInt32},pubKeyHash:Xr.typeforce.UInt8,scriptHash:Xr.typeforce.UInt8,wif:Xr.typeforce.UInt8}),Xr.TAPLEAF_VERSION_MASK=254;function fo(go){return!go||!("output"in go)||!eo.Buffer.isBuffer(go.output)?!1:go.version!==void 0?(go.version&Xr.TAPLEAF_VERSION_MASK)===go.version:!0}Xr.isTapleaf=fo;function ho(go){return(0,Xr.Array)(go)?go.length!==2?!1:go.every(yo=>ho(yo)):fo(go)}Xr.isTaptree=ho,Xr.Buffer256bit=Xr.typeforce.BufferN(32),Xr.Hash160bit=Xr.typeforce.BufferN(20),Xr.Hash256bit=Xr.typeforce.BufferN(32),Xr.Number=Xr.typeforce.Number,Xr.Array=Xr.typeforce.Array,Xr.Boolean=Xr.typeforce.Boolean,Xr.String=Xr.typeforce.String,Xr.Buffer=Xr.typeforce.Buffer,Xr.Hex=Xr.typeforce.Hex,Xr.maybe=Xr.typeforce.maybe,Xr.tuple=Xr.typeforce.tuple,Xr.UInt8=Xr.typeforce.UInt8,Xr.UInt32=Xr.typeforce.UInt32,Xr.Function=Xr.typeforce.Function,Xr.BufferN=Xr.typeforce.BufferN,Xr.Null=Xr.typeforce.Null,Xr.oneOf=Xr.typeforce.oneOf})(types$7);Object.defineProperty(script_signature,"__esModule",{value:!0});script_signature.encode=script_signature.decode=void 0;const bip66=bip66$1,types$5=types$7,{typeforce:typeforce$3}=types$5,ZERO$2=Buffer$3.alloc(1,0);function toDER(Xr){let eo=0;for(;Xr[eo]===0;)++eo;return eo===Xr.length?ZERO$2:(Xr=Xr.slice(eo),Xr[0]&128?Buffer$3.concat([ZERO$2,Xr],1+Xr.length):Xr)}function fromDER(Xr){Xr[0]===0&&(Xr=Xr.slice(1));const eo=Buffer$3.alloc(32,0),to=Math.max(0,32-Xr.length);return Xr.copy(eo,to),eo}function decode$l(Xr){const eo=Xr.readUInt8(Xr.length-1),to=eo&-129;if(to<=0||to>=4)throw new Error("Invalid hashType "+eo);const ro=bip66.decode(Xr.slice(0,-1)),no=fromDER(ro.r),io=fromDER(ro.s);return{signature:Buffer$3.concat([no,io],64),hashType:eo}}script_signature.decode=decode$l;function encode$j(Xr,eo){typeforce$3({signature:types$5.BufferN(64),hashType:types$5.UInt8},{signature:Xr,hashType:eo});const to=eo&-129;if(to<=0||to>=4)throw new Error("Invalid hashType "+eo);const ro=Buffer$3.allocUnsafe(1);ro.writeUInt8(eo,0);const no=toDER(Xr.slice(0,32)),io=toDER(Xr.slice(32,64));return Buffer$3.concat([bip66.encode(no,io),ro])}script_signature.encode=encode$j;(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.signature=Xr.number=Xr.isCanonicalScriptSignature=Xr.isDefinedHashType=Xr.isCanonicalPubKey=Xr.toStack=Xr.fromASM=Xr.toASM=Xr.decompile=Xr.compile=Xr.countNonPushOnlyOPs=Xr.isPushOnly=Xr.OPS=void 0;const eo=bip66$1,to=ops;Object.defineProperty(Xr,"OPS",{enumerable:!0,get:function(){return to.OPS}});const ro=push_data,no=script_number,io=script_signature,oo=types$7,{typeforce:ao}=oo,so=to.OPS.OP_RESERVED;function co(Fo){return oo.Number(Fo)&&(Fo===to.OPS.OP_0||Fo>=to.OPS.OP_1&&Fo<=to.OPS.OP_16||Fo===to.OPS.OP_1NEGATE)}function lo(Fo){return oo.Buffer(Fo)||co(Fo)}function fo(Fo){return oo.Array(Fo)&&Fo.every(lo)}Xr.isPushOnly=fo;function ho(Fo){return Fo.length-Fo.filter(lo).length}Xr.countNonPushOnlyOPs=ho;function go(Fo){if(Fo.length===0)return to.OPS.OP_0;if(Fo.length===1){if(Fo[0]>=1&&Fo[0]<=16)return so+Fo[0];if(Fo[0]===129)return to.OPS.OP_1NEGATE}}function yo(Fo){return Buffer$3.isBuffer(Fo)}function vo(Fo){return oo.Array(Fo)}function wo(Fo){return Buffer$3.isBuffer(Fo)}function Eo(Fo){if(yo(Fo))return Fo;ao(oo.Array,Fo);const Xo=Fo.reduce((xo,uo)=>wo(uo)?uo.length===1&&go(uo)!==void 0?xo+1:xo+ro.encodingLength(uo.length)+uo.length:xo+1,0),Lo=Buffer$3.allocUnsafe(Xo);let Bo=0;if(Fo.forEach(xo=>{if(wo(xo)){const uo=go(xo);if(uo!==void 0){Lo.writeUInt8(uo,Bo),Bo+=1;return}Bo+=ro.encode(Lo,xo.length,Bo),xo.copy(Lo,Bo),Bo+=xo.length}else Lo.writeUInt8(xo,Bo),Bo+=1}),Bo!==Lo.length)throw new Error("Could not decode chunks");return Lo}Xr.compile=Eo;function ko(Fo){if(vo(Fo))return Fo;ao(oo.Buffer,Fo);const Xo=[];let Lo=0;for(;Loto.OPS.OP_0&&Bo<=to.OPS.OP_PUSHDATA4){const xo=ro.decode(Fo,Lo);if(xo===null||(Lo+=xo.size,Lo+xo.number>Fo.length))return null;const uo=Fo.slice(Lo,Lo+xo.number);Lo+=xo.number;const po=go(uo);po!==void 0?Xo.push(po):Xo.push(uo)}else Xo.push(Bo),Lo+=1}return Xo}Xr.decompile=ko;function Ao(Fo){return yo(Fo)&&(Fo=ko(Fo)),Fo.map(Xo=>{if(wo(Xo)){const Lo=go(Xo);if(Lo===void 0)return Xo.toString("hex");Xo=Lo}return to.REVERSE_OPS[Xo]}).join(" ")}Xr.toASM=Ao;function Po(Fo){return ao(oo.String,Fo),Eo(Fo.split(" ").map(Xo=>to.OPS[Xo]!==void 0?to.OPS[Xo]:(ao(oo.Hex,Xo),Buffer$3.from(Xo,"hex"))))}Xr.fromASM=Po;function jo(Fo){return Fo=ko(Fo),ao(fo,Fo),Fo.map(Xo=>wo(Xo)?Xo:Xo===to.OPS.OP_0?Buffer$3.allocUnsafe(0):no.encode(Xo-so))}Xr.toStack=jo;function Mo(Fo){return oo.isPoint(Fo)}Xr.isCanonicalPubKey=Mo;function No(Fo){const Xo=Fo&-129;return Xo>0&&Xo<4}Xr.isDefinedHashType=No;function Do(Fo){return!Buffer$3.isBuffer(Fo)||!No(Fo[Fo.length-1])?!1:eo.check(Fo.slice(0,-1))}Xr.isCanonicalScriptSignature=Do,Xr.number=no,Xr.signature=io})(script$1);var lazy$8={};Object.defineProperty(lazy$8,"__esModule",{value:!0});lazy$8.value=lazy$8.prop=void 0;function prop(Xr,eo,to){Object.defineProperty(Xr,eo,{configurable:!0,enumerable:!0,get(){const ro=to.call(this);return this[eo]=ro,ro},set(ro){Object.defineProperty(this,eo,{configurable:!0,enumerable:!0,value:ro,writable:!0})}})}lazy$8.prop=prop;function value(Xr){let eo;return()=>(eo!==void 0||(eo=Xr()),eo)}lazy$8.value=value;Object.defineProperty(embed,"__esModule",{value:!0});embed.p2data=void 0;const networks_1$8=networks$1,bscript$b=script$1,types_1$9=types$7,lazy$7=lazy$8,OPS$7=bscript$b.OPS;function stacksEqual$4(Xr,eo){return Xr.length!==eo.length?!1:Xr.every((to,ro)=>to.equals(eo[ro]))}function p2data(Xr,eo){if(!Xr.data&&!Xr.output)throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{}),(0,types_1$9.typeforce)({network:types_1$9.typeforce.maybe(types_1$9.typeforce.Object),output:types_1$9.typeforce.maybe(types_1$9.typeforce.Buffer),data:types_1$9.typeforce.maybe(types_1$9.typeforce.arrayOf(types_1$9.typeforce.Buffer))},Xr);const ro={name:"embed",network:Xr.network||networks_1$8.bitcoin};if(lazy$7.prop(ro,"output",()=>{if(Xr.data)return bscript$b.compile([OPS$7.OP_RETURN].concat(Xr.data))}),lazy$7.prop(ro,"data",()=>{if(Xr.output)return bscript$b.decompile(Xr.output).slice(1)}),eo.validate&&Xr.output){const no=bscript$b.decompile(Xr.output);if(no[0]!==OPS$7.OP_RETURN)throw new TypeError("Output is invalid");if(!no.slice(1).every(types_1$9.typeforce.Buffer))throw new TypeError("Output is invalid");if(Xr.data&&!stacksEqual$4(Xr.data,ro.data))throw new TypeError("Data mismatch")}return Object.assign(ro,Xr)}embed.p2data=p2data;var p2ms$1={};Object.defineProperty(p2ms$1,"__esModule",{value:!0});p2ms$1.p2ms=void 0;const networks_1$7=networks$1,bscript$a=script$1,types_1$8=types$7,lazy$6=lazy$8,OPS$6=bscript$a.OPS,OP_INT_BASE=OPS$6.OP_RESERVED;function stacksEqual$3(Xr,eo){return Xr.length!==eo.length?!1:Xr.every((to,ro)=>to.equals(eo[ro]))}function p2ms(Xr,eo){if(!Xr.input&&!Xr.output&&!(Xr.pubkeys&&Xr.m!==void 0)&&!Xr.signatures)throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{});function to(so){return bscript$a.isCanonicalScriptSignature(so)||(eo.allowIncomplete&&so===OPS$6.OP_0)!==void 0}(0,types_1$8.typeforce)({network:types_1$8.typeforce.maybe(types_1$8.typeforce.Object),m:types_1$8.typeforce.maybe(types_1$8.typeforce.Number),n:types_1$8.typeforce.maybe(types_1$8.typeforce.Number),output:types_1$8.typeforce.maybe(types_1$8.typeforce.Buffer),pubkeys:types_1$8.typeforce.maybe(types_1$8.typeforce.arrayOf(types_1$8.isPoint)),signatures:types_1$8.typeforce.maybe(types_1$8.typeforce.arrayOf(to)),input:types_1$8.typeforce.maybe(types_1$8.typeforce.Buffer)},Xr);const no={network:Xr.network||networks_1$7.bitcoin};let io=[],oo=!1;function ao(so){oo||(oo=!0,io=bscript$a.decompile(so),no.m=io[0]-OP_INT_BASE,no.n=io[io.length-2]-OP_INT_BASE,no.pubkeys=io.slice(1,-2))}if(lazy$6.prop(no,"output",()=>{if(Xr.m&&no.n&&Xr.pubkeys)return bscript$a.compile([].concat(OP_INT_BASE+Xr.m,Xr.pubkeys,OP_INT_BASE+no.n,OPS$6.OP_CHECKMULTISIG))}),lazy$6.prop(no,"m",()=>{if(no.output)return ao(no.output),no.m}),lazy$6.prop(no,"n",()=>{if(no.pubkeys)return no.pubkeys.length}),lazy$6.prop(no,"pubkeys",()=>{if(Xr.output)return ao(Xr.output),no.pubkeys}),lazy$6.prop(no,"signatures",()=>{if(Xr.input)return bscript$a.decompile(Xr.input).slice(1)}),lazy$6.prop(no,"input",()=>{if(Xr.signatures)return bscript$a.compile([OPS$6.OP_0].concat(Xr.signatures))}),lazy$6.prop(no,"witness",()=>{if(no.input)return[]}),lazy$6.prop(no,"name",()=>{if(!(!no.m||!no.n))return`p2ms(${no.m} of ${no.n})`}),eo.validate){if(Xr.output){if(ao(Xr.output),!types_1$8.typeforce.Number(io[0]))throw new TypeError("Output is invalid");if(!types_1$8.typeforce.Number(io[io.length-2]))throw new TypeError("Output is invalid");if(io[io.length-1]!==OPS$6.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(no.m<=0||no.n>16||no.m>no.n||no.n!==io.length-3)throw new TypeError("Output is invalid");if(!no.pubkeys.every(so=>(0,types_1$8.isPoint)(so)))throw new TypeError("Output is invalid");if(Xr.m!==void 0&&Xr.m!==no.m)throw new TypeError("m mismatch");if(Xr.n!==void 0&&Xr.n!==no.n)throw new TypeError("n mismatch");if(Xr.pubkeys&&!stacksEqual$3(Xr.pubkeys,no.pubkeys))throw new TypeError("Pubkeys mismatch")}if(Xr.pubkeys){if(Xr.n!==void 0&&Xr.n!==Xr.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(no.n=Xr.pubkeys.length,no.nno.m)throw new TypeError("Too many signatures provided")}if(Xr.input){if(Xr.input[0]!==OPS$6.OP_0)throw new TypeError("Input is invalid");if(no.signatures.length===0||!no.signatures.every(to))throw new TypeError("Input has invalid signature(s)");if(Xr.signatures&&!stacksEqual$3(Xr.signatures,no.signatures))throw new TypeError("Signature mismatch");if(Xr.m!==void 0&&Xr.m!==Xr.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(no,Xr)}p2ms$1.p2ms=p2ms;var p2pk$1={};Object.defineProperty(p2pk$1,"__esModule",{value:!0});p2pk$1.p2pk=void 0;const networks_1$6=networks$1,bscript$9=script$1,types_1$7=types$7,lazy$5=lazy$8,OPS$5=bscript$9.OPS;function p2pk(Xr,eo){if(!Xr.input&&!Xr.output&&!Xr.pubkey&&!Xr.input&&!Xr.signature)throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{}),(0,types_1$7.typeforce)({network:types_1$7.typeforce.maybe(types_1$7.typeforce.Object),output:types_1$7.typeforce.maybe(types_1$7.typeforce.Buffer),pubkey:types_1$7.typeforce.maybe(types_1$7.isPoint),signature:types_1$7.typeforce.maybe(bscript$9.isCanonicalScriptSignature),input:types_1$7.typeforce.maybe(types_1$7.typeforce.Buffer)},Xr);const to=lazy$5.value(()=>bscript$9.decompile(Xr.input)),no={name:"p2pk",network:Xr.network||networks_1$6.bitcoin};if(lazy$5.prop(no,"output",()=>{if(Xr.pubkey)return bscript$9.compile([Xr.pubkey,OPS$5.OP_CHECKSIG])}),lazy$5.prop(no,"pubkey",()=>{if(Xr.output)return Xr.output.slice(1,-1)}),lazy$5.prop(no,"signature",()=>{if(Xr.input)return to()[0]}),lazy$5.prop(no,"input",()=>{if(Xr.signature)return bscript$9.compile([Xr.signature])}),lazy$5.prop(no,"witness",()=>{if(no.input)return[]}),eo.validate){if(Xr.output){if(Xr.output[Xr.output.length-1]!==OPS$5.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,types_1$7.isPoint)(no.pubkey))throw new TypeError("Output pubkey is invalid");if(Xr.pubkey&&!Xr.pubkey.equals(no.pubkey))throw new TypeError("Pubkey mismatch")}if(Xr.signature&&Xr.input&&!Xr.input.equals(no.input))throw new TypeError("Signature mismatch");if(Xr.input){if(to().length!==1)throw new TypeError("Input is invalid");if(!bscript$9.isCanonicalScriptSignature(no.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(no,Xr)}p2pk$1.p2pk=p2pk;var p2pkh$1={},crypto$3={},sha1$1={};Object.defineProperty(sha1$1,"__esModule",{value:!0});sha1$1.sha1=sha1$1.SHA1=void 0;const _md_js_1=_md,utils_js_1=utils$e,SHA1_IV=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),SHA1_W=new Uint32Array(80);class SHA1 extends _md_js_1.HashMD{constructor(){super(64,20,8,!1),this.A=SHA1_IV[0]|0,this.B=SHA1_IV[1]|0,this.C=SHA1_IV[2]|0,this.D=SHA1_IV[3]|0,this.E=SHA1_IV[4]|0}get(){const{A:eo,B:to,C:ro,D:no,E:io}=this;return[eo,to,ro,no,io]}set(eo,to,ro,no,io){this.A=eo|0,this.B=to|0,this.C=ro|0,this.D=no|0,this.E=io|0}process(eo,to){for(let so=0;so<16;so++,to+=4)SHA1_W[so]=eo.getUint32(to,!1);for(let so=16;so<80;so++)SHA1_W[so]=(0,utils_js_1.rotl)(SHA1_W[so-3]^SHA1_W[so-8]^SHA1_W[so-14]^SHA1_W[so-16],1);let{A:ro,B:no,C:io,D:oo,E:ao}=this;for(let so=0;so<80;so++){let co,lo;so<20?(co=(0,_md_js_1.Chi)(no,io,oo),lo=1518500249):so<40?(co=no^io^oo,lo=1859775393):so<60?(co=(0,_md_js_1.Maj)(no,io,oo),lo=2400959708):(co=no^io^oo,lo=3395469782);const fo=(0,utils_js_1.rotl)(ro,5)+co+ao+lo+SHA1_W[so]|0;ao=oo,oo=io,io=(0,utils_js_1.rotl)(no,30),no=ro,ro=fo}ro=ro+this.A|0,no=no+this.B|0,io=io+this.C|0,oo=oo+this.D|0,ao=ao+this.E|0,this.set(ro,no,io,oo,ao)}roundClean(){SHA1_W.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}sha1$1.SHA1=SHA1;sha1$1.sha1=(0,utils_js_1.wrapConstructor)(()=>new SHA1);(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.taggedHash=Xr.TAGGED_HASH_PREFIXES=Xr.TAGS=Xr.hash256=Xr.hash160=Xr.sha256=Xr.sha1=Xr.ripemd160=void 0;const eo=ripemd160$1,to=sha1$1,ro=sha256$7;function no(lo){return Buffer$3.from((0,eo.ripemd160)(Uint8Array.from(lo)))}Xr.ripemd160=no;function io(lo){return Buffer$3.from((0,to.sha1)(Uint8Array.from(lo)))}Xr.sha1=io;function oo(lo){return Buffer$3.from((0,ro.sha256)(Uint8Array.from(lo)))}Xr.sha256=oo;function ao(lo){return Buffer$3.from((0,eo.ripemd160)((0,ro.sha256)(Uint8Array.from(lo))))}Xr.hash160=ao;function so(lo){return Buffer$3.from((0,ro.sha256)((0,ro.sha256)(Uint8Array.from(lo))))}Xr.hash256=so,Xr.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],Xr.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer$3.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer$3.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer$3.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer$3.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer$3.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer$3.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer$3.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer$3.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer$3.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function co(lo,fo){return oo(Buffer$3.concat([Xr.TAGGED_HASH_PREFIXES[lo],fo]))}Xr.taggedHash=co})(crypto$3);function base$3(Xr){if(Xr.length>=255)throw new TypeError("Alphabet too long");for(var eo=new Uint8Array(256),to=0;to>>0,Ao=new Uint8Array(ko);wo!==Eo;){for(var Po=go[wo],jo=0,Mo=ko-1;(Po!==0||jo>>0,Ao[Mo]=Po%oo>>>0,Po=Po/oo>>>0;if(Po!==0)throw new Error("Non-zero carry");vo=jo,wo++}for(var No=ko-vo;No!==ko&&Ao[No]===0;)No++;for(var Do=ao.repeat(yo);No>>0,ko=new Uint8Array(Eo);go[yo];){var Ao=eo[go.charCodeAt(yo)];if(Ao===255)return;for(var Po=0,jo=Eo-1;(Ao!==0||Po>>0,ko[jo]=Ao%256>>>0,Ao=Ao/256>>>0;if(Ao!==0)throw new Error("Non-zero carry");wo=Po,yo++}for(var Mo=Eo-wo;Mo!==Eo&&ko[Mo]===0;)Mo++;for(var No=new Uint8Array(vo+(Eo-Mo)),Do=vo;Mo!==Eo;)No[Do++]=ko[Mo++];return No}function ho(go){var yo=fo(go);if(yo)return yo;throw new Error("Non-base"+oo+" character")}return{encode:lo,decodeUnsafe:fo,decode:ho}}var src$2=base$3;const basex$2=src$2,ALPHABET$2="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var bs58$4=basex$2(ALPHABET$2),base58$1=bs58$4,base$2=function(Xr){function eo(io){var oo=Uint8Array.from(io),ao=Xr(oo),so=oo.length+4,co=new Uint8Array(so);return co.set(oo,0),co.set(ao.subarray(0,4),oo.length),base58$1.encode(co,so)}function to(io){var oo=io.slice(0,-4),ao=io.slice(-4),so=Xr(oo);if(!(ao[0]^so[0]|ao[1]^so[1]|ao[2]^so[2]|ao[3]^so[3]))return oo}function ro(io){var oo=base58$1.decodeUnsafe(io);if(oo)return to(oo)}function no(io){var oo=base58$1.decode(io),ao=to(oo);if(!ao)throw new Error("Invalid checksum");return ao}return{encode:eo,decode:no,decodeUnsafe:ro}},{sha256:sha256$2}=sha256$7,bs58checkBase=base$2;function sha256x2(Xr){return sha256$2(sha256$2(Xr))}var bs58check$3=bs58checkBase(sha256x2);Object.defineProperty(p2pkh$1,"__esModule",{value:!0});p2pkh$1.p2pkh=void 0;const bcrypto$5=crypto$3,networks_1$5=networks$1,bscript$8=script$1,types_1$6=types$7,lazy$4=lazy$8,bs58check$2=bs58check$3,OPS$4=bscript$8.OPS;function p2pkh(Xr,eo){if(!Xr.address&&!Xr.hash&&!Xr.output&&!Xr.pubkey&&!Xr.input)throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{}),(0,types_1$6.typeforce)({network:types_1$6.typeforce.maybe(types_1$6.typeforce.Object),address:types_1$6.typeforce.maybe(types_1$6.typeforce.String),hash:types_1$6.typeforce.maybe(types_1$6.typeforce.BufferN(20)),output:types_1$6.typeforce.maybe(types_1$6.typeforce.BufferN(25)),pubkey:types_1$6.typeforce.maybe(types_1$6.isPoint),signature:types_1$6.typeforce.maybe(bscript$8.isCanonicalScriptSignature),input:types_1$6.typeforce.maybe(types_1$6.typeforce.Buffer)},Xr);const to=lazy$4.value(()=>{const oo=Buffer$3.from(bs58check$2.decode(Xr.address)),ao=oo.readUInt8(0),so=oo.slice(1);return{version:ao,hash:so}}),ro=lazy$4.value(()=>bscript$8.decompile(Xr.input)),no=Xr.network||networks_1$5.bitcoin,io={name:"p2pkh",network:no};if(lazy$4.prop(io,"address",()=>{if(!io.hash)return;const oo=Buffer$3.allocUnsafe(21);return oo.writeUInt8(no.pubKeyHash,0),io.hash.copy(oo,1),bs58check$2.encode(oo)}),lazy$4.prop(io,"hash",()=>{if(Xr.output)return Xr.output.slice(3,23);if(Xr.address)return to().hash;if(Xr.pubkey||io.pubkey)return bcrypto$5.hash160(Xr.pubkey||io.pubkey)}),lazy$4.prop(io,"output",()=>{if(io.hash)return bscript$8.compile([OPS$4.OP_DUP,OPS$4.OP_HASH160,io.hash,OPS$4.OP_EQUALVERIFY,OPS$4.OP_CHECKSIG])}),lazy$4.prop(io,"pubkey",()=>{if(Xr.input)return ro()[1]}),lazy$4.prop(io,"signature",()=>{if(Xr.input)return ro()[0]}),lazy$4.prop(io,"input",()=>{if(Xr.pubkey&&Xr.signature)return bscript$8.compile([Xr.signature,Xr.pubkey])}),lazy$4.prop(io,"witness",()=>{if(io.input)return[]}),eo.validate){let oo=Buffer$3.from([]);if(Xr.address){if(to().version!==no.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(to().hash.length!==20)throw new TypeError("Invalid address");oo=to().hash}if(Xr.hash){if(oo.length>0&&!oo.equals(Xr.hash))throw new TypeError("Hash mismatch");oo=Xr.hash}if(Xr.output){if(Xr.output.length!==25||Xr.output[0]!==OPS$4.OP_DUP||Xr.output[1]!==OPS$4.OP_HASH160||Xr.output[2]!==20||Xr.output[23]!==OPS$4.OP_EQUALVERIFY||Xr.output[24]!==OPS$4.OP_CHECKSIG)throw new TypeError("Output is invalid");const ao=Xr.output.slice(3,23);if(oo.length>0&&!oo.equals(ao))throw new TypeError("Hash mismatch");oo=ao}if(Xr.pubkey){const ao=bcrypto$5.hash160(Xr.pubkey);if(oo.length>0&&!oo.equals(ao))throw new TypeError("Hash mismatch");oo=ao}if(Xr.input){const ao=ro();if(ao.length!==2)throw new TypeError("Input is invalid");if(!bscript$8.isCanonicalScriptSignature(ao[0]))throw new TypeError("Input has invalid signature");if(!(0,types_1$6.isPoint)(ao[1]))throw new TypeError("Input has invalid pubkey");if(Xr.signature&&!Xr.signature.equals(ao[0]))throw new TypeError("Signature mismatch");if(Xr.pubkey&&!Xr.pubkey.equals(ao[1]))throw new TypeError("Pubkey mismatch");const so=bcrypto$5.hash160(ao[1]);if(oo.length>0&&!oo.equals(so))throw new TypeError("Hash mismatch")}}return Object.assign(io,Xr)}p2pkh$1.p2pkh=p2pkh;var p2sh$1={};Object.defineProperty(p2sh$1,"__esModule",{value:!0});p2sh$1.p2sh=void 0;const bcrypto$4=crypto$3,networks_1$4=networks$1,bscript$7=script$1,types_1$5=types$7,lazy$3=lazy$8,bs58check$1=bs58check$3,OPS$3=bscript$7.OPS;function stacksEqual$2(Xr,eo){return Xr.length!==eo.length?!1:Xr.every((to,ro)=>to.equals(eo[ro]))}function p2sh(Xr,eo){if(!Xr.address&&!Xr.hash&&!Xr.output&&!Xr.redeem&&!Xr.input)throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{}),(0,types_1$5.typeforce)({network:types_1$5.typeforce.maybe(types_1$5.typeforce.Object),address:types_1$5.typeforce.maybe(types_1$5.typeforce.String),hash:types_1$5.typeforce.maybe(types_1$5.typeforce.BufferN(20)),output:types_1$5.typeforce.maybe(types_1$5.typeforce.BufferN(23)),redeem:types_1$5.typeforce.maybe({network:types_1$5.typeforce.maybe(types_1$5.typeforce.Object),output:types_1$5.typeforce.maybe(types_1$5.typeforce.Buffer),input:types_1$5.typeforce.maybe(types_1$5.typeforce.Buffer),witness:types_1$5.typeforce.maybe(types_1$5.typeforce.arrayOf(types_1$5.typeforce.Buffer))}),input:types_1$5.typeforce.maybe(types_1$5.typeforce.Buffer),witness:types_1$5.typeforce.maybe(types_1$5.typeforce.arrayOf(types_1$5.typeforce.Buffer))},Xr);let to=Xr.network;to||(to=Xr.redeem&&Xr.redeem.network||networks_1$4.bitcoin);const ro={network:to},no=lazy$3.value(()=>{const ao=Buffer$3.from(bs58check$1.decode(Xr.address)),so=ao.readUInt8(0),co=ao.slice(1);return{version:so,hash:co}}),io=lazy$3.value(()=>bscript$7.decompile(Xr.input)),oo=lazy$3.value(()=>{const ao=io(),so=ao[ao.length-1];return{network:to,output:so===OPS$3.OP_FALSE?Buffer$3.from([]):so,input:bscript$7.compile(ao.slice(0,-1)),witness:Xr.witness||[]}});if(lazy$3.prop(ro,"address",()=>{if(!ro.hash)return;const ao=Buffer$3.allocUnsafe(21);return ao.writeUInt8(ro.network.scriptHash,0),ro.hash.copy(ao,1),bs58check$1.encode(ao)}),lazy$3.prop(ro,"hash",()=>{if(Xr.output)return Xr.output.slice(2,22);if(Xr.address)return no().hash;if(ro.redeem&&ro.redeem.output)return bcrypto$4.hash160(ro.redeem.output)}),lazy$3.prop(ro,"output",()=>{if(ro.hash)return bscript$7.compile([OPS$3.OP_HASH160,ro.hash,OPS$3.OP_EQUAL])}),lazy$3.prop(ro,"redeem",()=>{if(Xr.input)return oo()}),lazy$3.prop(ro,"input",()=>{if(!(!Xr.redeem||!Xr.redeem.input||!Xr.redeem.output))return bscript$7.compile([].concat(bscript$7.decompile(Xr.redeem.input),Xr.redeem.output))}),lazy$3.prop(ro,"witness",()=>{if(ro.redeem&&ro.redeem.witness)return ro.redeem.witness;if(ro.input)return[]}),lazy$3.prop(ro,"name",()=>{const ao=["p2sh"];return ro.redeem!==void 0&&ro.redeem.name!==void 0&&ao.push(ro.redeem.name),ao.join("-")}),eo.validate){let ao=Buffer$3.from([]);if(Xr.address){if(no().version!==to.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(no().hash.length!==20)throw new TypeError("Invalid address");ao=no().hash}if(Xr.hash){if(ao.length>0&&!ao.equals(Xr.hash))throw new TypeError("Hash mismatch");ao=Xr.hash}if(Xr.output){if(Xr.output.length!==23||Xr.output[0]!==OPS$3.OP_HASH160||Xr.output[1]!==20||Xr.output[22]!==OPS$3.OP_EQUAL)throw new TypeError("Output is invalid");const co=Xr.output.slice(2,22);if(ao.length>0&&!ao.equals(co))throw new TypeError("Hash mismatch");ao=co}const so=co=>{if(co.output){const lo=bscript$7.decompile(co.output);if(!lo||lo.length<1)throw new TypeError("Redeem.output too short");if(co.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(bscript$7.countNonPushOnlyOPs(lo)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const fo=bcrypto$4.hash160(co.output);if(ao.length>0&&!ao.equals(fo))throw new TypeError("Hash mismatch");ao=fo}if(co.input){const lo=co.input.length>0,fo=co.witness&&co.witness.length>0;if(!lo&&!fo)throw new TypeError("Empty input");if(lo&&fo)throw new TypeError("Input and witness provided");if(lo){const ho=bscript$7.decompile(co.input);if(!bscript$7.isPushOnly(ho))throw new TypeError("Non push-only scriptSig")}}};if(Xr.input){const co=io();if(!co||co.length<1)throw new TypeError("Input too short");if(!Buffer$3.isBuffer(oo().output))throw new TypeError("Input is invalid");so(oo())}if(Xr.redeem){if(Xr.redeem.network&&Xr.redeem.network!==to)throw new TypeError("Network mismatch");if(Xr.input){const co=oo();if(Xr.redeem.output&&!Xr.redeem.output.equals(co.output))throw new TypeError("Redeem.output mismatch");if(Xr.redeem.input&&!Xr.redeem.input.equals(co.input))throw new TypeError("Redeem.input mismatch")}so(Xr.redeem)}if(Xr.witness&&Xr.redeem&&Xr.redeem.witness&&!stacksEqual$2(Xr.redeem.witness,Xr.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(ro,Xr)}p2sh$1.p2sh=p2sh;var p2wpkh$1={};Object.defineProperty(p2wpkh$1,"__esModule",{value:!0});p2wpkh$1.p2wpkh=void 0;const bcrypto$3=crypto$3,networks_1$3=networks$1,bscript$6=script$1,types_1$4=types$7,lazy$2=lazy$8,bech32_1$3=dist$1,OPS$2=bscript$6.OPS,EMPTY_BUFFER$2=Buffer$3.alloc(0);function p2wpkh(Xr,eo){if(!Xr.address&&!Xr.hash&&!Xr.output&&!Xr.pubkey&&!Xr.witness)throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{}),(0,types_1$4.typeforce)({address:types_1$4.typeforce.maybe(types_1$4.typeforce.String),hash:types_1$4.typeforce.maybe(types_1$4.typeforce.BufferN(20)),input:types_1$4.typeforce.maybe(types_1$4.typeforce.BufferN(0)),network:types_1$4.typeforce.maybe(types_1$4.typeforce.Object),output:types_1$4.typeforce.maybe(types_1$4.typeforce.BufferN(22)),pubkey:types_1$4.typeforce.maybe(types_1$4.isPoint),signature:types_1$4.typeforce.maybe(bscript$6.isCanonicalScriptSignature),witness:types_1$4.typeforce.maybe(types_1$4.typeforce.arrayOf(types_1$4.typeforce.Buffer))},Xr);const to=lazy$2.value(()=>{const io=bech32_1$3.bech32.decode(Xr.address),oo=io.words.shift(),ao=bech32_1$3.bech32.fromWords(io.words);return{version:oo,prefix:io.prefix,data:Buffer$3.from(ao)}}),ro=Xr.network||networks_1$3.bitcoin,no={name:"p2wpkh",network:ro};if(lazy$2.prop(no,"address",()=>{if(!no.hash)return;const io=bech32_1$3.bech32.toWords(no.hash);return io.unshift(0),bech32_1$3.bech32.encode(ro.bech32,io)}),lazy$2.prop(no,"hash",()=>{if(Xr.output)return Xr.output.slice(2,22);if(Xr.address)return to().data;if(Xr.pubkey||no.pubkey)return bcrypto$3.hash160(Xr.pubkey||no.pubkey)}),lazy$2.prop(no,"output",()=>{if(no.hash)return bscript$6.compile([OPS$2.OP_0,no.hash])}),lazy$2.prop(no,"pubkey",()=>{if(Xr.pubkey)return Xr.pubkey;if(Xr.witness)return Xr.witness[1]}),lazy$2.prop(no,"signature",()=>{if(Xr.witness)return Xr.witness[0]}),lazy$2.prop(no,"input",()=>{if(no.witness)return EMPTY_BUFFER$2}),lazy$2.prop(no,"witness",()=>{if(Xr.pubkey&&Xr.signature)return[Xr.signature,Xr.pubkey]}),eo.validate){let io=Buffer$3.from([]);if(Xr.address){if(ro&&ro.bech32!==to().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(to().version!==0)throw new TypeError("Invalid address version");if(to().data.length!==20)throw new TypeError("Invalid address data");io=to().data}if(Xr.hash){if(io.length>0&&!io.equals(Xr.hash))throw new TypeError("Hash mismatch");io=Xr.hash}if(Xr.output){if(Xr.output.length!==22||Xr.output[0]!==OPS$2.OP_0||Xr.output[1]!==20)throw new TypeError("Output is invalid");if(io.length>0&&!io.equals(Xr.output.slice(2)))throw new TypeError("Hash mismatch");io=Xr.output.slice(2)}if(Xr.pubkey){const oo=bcrypto$3.hash160(Xr.pubkey);if(io.length>0&&!io.equals(oo))throw new TypeError("Hash mismatch");if(io=oo,!(0,types_1$4.isPoint)(Xr.pubkey)||Xr.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(Xr.witness){if(Xr.witness.length!==2)throw new TypeError("Witness is invalid");if(!bscript$6.isCanonicalScriptSignature(Xr.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,types_1$4.isPoint)(Xr.witness[1])||Xr.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(Xr.signature&&!Xr.signature.equals(Xr.witness[0]))throw new TypeError("Signature mismatch");if(Xr.pubkey&&!Xr.pubkey.equals(Xr.witness[1]))throw new TypeError("Pubkey mismatch");const oo=bcrypto$3.hash160(Xr.witness[1]);if(io.length>0&&!io.equals(oo))throw new TypeError("Hash mismatch")}}return Object.assign(no,Xr)}p2wpkh$1.p2wpkh=p2wpkh;var p2wsh$1={};Object.defineProperty(p2wsh$1,"__esModule",{value:!0});p2wsh$1.p2wsh=void 0;const bcrypto$2=crypto$3,networks_1$2=networks$1,bscript$5=script$1,types_1$3=types$7,lazy$1=lazy$8,bech32_1$2=dist$1,OPS$1=bscript$5.OPS,EMPTY_BUFFER$1=Buffer$3.alloc(0);function stacksEqual$1(Xr,eo){return Xr.length!==eo.length?!1:Xr.every((to,ro)=>to.equals(eo[ro]))}function chunkHasUncompressedPubkey(Xr){return!!(Buffer$3.isBuffer(Xr)&&Xr.length===65&&Xr[0]===4&&(0,types_1$3.isPoint)(Xr))}function p2wsh(Xr,eo){if(!Xr.address&&!Xr.hash&&!Xr.output&&!Xr.redeem&&!Xr.witness)throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{}),(0,types_1$3.typeforce)({network:types_1$3.typeforce.maybe(types_1$3.typeforce.Object),address:types_1$3.typeforce.maybe(types_1$3.typeforce.String),hash:types_1$3.typeforce.maybe(types_1$3.typeforce.BufferN(32)),output:types_1$3.typeforce.maybe(types_1$3.typeforce.BufferN(34)),redeem:types_1$3.typeforce.maybe({input:types_1$3.typeforce.maybe(types_1$3.typeforce.Buffer),network:types_1$3.typeforce.maybe(types_1$3.typeforce.Object),output:types_1$3.typeforce.maybe(types_1$3.typeforce.Buffer),witness:types_1$3.typeforce.maybe(types_1$3.typeforce.arrayOf(types_1$3.typeforce.Buffer))}),input:types_1$3.typeforce.maybe(types_1$3.typeforce.BufferN(0)),witness:types_1$3.typeforce.maybe(types_1$3.typeforce.arrayOf(types_1$3.typeforce.Buffer))},Xr);const to=lazy$1.value(()=>{const oo=bech32_1$2.bech32.decode(Xr.address),ao=oo.words.shift(),so=bech32_1$2.bech32.fromWords(oo.words);return{version:ao,prefix:oo.prefix,data:Buffer$3.from(so)}}),ro=lazy$1.value(()=>bscript$5.decompile(Xr.redeem.input));let no=Xr.network;no||(no=Xr.redeem&&Xr.redeem.network||networks_1$2.bitcoin);const io={network:no};if(lazy$1.prop(io,"address",()=>{if(!io.hash)return;const oo=bech32_1$2.bech32.toWords(io.hash);return oo.unshift(0),bech32_1$2.bech32.encode(no.bech32,oo)}),lazy$1.prop(io,"hash",()=>{if(Xr.output)return Xr.output.slice(2);if(Xr.address)return to().data;if(io.redeem&&io.redeem.output)return bcrypto$2.sha256(io.redeem.output)}),lazy$1.prop(io,"output",()=>{if(io.hash)return bscript$5.compile([OPS$1.OP_0,io.hash])}),lazy$1.prop(io,"redeem",()=>{if(Xr.witness)return{output:Xr.witness[Xr.witness.length-1],input:EMPTY_BUFFER$1,witness:Xr.witness.slice(0,-1)}}),lazy$1.prop(io,"input",()=>{if(io.witness)return EMPTY_BUFFER$1}),lazy$1.prop(io,"witness",()=>{if(Xr.redeem&&Xr.redeem.input&&Xr.redeem.input.length>0&&Xr.redeem.output&&Xr.redeem.output.length>0){const oo=bscript$5.toStack(ro());return io.redeem=Object.assign({witness:oo},Xr.redeem),io.redeem.input=EMPTY_BUFFER$1,[].concat(oo,Xr.redeem.output)}if(Xr.redeem&&Xr.redeem.output&&Xr.redeem.witness)return[].concat(Xr.redeem.witness,Xr.redeem.output)}),lazy$1.prop(io,"name",()=>{const oo=["p2wsh"];return io.redeem!==void 0&&io.redeem.name!==void 0&&oo.push(io.redeem.name),oo.join("-")}),eo.validate){let oo=Buffer$3.from([]);if(Xr.address){if(to().prefix!==no.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(to().version!==0)throw new TypeError("Invalid address version");if(to().data.length!==32)throw new TypeError("Invalid address data");oo=to().data}if(Xr.hash){if(oo.length>0&&!oo.equals(Xr.hash))throw new TypeError("Hash mismatch");oo=Xr.hash}if(Xr.output){if(Xr.output.length!==34||Xr.output[0]!==OPS$1.OP_0||Xr.output[1]!==32)throw new TypeError("Output is invalid");const ao=Xr.output.slice(2);if(oo.length>0&&!oo.equals(ao))throw new TypeError("Hash mismatch");oo=ao}if(Xr.redeem){if(Xr.redeem.network&&Xr.redeem.network!==no)throw new TypeError("Network mismatch");if(Xr.redeem.input&&Xr.redeem.input.length>0&&Xr.redeem.witness&&Xr.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(Xr.redeem.output){const ao=bscript$5.decompile(Xr.redeem.output);if(!ao||ao.length<1)throw new TypeError("Redeem.output is invalid");if(Xr.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(bscript$5.countNonPushOnlyOPs(ao)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const so=bcrypto$2.sha256(Xr.redeem.output);if(oo.length>0&&!oo.equals(so))throw new TypeError("Hash mismatch");oo=so}if(Xr.redeem.input&&!bscript$5.isPushOnly(ro()))throw new TypeError("Non push-only scriptSig");if(Xr.witness&&Xr.redeem.witness&&!stacksEqual$1(Xr.witness,Xr.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(Xr.redeem.input&&ro().some(chunkHasUncompressedPubkey)||Xr.redeem.output&&(bscript$5.decompile(Xr.redeem.output)||[]).some(chunkHasUncompressedPubkey))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(Xr.witness&&Xr.witness.length>0){const ao=Xr.witness[Xr.witness.length-1];if(Xr.redeem&&Xr.redeem.output&&!Xr.redeem.output.equals(ao))throw new TypeError("Witness and redeem.output mismatch");if(Xr.witness.some(chunkHasUncompressedPubkey)||(bscript$5.decompile(ao)||[]).some(chunkHasUncompressedPubkey))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(io,Xr)}p2wsh$1.p2wsh=p2wsh;var p2tr$1={},ecc_lib={};Object.defineProperty(ecc_lib,"__esModule",{value:!0});ecc_lib.getEccLib=ecc_lib.initEccLib=void 0;const _ECCLIB_CACHE={};function initEccLib(Xr){Xr?Xr!==_ECCLIB_CACHE.eccLib&&(verifyEcc(Xr),_ECCLIB_CACHE.eccLib=Xr):_ECCLIB_CACHE.eccLib=Xr}ecc_lib.initEccLib=initEccLib;function getEccLib(){if(!_ECCLIB_CACHE.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return _ECCLIB_CACHE.eccLib}ecc_lib.getEccLib=getEccLib;const h$8=Xr=>Buffer$3.from(Xr,"hex");function verifyEcc(Xr){assert$7(typeof Xr.isXOnlyPoint=="function"),assert$7(Xr.isXOnlyPoint(h$8("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),assert$7(Xr.isXOnlyPoint(h$8("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),assert$7(Xr.isXOnlyPoint(h$8("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),assert$7(Xr.isXOnlyPoint(h$8("0000000000000000000000000000000000000000000000000000000000000001"))),assert$7(!Xr.isXOnlyPoint(h$8("0000000000000000000000000000000000000000000000000000000000000000"))),assert$7(!Xr.isXOnlyPoint(h$8("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),assert$7(typeof Xr.xOnlyPointAddTweak=="function"),tweakAddVectors.forEach(eo=>{const to=Xr.xOnlyPointAddTweak(h$8(eo.pubkey),h$8(eo.tweak));eo.result===null?assert$7(to===null):(assert$7(to!==null),assert$7(to.parity===eo.parity),assert$7(Buffer$3.from(to.xOnlyPubkey).equals(h$8(eo.result))))})}function assert$7(Xr){if(!Xr)throw new Error("ecc library invalid")}const tweakAddVectors=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var bip341={},bufferutils={},Buffer=safeBufferExports.Buffer,MAX_SAFE_INTEGER$1=9007199254740991;function checkUInt53$1(Xr){if(Xr<0||Xr>MAX_SAFE_INTEGER$1||Xr%1!==0)throw new RangeError("value out of range")}function encode$i(Xr,eo,to){if(checkUInt53$1(Xr),eo||(eo=Buffer.allocUnsafe(encodingLength$1(Xr))),!Buffer.isBuffer(eo))throw new TypeError("buffer must be a Buffer instance");return to||(to=0),Xr<253?(eo.writeUInt8(Xr,to),encode$i.bytes=1):Xr<=65535?(eo.writeUInt8(253,to),eo.writeUInt16LE(Xr,to+1),encode$i.bytes=3):Xr<=4294967295?(eo.writeUInt8(254,to),eo.writeUInt32LE(Xr,to+1),encode$i.bytes=5):(eo.writeUInt8(255,to),eo.writeUInt32LE(Xr>>>0,to+1),eo.writeUInt32LE(Xr/4294967296|0,to+5),encode$i.bytes=9),eo}function decode$k(Xr,eo){if(!Buffer.isBuffer(Xr))throw new TypeError("buffer must be a Buffer instance");eo||(eo=0);var to=Xr.readUInt8(eo);if(to<253)return decode$k.bytes=1,to;if(to===253)return decode$k.bytes=3,Xr.readUInt16LE(eo+1);if(to===254)return decode$k.bytes=5,Xr.readUInt32LE(eo+1);decode$k.bytes=9;var ro=Xr.readUInt32LE(eo+1),no=Xr.readUInt32LE(eo+5),io=no*4294967296+ro;return checkUInt53$1(io),io}function encodingLength$1(Xr){return checkUInt53$1(Xr),Xr<253?1:Xr<=65535?3:Xr<=4294967295?5:9}var varuintBitcoin={encode:encode$i,decode:decode$k,encodingLength:encodingLength$1};Object.defineProperty(bufferutils,"__esModule",{value:!0});bufferutils.BufferReader=bufferutils.BufferWriter=bufferutils.cloneBuffer=bufferutils.reverseBuffer=bufferutils.writeUInt64LE=bufferutils.readUInt64LE=bufferutils.varuint=void 0;const types$4=types$7,{typeforce:typeforce$2}=types$4,varuint$7=varuintBitcoin;bufferutils.varuint=varuint$7;function verifuint$1(Xr,eo){if(typeof Xr!="number")throw new Error("cannot write a non-number as a number");if(Xr<0)throw new Error("specified a negative value for writing an unsigned value");if(Xr>eo)throw new Error("RangeError: value out of range");if(Math.floor(Xr)!==Xr)throw new Error("value has a fractional component")}function readUInt64LE$1(Xr,eo){const to=Xr.readUInt32LE(eo);let ro=Xr.readUInt32LE(eo+4);return ro*=4294967296,verifuint$1(ro+to,9007199254740991),ro+to}bufferutils.readUInt64LE=readUInt64LE$1;function writeUInt64LE$1(Xr,eo,to){return verifuint$1(eo,9007199254740991),Xr.writeInt32LE(eo&-1,to),Xr.writeUInt32LE(Math.floor(eo/4294967296),to+4),to+8}bufferutils.writeUInt64LE=writeUInt64LE$1;function reverseBuffer$1(Xr){if(Xr.length<1)return Xr;let eo=Xr.length-1,to=0;for(let ro=0;rothis.writeVarSlice(to))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}bufferutils.BufferWriter=BufferWriter;class BufferReader{constructor(eo,to=0){this.buffer=eo,this.offset=to,typeforce$2(types$4.tuple(types$4.Buffer,types$4.UInt32),[eo,to])}readUInt8(){const eo=this.buffer.readUInt8(this.offset);return this.offset++,eo}readInt32(){const eo=this.buffer.readInt32LE(this.offset);return this.offset+=4,eo}readUInt32(){const eo=this.buffer.readUInt32LE(this.offset);return this.offset+=4,eo}readUInt64(){const eo=readUInt64LE$1(this.buffer,this.offset);return this.offset+=8,eo}readVarInt(){const eo=varuint$7.decode(this.buffer,this.offset);return this.offset+=varuint$7.decode.bytes,eo}readSlice(eo){if(this.buffer.length"left"in vo&&"right"in vo;function ao(vo,wo){if(vo.length<33)throw new TypeError(`The control-block length is too small. Got ${vo.length}, expected min 33.`);const Eo=(vo.length-33)/32;let ko=wo;for(let Ao=0;AoAo.hash.compare(Po.hash));const[Eo,ko]=wo;return{hash:go(Eo.hash,ko.hash),left:Eo,right:ko}}Xr.toHashTree=so;function co(vo,wo){if(oo(vo)){const Eo=co(vo.left,wo);if(Eo!==void 0)return[...Eo,vo.right.hash];const ko=co(vo.right,wo);if(ko!==void 0)return[...ko,vo.left.hash]}else if(vo.hash.equals(wo))return[]}Xr.findScriptPath=co;function lo(vo){const wo=vo.version||Xr.LEAF_VERSION_TAPSCRIPT;return ro.taggedHash("TapLeaf",eo.Buffer.concat([eo.Buffer.from([wo]),yo(vo.output)]))}Xr.tapleafHash=lo;function fo(vo,wo){return ro.taggedHash("TapTweak",eo.Buffer.concat(wo?[vo,wo]:[vo]))}Xr.tapTweakHash=fo;function ho(vo,wo){if(!eo.Buffer.isBuffer(vo)||vo.length!==32||wo&&wo.length!==32)return null;const Eo=fo(vo,wo),ko=(0,to.getEccLib)().xOnlyPointAddTweak(vo,Eo);return!ko||ko.xOnlyPubkey===null?null:{parity:ko.parity,x:eo.Buffer.from(ko.xOnlyPubkey)}}Xr.tweakKey=ho;function go(vo,wo){return ro.taggedHash("TapBranch",eo.Buffer.concat([vo,wo]))}function yo(vo){const wo=no.varuint.encodingLength(vo.length),Eo=eo.Buffer.allocUnsafe(wo);return no.varuint.encode(vo.length,Eo),eo.Buffer.concat([Eo,vo])}})(bip341);Object.defineProperty(p2tr$1,"__esModule",{value:!0});p2tr$1.p2tr=void 0;const buffer_1$1=require$$0$9,networks_1$1=networks$1,bscript$4=script$1,types_1$2=types$7,ecc_lib_1=ecc_lib,bip341_1$2=bip341,lazy=lazy$8,bech32_1$1=dist$1,OPS=bscript$4.OPS,TAPROOT_WITNESS_VERSION=1,ANNEX_PREFIX=80;function p2tr(Xr,eo){if(!Xr.address&&!Xr.output&&!Xr.pubkey&&!Xr.internalPubkey&&!(Xr.witness&&Xr.witness.length>1))throw new TypeError("Not enough data");eo=Object.assign({validate:!0},eo||{}),(0,types_1$2.typeforce)({address:types_1$2.typeforce.maybe(types_1$2.typeforce.String),input:types_1$2.typeforce.maybe(types_1$2.typeforce.BufferN(0)),network:types_1$2.typeforce.maybe(types_1$2.typeforce.Object),output:types_1$2.typeforce.maybe(types_1$2.typeforce.BufferN(34)),internalPubkey:types_1$2.typeforce.maybe(types_1$2.typeforce.BufferN(32)),hash:types_1$2.typeforce.maybe(types_1$2.typeforce.BufferN(32)),pubkey:types_1$2.typeforce.maybe(types_1$2.typeforce.BufferN(32)),signature:types_1$2.typeforce.maybe(types_1$2.typeforce.anyOf(types_1$2.typeforce.BufferN(64),types_1$2.typeforce.BufferN(65))),witness:types_1$2.typeforce.maybe(types_1$2.typeforce.arrayOf(types_1$2.typeforce.Buffer)),scriptTree:types_1$2.typeforce.maybe(types_1$2.isTaptree),redeem:types_1$2.typeforce.maybe({output:types_1$2.typeforce.maybe(types_1$2.typeforce.Buffer),redeemVersion:types_1$2.typeforce.maybe(types_1$2.typeforce.Number),witness:types_1$2.typeforce.maybe(types_1$2.typeforce.arrayOf(types_1$2.typeforce.Buffer))}),redeemVersion:types_1$2.typeforce.maybe(types_1$2.typeforce.Number)},Xr);const to=lazy.value(()=>{const ao=bech32_1$1.bech32m.decode(Xr.address),so=ao.words.shift(),co=bech32_1$1.bech32m.fromWords(ao.words);return{version:so,prefix:ao.prefix,data:buffer_1$1.Buffer.from(co)}}),ro=lazy.value(()=>{if(!(!Xr.witness||!Xr.witness.length))return Xr.witness.length>=2&&Xr.witness[Xr.witness.length-1][0]===ANNEX_PREFIX?Xr.witness.slice(0,-1):Xr.witness.slice()}),no=lazy.value(()=>{if(Xr.scriptTree)return(0,bip341_1$2.toHashTree)(Xr.scriptTree);if(Xr.hash)return{hash:Xr.hash}}),io=Xr.network||networks_1$1.bitcoin,oo={name:"p2tr",network:io};if(lazy.prop(oo,"address",()=>{if(!oo.pubkey)return;const ao=bech32_1$1.bech32m.toWords(oo.pubkey);return ao.unshift(TAPROOT_WITNESS_VERSION),bech32_1$1.bech32m.encode(io.bech32,ao)}),lazy.prop(oo,"hash",()=>{const ao=no();if(ao)return ao.hash;const so=ro();if(so&&so.length>1){const co=so[so.length-1],lo=co[0]&types_1$2.TAPLEAF_VERSION_MASK,fo=so[so.length-2],ho=(0,bip341_1$2.tapleafHash)({output:fo,version:lo});return(0,bip341_1$2.rootHashFromPath)(co,ho)}return null}),lazy.prop(oo,"output",()=>{if(oo.pubkey)return bscript$4.compile([OPS.OP_1,oo.pubkey])}),lazy.prop(oo,"redeemVersion",()=>Xr.redeemVersion?Xr.redeemVersion:Xr.redeem&&Xr.redeem.redeemVersion!==void 0&&Xr.redeem.redeemVersion!==null?Xr.redeem.redeemVersion:bip341_1$2.LEAF_VERSION_TAPSCRIPT),lazy.prop(oo,"redeem",()=>{const ao=ro();if(!(!ao||ao.length<2))return{output:ao[ao.length-2],witness:ao.slice(0,-2),redeemVersion:ao[ao.length-1][0]&types_1$2.TAPLEAF_VERSION_MASK}}),lazy.prop(oo,"pubkey",()=>{if(Xr.pubkey)return Xr.pubkey;if(Xr.output)return Xr.output.slice(2);if(Xr.address)return to().data;if(oo.internalPubkey){const ao=(0,bip341_1$2.tweakKey)(oo.internalPubkey,oo.hash);if(ao)return ao.x}}),lazy.prop(oo,"internalPubkey",()=>{if(Xr.internalPubkey)return Xr.internalPubkey;const ao=ro();if(ao&&ao.length>1)return ao[ao.length-1].slice(1,33)}),lazy.prop(oo,"signature",()=>{if(Xr.signature)return Xr.signature;const ao=ro();if(!(!ao||ao.length!==1))return ao[0]}),lazy.prop(oo,"witness",()=>{if(Xr.witness)return Xr.witness;const ao=no();if(ao&&Xr.redeem&&Xr.redeem.output&&Xr.internalPubkey){const so=(0,bip341_1$2.tapleafHash)({output:Xr.redeem.output,version:oo.redeemVersion}),co=(0,bip341_1$2.findScriptPath)(ao,so);if(!co)return;const lo=(0,bip341_1$2.tweakKey)(Xr.internalPubkey,ao.hash);if(!lo)return;const fo=buffer_1$1.Buffer.concat([buffer_1$1.Buffer.from([oo.redeemVersion|lo.parity]),Xr.internalPubkey].concat(co));return[Xr.redeem.output,fo]}if(Xr.signature)return[Xr.signature]}),eo.validate){let ao=buffer_1$1.Buffer.from([]);if(Xr.address){if(io&&io.bech32!==to().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(to().version!==TAPROOT_WITNESS_VERSION)throw new TypeError("Invalid address version");if(to().data.length!==32)throw new TypeError("Invalid address data");ao=to().data}if(Xr.pubkey){if(ao.length>0&&!ao.equals(Xr.pubkey))throw new TypeError("Pubkey mismatch");ao=Xr.pubkey}if(Xr.output){if(Xr.output.length!==34||Xr.output[0]!==OPS.OP_1||Xr.output[1]!==32)throw new TypeError("Output is invalid");if(ao.length>0&&!ao.equals(Xr.output.slice(2)))throw new TypeError("Pubkey mismatch");ao=Xr.output.slice(2)}if(Xr.internalPubkey){const lo=(0,bip341_1$2.tweakKey)(Xr.internalPubkey,oo.hash);if(ao.length>0&&!ao.equals(lo.x))throw new TypeError("Pubkey mismatch");ao=lo.x}if(ao&&ao.length&&!(0,ecc_lib_1.getEccLib)().isXOnlyPoint(ao))throw new TypeError("Invalid pubkey for p2tr");const so=no();if(Xr.hash&&so&&!Xr.hash.equals(so.hash))throw new TypeError("Hash mismatch");if(Xr.redeem&&Xr.redeem.output&&so){const lo=(0,bip341_1$2.tapleafHash)({output:Xr.redeem.output,version:oo.redeemVersion});if(!(0,bip341_1$2.findScriptPath)(so,lo))throw new TypeError("Redeem script not in tree")}const co=ro();if(Xr.redeem&&oo.redeem){if(Xr.redeem.redeemVersion&&Xr.redeem.redeemVersion!==oo.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(Xr.redeem.output){if(bscript$4.decompile(Xr.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(oo.redeem.output&&!Xr.redeem.output.equals(oo.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(Xr.redeem.witness&&oo.redeem.witness&&!stacksEqual(Xr.redeem.witness,oo.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(co&&co.length)if(co.length===1){if(Xr.signature&&!Xr.signature.equals(co[0]))throw new TypeError("Signature mismatch")}else{const lo=co[co.length-1];if(lo.length<33)throw new TypeError(`The control-block length is too small. Got ${lo.length}, expected min 33.`);if((lo.length-33)%32!==0)throw new TypeError(`The control-block length of ${lo.length} is incorrect!`);const fo=(lo.length-33)/32;if(fo>128)throw new TypeError(`The script path is too long. Got ${fo}, expected max 128.`);const ho=lo.slice(1,33);if(Xr.internalPubkey&&!Xr.internalPubkey.equals(ho))throw new TypeError("Internal pubkey mismatch");if(!(0,ecc_lib_1.getEccLib)().isXOnlyPoint(ho))throw new TypeError("Invalid internalPubkey for p2tr witness");const go=lo[0]&types_1$2.TAPLEAF_VERSION_MASK,yo=co[co.length-2],vo=(0,bip341_1$2.tapleafHash)({output:yo,version:go}),wo=(0,bip341_1$2.rootHashFromPath)(lo,vo),Eo=(0,bip341_1$2.tweakKey)(ho,wo);if(!Eo)throw new TypeError("Invalid outputKey for p2tr witness");if(ao.length&&!ao.equals(Eo.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(Eo.parity!==(lo[0]&1))throw new Error("Incorrect parity")}}return Object.assign(oo,Xr)}p2tr$1.p2tr=p2tr;function stacksEqual(Xr,eo){return Xr.length!==eo.length?!1:Xr.every((to,ro)=>to.equals(eo[ro]))}(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.p2tr=Xr.p2wsh=Xr.p2wpkh=Xr.p2sh=Xr.p2pkh=Xr.p2pk=Xr.p2ms=Xr.embed=void 0;const eo=embed;Object.defineProperty(Xr,"embed",{enumerable:!0,get:function(){return eo.p2data}});const to=p2ms$1;Object.defineProperty(Xr,"p2ms",{enumerable:!0,get:function(){return to.p2ms}});const ro=p2pk$1;Object.defineProperty(Xr,"p2pk",{enumerable:!0,get:function(){return ro.p2pk}});const no=p2pkh$1;Object.defineProperty(Xr,"p2pkh",{enumerable:!0,get:function(){return no.p2pkh}});const io=p2sh$1;Object.defineProperty(Xr,"p2sh",{enumerable:!0,get:function(){return io.p2sh}});const oo=p2wpkh$1;Object.defineProperty(Xr,"p2wpkh",{enumerable:!0,get:function(){return oo.p2wpkh}});const ao=p2wsh$1;Object.defineProperty(Xr,"p2wsh",{enumerable:!0,get:function(){return ao.p2wsh}});const so=p2tr$1;Object.defineProperty(Xr,"p2tr",{enumerable:!0,get:function(){return so.p2tr}})})(payments$3);Object.defineProperty(address,"__esModule",{value:!0});address.toOutputScript=address.fromOutputScript=address.toBech32=address.toBase58Check=address.fromBech32=address.fromBase58Check=void 0;const networks=networks$1,payments$2=payments$3,bscript$3=script$1,types_1$1=types$7,bech32_1=dist$1,bs58check=bs58check$3,FUTURE_SEGWIT_MAX_SIZE=40,FUTURE_SEGWIT_MIN_SIZE=2,FUTURE_SEGWIT_MAX_VERSION=16,FUTURE_SEGWIT_MIN_VERSION=2,FUTURE_SEGWIT_VERSION_DIFF=80,FUTURE_SEGWIT_VERSION_WARNING="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function _toFutureSegwitAddress(Xr,eo){const to=Xr.slice(2);if(to.lengthFUTURE_SEGWIT_MAX_SIZE)throw new TypeError("Invalid program length for segwit address");const ro=Xr[0]-FUTURE_SEGWIT_VERSION_DIFF;if(roFUTURE_SEGWIT_MAX_VERSION)throw new TypeError("Invalid version for segwit address");if(Xr[1]!==to.length)throw new TypeError("Invalid script for segwit address");return console.warn(FUTURE_SEGWIT_VERSION_WARNING),toBech32(to,ro,eo.bech32)}function fromBase58Check(Xr){const eo=Buffer$3.from(bs58check.decode(Xr));if(eo.length<21)throw new TypeError(Xr+" is too short");if(eo.length>21)throw new TypeError(Xr+" is too long");const to=eo.readUInt8(0),ro=eo.slice(1);return{version:to,hash:ro}}address.fromBase58Check=fromBase58Check;function fromBech32(Xr){let eo,to;try{eo=bech32_1.bech32.decode(Xr)}catch{}if(eo){if(to=eo.words[0],to!==0)throw new TypeError(Xr+" uses wrong encoding")}else if(eo=bech32_1.bech32m.decode(Xr),to=eo.words[0],to===0)throw new TypeError(Xr+" uses wrong encoding");const ro=bech32_1.bech32.fromWords(eo.words.slice(1));return{version:to,prefix:eo.prefix,data:Buffer$3.from(ro)}}address.fromBech32=fromBech32;function toBase58Check(Xr,eo){(0,types_1$1.typeforce)((0,types_1$1.tuple)(types_1$1.Hash160bit,types_1$1.UInt8),arguments);const to=Buffer$3.allocUnsafe(21);return to.writeUInt8(eo,0),Xr.copy(to,1),bs58check.encode(to)}address.toBase58Check=toBase58Check;function toBech32(Xr,eo,to){const ro=bech32_1.bech32.toWords(Xr);return ro.unshift(eo),eo===0?bech32_1.bech32.encode(to,ro):bech32_1.bech32m.encode(to,ro)}address.toBech32=toBech32;function fromOutputScript(Xr,eo){eo=eo||networks.bitcoin;try{return payments$2.p2pkh({output:Xr,network:eo}).address}catch{}try{return payments$2.p2sh({output:Xr,network:eo}).address}catch{}try{return payments$2.p2wpkh({output:Xr,network:eo}).address}catch{}try{return payments$2.p2wsh({output:Xr,network:eo}).address}catch{}try{return payments$2.p2tr({output:Xr,network:eo}).address}catch{}try{return _toFutureSegwitAddress(Xr,eo)}catch{}throw new Error(bscript$3.toASM(Xr)+" has no matching Address")}address.fromOutputScript=fromOutputScript;function toOutputScript(Xr,eo){eo=eo||networks.bitcoin;let to,ro;try{to=fromBase58Check(Xr)}catch{}if(to){if(to.version===eo.pubKeyHash)return payments$2.p2pkh({hash:to.hash}).output;if(to.version===eo.scriptHash)return payments$2.p2sh({hash:to.hash}).output}else{try{ro=fromBech32(Xr)}catch{}if(ro){if(ro.prefix!==eo.bech32)throw new Error(Xr+" has an invalid prefix");if(ro.version===0){if(ro.data.length===20)return payments$2.p2wpkh({hash:ro.data}).output;if(ro.data.length===32)return payments$2.p2wsh({hash:ro.data}).output}else if(ro.version===1){if(ro.data.length===32)return payments$2.p2tr({pubkey:ro.data}).output}else if(ro.version>=FUTURE_SEGWIT_MIN_VERSION&&ro.version<=FUTURE_SEGWIT_MAX_VERSION&&ro.data.length>=FUTURE_SEGWIT_MIN_SIZE&&ro.data.length<=FUTURE_SEGWIT_MAX_SIZE)return console.warn(FUTURE_SEGWIT_VERSION_WARNING),bscript$3.compile([ro.version+FUTURE_SEGWIT_VERSION_DIFF,ro.data])}}throw new Error(Xr+" has no matching Script")}address.toOutputScript=toOutputScript;var block={},merkle={};Object.defineProperty(merkle,"__esModule",{value:!0});merkle.fastMerkleRoot=void 0;function fastMerkleRoot(Xr,eo){if(!Array.isArray(Xr))throw TypeError("Expected values Array");if(typeof eo!="function")throw TypeError("Expected digest Function");let to=Xr.length;const ro=Xr.concat();for(;to>1;){let no=0;for(let io=0;ioto+varSliceSize(ro),0)}const EMPTY_BUFFER=Buffer$3.allocUnsafe(0),EMPTY_WITNESS=[],ZERO$1=Buffer$3.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),ONE=Buffer$3.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),VALUE_UINT64_MAX=Buffer$3.from("ffffffffffffffff","hex"),BLANK_OUTPUT={script:EMPTY_BUFFER,valueBuffer:VALUE_UINT64_MAX};function isOutput(Xr){return Xr.value!==void 0}let Transaction$1=class Dp{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(eo,to){const ro=new bufferutils_1$2.BufferReader(eo),no=new Dp;no.version=ro.readInt32();const io=ro.readUInt8(),oo=ro.readUInt8();let ao=!1;io===Dp.ADVANCED_TRANSACTION_MARKER&&oo===Dp.ADVANCED_TRANSACTION_FLAG?ao=!0:ro.offset-=2;const so=ro.readVarInt();for(let lo=0;loeo.witness.length!==0)}weight(){const eo=this.byteLength(!1),to=this.byteLength(!0);return eo*3+to}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(eo=!0){const to=eo&&this.hasWitnesses();return(to?10:8)+bufferutils_1$2.varuint.encodingLength(this.ins.length)+bufferutils_1$2.varuint.encodingLength(this.outs.length)+this.ins.reduce((ro,no)=>ro+40+varSliceSize(no.script),0)+this.outs.reduce((ro,no)=>ro+8+varSliceSize(no.script),0)+(to?this.ins.reduce((ro,no)=>ro+vectorSize(no.witness),0):0)}clone(){const eo=new Dp;return eo.version=this.version,eo.locktime=this.locktime,eo.ins=this.ins.map(to=>({hash:to.hash,index:to.index,script:to.script,sequence:to.sequence,witness:to.witness})),eo.outs=this.outs.map(to=>({script:to.script,value:to.value})),eo}hashForSignature(eo,to,ro){if(typeforce$1(types$3.tuple(types$3.UInt32,types$3.Buffer,types$3.Number),arguments),eo>=this.ins.length)return ONE;const no=bscript$2.compile(bscript$2.decompile(to).filter(ao=>ao!==script_1.OPS.OP_CODESEPARATOR)),io=this.clone();if((ro&31)===Dp.SIGHASH_NONE)io.outs=[],io.ins.forEach((ao,so)=>{so!==eo&&(ao.sequence=0)});else if((ro&31)===Dp.SIGHASH_SINGLE){if(eo>=this.outs.length)return ONE;io.outs.length=eo+1;for(let ao=0;ao{so!==eo&&(ao.sequence=0)})}ro&Dp.SIGHASH_ANYONECANPAY?(io.ins=[io.ins[eo]],io.ins[0].script=no):(io.ins.forEach(ao=>{ao.script=EMPTY_BUFFER}),io.ins[eo].script=no);const oo=Buffer$3.allocUnsafe(io.byteLength(!1)+4);return oo.writeInt32LE(ro,oo.length-4),io.__toBuffer(oo,0,!1),bcrypto$1.hash256(oo)}hashForWitnessV1(eo,to,ro,no,io,oo){if(typeforce$1(types$3.tuple(types$3.UInt32,typeforce$1.arrayOf(types$3.Buffer),typeforce$1.arrayOf(types$3.Satoshi),types$3.UInt32),arguments),ro.length!==this.ins.length||to.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const ao=no===Dp.SIGHASH_DEFAULT?Dp.SIGHASH_ALL:no&Dp.SIGHASH_OUTPUT_MASK,co=(no&Dp.SIGHASH_INPUT_MASK)===Dp.SIGHASH_ANYONECANPAY,lo=ao===Dp.SIGHASH_NONE,fo=ao===Dp.SIGHASH_SINGLE;let ho=EMPTY_BUFFER,go=EMPTY_BUFFER,yo=EMPTY_BUFFER,vo=EMPTY_BUFFER,wo=EMPTY_BUFFER;if(!co){let Po=bufferutils_1$2.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(jo=>{Po.writeSlice(jo.hash),Po.writeUInt32(jo.index)}),ho=bcrypto$1.sha256(Po.end()),Po=bufferutils_1$2.BufferWriter.withCapacity(8*this.ins.length),ro.forEach(jo=>Po.writeUInt64(jo)),go=bcrypto$1.sha256(Po.end()),Po=bufferutils_1$2.BufferWriter.withCapacity(to.map(varSliceSize).reduce((jo,Mo)=>jo+Mo)),to.forEach(jo=>Po.writeVarSlice(jo)),yo=bcrypto$1.sha256(Po.end()),Po=bufferutils_1$2.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(jo=>Po.writeUInt32(jo.sequence)),vo=bcrypto$1.sha256(Po.end())}if(lo||fo){if(fo&&eo8+varSliceSize(Mo.script)).reduce((Mo,No)=>Mo+No),jo=bufferutils_1$2.BufferWriter.withCapacity(Po);this.outs.forEach(Mo=>{jo.writeUInt64(Mo.value),jo.writeVarSlice(Mo.script)}),wo=bcrypto$1.sha256(jo.end())}const Eo=(io?2:0)+(oo?1:0),ko=174-(co?49:0)-(lo?32:0)+(oo?32:0)+(io?37:0),Ao=bufferutils_1$2.BufferWriter.withCapacity(ko);if(Ao.writeUInt8(no),Ao.writeInt32(this.version),Ao.writeUInt32(this.locktime),Ao.writeSlice(ho),Ao.writeSlice(go),Ao.writeSlice(yo),Ao.writeSlice(vo),lo||fo||Ao.writeSlice(wo),Ao.writeUInt8(Eo),co){const Po=this.ins[eo];Ao.writeSlice(Po.hash),Ao.writeUInt32(Po.index),Ao.writeUInt64(ro[eo]),Ao.writeVarSlice(to[eo]),Ao.writeUInt32(Po.sequence)}else Ao.writeUInt32(eo);if(oo){const Po=bufferutils_1$2.BufferWriter.withCapacity(varSliceSize(oo));Po.writeVarSlice(oo),Ao.writeSlice(bcrypto$1.sha256(Po.end()))}return fo&&Ao.writeSlice(wo),io&&(Ao.writeSlice(io),Ao.writeUInt8(0),Ao.writeUInt32(4294967295)),bcrypto$1.taggedHash("TapSighash",Buffer$3.concat([Buffer$3.from([0]),Ao.end()]))}hashForWitnessV0(eo,to,ro,no){typeforce$1(types$3.tuple(types$3.UInt32,types$3.Buffer,types$3.Satoshi,types$3.UInt32),arguments);let io=Buffer$3.from([]),oo,ao=ZERO$1,so=ZERO$1,co=ZERO$1;if(no&Dp.SIGHASH_ANYONECANPAY||(io=Buffer$3.allocUnsafe(36*this.ins.length),oo=new bufferutils_1$2.BufferWriter(io,0),this.ins.forEach(fo=>{oo.writeSlice(fo.hash),oo.writeUInt32(fo.index)}),so=bcrypto$1.hash256(io)),!(no&Dp.SIGHASH_ANYONECANPAY)&&(no&31)!==Dp.SIGHASH_SINGLE&&(no&31)!==Dp.SIGHASH_NONE&&(io=Buffer$3.allocUnsafe(4*this.ins.length),oo=new bufferutils_1$2.BufferWriter(io,0),this.ins.forEach(fo=>{oo.writeUInt32(fo.sequence)}),co=bcrypto$1.hash256(io)),(no&31)!==Dp.SIGHASH_SINGLE&&(no&31)!==Dp.SIGHASH_NONE){const fo=this.outs.reduce((ho,go)=>ho+8+varSliceSize(go.script),0);io=Buffer$3.allocUnsafe(fo),oo=new bufferutils_1$2.BufferWriter(io,0),this.outs.forEach(ho=>{oo.writeUInt64(ho.value),oo.writeVarSlice(ho.script)}),ao=bcrypto$1.hash256(io)}else if((no&31)===Dp.SIGHASH_SINGLE&&eo{no.writeSlice(oo.hash),no.writeUInt32(oo.index),no.writeVarSlice(oo.script),no.writeUInt32(oo.sequence)}),no.writeVarInt(this.outs.length),this.outs.forEach(oo=>{isOutput(oo)?no.writeUInt64(oo.value):no.writeSlice(oo.valueBuffer),no.writeVarSlice(oo.script)}),io&&this.ins.forEach(oo=>{no.writeVector(oo.witness)}),no.writeUInt32(this.locktime),to!==void 0?eo.slice(to,no.offset):eo}};transaction.Transaction=Transaction$1;Transaction$1.DEFAULT_SEQUENCE=4294967295;Transaction$1.SIGHASH_DEFAULT=0;Transaction$1.SIGHASH_ALL=1;Transaction$1.SIGHASH_NONE=2;Transaction$1.SIGHASH_SINGLE=3;Transaction$1.SIGHASH_ANYONECANPAY=128;Transaction$1.SIGHASH_OUTPUT_MASK=3;Transaction$1.SIGHASH_INPUT_MASK=128;Transaction$1.ADVANCED_TRANSACTION_MARKER=0;Transaction$1.ADVANCED_TRANSACTION_FLAG=1;Object.defineProperty(block,"__esModule",{value:!0});block.Block=void 0;const bufferutils_1$1=bufferutils,bcrypto=crypto$3,merkle_1=merkle,transaction_1$3=transaction,types$2=types$7,{typeforce}=types$2,errorMerkleNoTxes=new TypeError("Cannot compute merkle root for zero transactions"),errorWitnessNotSegwit=new TypeError("Cannot compute witness commit for non-segwit block");let Block$1=class K0{constructor(){this.version=1,this.prevHash=void 0,this.merkleRoot=void 0,this.timestamp=0,this.witnessCommit=void 0,this.bits=0,this.nonce=0,this.transactions=void 0}static fromBuffer(eo){if(eo.length<80)throw new Error("Buffer too small (< 80 bytes)");const to=new bufferutils_1$1.BufferReader(eo),ro=new K0;if(ro.version=to.readInt32(),ro.prevHash=to.readSlice(32),ro.merkleRoot=to.readSlice(32),ro.timestamp=to.readUInt32(),ro.bits=to.readUInt32(),ro.nonce=to.readUInt32(),eo.length===80)return ro;const no=()=>{const ao=transaction_1$3.Transaction.fromBuffer(to.buffer.slice(to.offset),!0);return to.offset+=ao.byteLength(),ao},io=to.readVarInt();ro.transactions=[];for(let ao=0;ao>24)-3,ro=eo&8388607,no=Buffer$3.alloc(32,0);return no.writeUIntBE(ro,29-to,3),no}static calculateMerkleRoot(eo,to){if(typeforce([{getHash:types$2.Function}],eo),eo.length===0)throw errorMerkleNoTxes;if(to&&!txesHaveWitnessCommit(eo))throw errorWitnessNotSegwit;const ro=eo.map(io=>io.getHash(to)),no=(0,merkle_1.fastMerkleRoot)(ro,bcrypto.hash256);return to?bcrypto.hash256(Buffer$3.concat([no,eo[0].ins[0].witness[0]])):no}getWitnessCommit(){if(!txesHaveWitnessCommit(this.transactions))return null;const eo=this.transactions[0].outs.filter(ro=>ro.script.slice(0,6).equals(Buffer$3.from("6a24aa21a9ed","hex"))).map(ro=>ro.script.slice(6,38));if(eo.length===0)return null;const to=eo[eo.length-1];return to instanceof Buffer$3&&to.length===32?to:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer$3&&this.witnessCommit.length===32||this.getWitnessCommit()!==null}hasWitness(){return anyTxHasWitness(this.transactions)}weight(){const eo=this.byteLength(!1,!1),to=this.byteLength(!1,!0);return eo*3+to}byteLength(eo,to=!0){return eo||!this.transactions?80:80+bufferutils_1$1.varuint.encodingLength(this.transactions.length)+this.transactions.reduce((ro,no)=>ro+no.byteLength(to),0)}getHash(){return bcrypto.hash256(this.toBuffer(!0))}getId(){return(0,bufferutils_1$1.reverseBuffer)(this.getHash()).toString("hex")}getUTCDate(){const eo=new Date(0);return eo.setUTCSeconds(this.timestamp),eo}toBuffer(eo){const to=Buffer$3.allocUnsafe(this.byteLength(eo)),ro=new bufferutils_1$1.BufferWriter(to);return ro.writeInt32(this.version),ro.writeSlice(this.prevHash),ro.writeSlice(this.merkleRoot),ro.writeUInt32(this.timestamp),ro.writeUInt32(this.bits),ro.writeUInt32(this.nonce),eo||!this.transactions||(bufferutils_1$1.varuint.encode(this.transactions.length,to,ro.offset),ro.offset+=bufferutils_1$1.varuint.encode.bytes,this.transactions.forEach(no=>{const io=no.byteLength();no.toBuffer(to,ro.offset),ro.offset+=io})),to}toHex(eo){return this.toBuffer(eo).toString("hex")}checkTxRoots(){const eo=this.hasWitnessCommit();return!eo&&this.hasWitness()?!1:this.__checkMerkleRoot()&&(eo?this.__checkWitnessCommit():!0)}checkProofOfWork(){const eo=(0,bufferutils_1$1.reverseBuffer)(this.getHash()),to=K0.calculateTarget(this.bits);return eo.compare(to)<=0}__checkMerkleRoot(){if(!this.transactions)throw errorMerkleNoTxes;const eo=K0.calculateMerkleRoot(this.transactions);return this.merkleRoot.compare(eo)===0}__checkWitnessCommit(){if(!this.transactions)throw errorMerkleNoTxes;if(!this.hasWitnessCommit())throw errorWitnessNotSegwit;const eo=K0.calculateMerkleRoot(this.transactions,!0);return this.witnessCommit.compare(eo)===0}};block.Block=Block$1;function txesHaveWitnessCommit(Xr){return Xr instanceof Array&&Xr[0]&&Xr[0].ins&&Xr[0].ins instanceof Array&&Xr[0].ins[0]&&Xr[0].ins[0].witness&&Xr[0].ins[0].witness instanceof Array&&Xr[0].ins[0].witness.length>0}function anyTxHasWitness(Xr){return Xr instanceof Array&&Xr.some(eo=>typeof eo=="object"&&eo.ins instanceof Array&&eo.ins.some(to=>typeof to=="object"&&to.witness instanceof Array&&to.witness.length>0))}var psbt$1={},psbt={},combiner={},parser={},fromBuffer={},converter={},typeFields={};(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),function(eo){eo[eo.UNSIGNED_TX=0]="UNSIGNED_TX",eo[eo.GLOBAL_XPUB=1]="GLOBAL_XPUB"}(Xr.GlobalTypes||(Xr.GlobalTypes={})),Xr.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],function(eo){eo[eo.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",eo[eo.WITNESS_UTXO=1]="WITNESS_UTXO",eo[eo.PARTIAL_SIG=2]="PARTIAL_SIG",eo[eo.SIGHASH_TYPE=3]="SIGHASH_TYPE",eo[eo.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",eo[eo.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",eo[eo.BIP32_DERIVATION=6]="BIP32_DERIVATION",eo[eo.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",eo[eo.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",eo[eo.POR_COMMITMENT=9]="POR_COMMITMENT",eo[eo.TAP_KEY_SIG=19]="TAP_KEY_SIG",eo[eo.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",eo[eo.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",eo[eo.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",eo[eo.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",eo[eo.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"}(Xr.InputTypes||(Xr.InputTypes={})),Xr.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment","tapKeySig","tapScriptSig","tapLeafScript","tapBip32Derivation","tapInternalKey","tapMerkleRoot"],function(eo){eo[eo.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",eo[eo.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",eo[eo.BIP32_DERIVATION=2]="BIP32_DERIVATION",eo[eo.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",eo[eo.TAP_TREE=6]="TAP_TREE",eo[eo.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"}(Xr.OutputTypes||(Xr.OutputTypes={})),Xr.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation","tapInternalKey","tapTree","tapBip32Derivation"]})(typeFields);var globalXpub$1={};Object.defineProperty(globalXpub$1,"__esModule",{value:!0});const typeFields_1$g=typeFields,range$3=Xr=>[...Array(Xr).keys()];function decode$j(Xr){if(Xr.key[0]!==typeFields_1$g.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+Xr.key.toString("hex"));if(Xr.key.length!==79||![2,3].includes(Xr.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+Xr.key.toString("hex"));if(Xr.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const eo=Xr.key.slice(1),to={masterFingerprint:Xr.value.slice(0,4),extendedPubkey:eo,path:"m"};for(const ro of range$3(Xr.value.length/4-1)){const no=Xr.value.readUInt32LE(ro*4+4),io=!!(no&2147483648),oo=no&2147483647;to.path+="/"+oo.toString(10)+(io?"'":"")}return to}globalXpub$1.decode=decode$j;function encode$h(Xr){const eo=Buffer$3.from([typeFields_1$g.GlobalTypes.GLOBAL_XPUB]),to=Buffer$3.concat([eo,Xr.extendedPubkey]),ro=Xr.path.split("/"),no=Buffer$3.allocUnsafe(ro.length*4);Xr.masterFingerprint.copy(no,0);let io=4;return ro.slice(1).forEach(oo=>{const ao=oo.slice(-1)==="'";let so=2147483647&parseInt(ao?oo.slice(0,-1):oo,10);ao&&(so+=2147483648),no.writeUInt32LE(so,io),io+=4}),{key:to,value:no}}globalXpub$1.encode=encode$h;globalXpub$1.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }";function check$c(Xr){const eo=Xr.extendedPubkey,to=Xr.masterFingerprint,ro=Xr.path;return Buffer$3.isBuffer(eo)&&eo.length===78&&[2,3].indexOf(eo[45])>-1&&Buffer$3.isBuffer(to)&&to.length===4&&typeof ro=="string"&&!!ro.match(/^m(\/\d+'?)*$/)}globalXpub$1.check=check$c;function canAddToArray$3(Xr,eo,to){const ro=eo.extendedPubkey.toString("hex");return to.has(ro)?!1:(to.add(ro),Xr.filter(no=>no.extendedPubkey.equals(eo.extendedPubkey)).length===0)}globalXpub$1.canAddToArray=canAddToArray$3;var unsignedTx$1={};Object.defineProperty(unsignedTx$1,"__esModule",{value:!0});const typeFields_1$f=typeFields;function encode$g(Xr){return{key:Buffer$3.from([typeFields_1$f.GlobalTypes.UNSIGNED_TX]),value:Xr.toBuffer()}}unsignedTx$1.encode=encode$g;var finalScriptSig$1={};Object.defineProperty(finalScriptSig$1,"__esModule",{value:!0});const typeFields_1$e=typeFields;function decode$i(Xr){if(Xr.key[0]!==typeFields_1$e.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+Xr.key.toString("hex"));return Xr.value}finalScriptSig$1.decode=decode$i;function encode$f(Xr){return{key:Buffer$3.from([typeFields_1$e.InputTypes.FINAL_SCRIPTSIG]),value:Xr}}finalScriptSig$1.encode=encode$f;finalScriptSig$1.expected="Buffer";function check$b(Xr){return Buffer$3.isBuffer(Xr)}finalScriptSig$1.check=check$b;function canAdd$8(Xr,eo){return!!Xr&&!!eo&&Xr.finalScriptSig===void 0}finalScriptSig$1.canAdd=canAdd$8;var finalScriptWitness$1={};Object.defineProperty(finalScriptWitness$1,"__esModule",{value:!0});const typeFields_1$d=typeFields;function decode$h(Xr){if(Xr.key[0]!==typeFields_1$d.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+Xr.key.toString("hex"));return Xr.value}finalScriptWitness$1.decode=decode$h;function encode$e(Xr){return{key:Buffer$3.from([typeFields_1$d.InputTypes.FINAL_SCRIPTWITNESS]),value:Xr}}finalScriptWitness$1.encode=encode$e;finalScriptWitness$1.expected="Buffer";function check$a(Xr){return Buffer$3.isBuffer(Xr)}finalScriptWitness$1.check=check$a;function canAdd$7(Xr,eo){return!!Xr&&!!eo&&Xr.finalScriptWitness===void 0}finalScriptWitness$1.canAdd=canAdd$7;var nonWitnessUtxo$1={};Object.defineProperty(nonWitnessUtxo$1,"__esModule",{value:!0});const typeFields_1$c=typeFields;function decode$g(Xr){if(Xr.key[0]!==typeFields_1$c.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+Xr.key.toString("hex"));return Xr.value}nonWitnessUtxo$1.decode=decode$g;function encode$d(Xr){return{key:Buffer$3.from([typeFields_1$c.InputTypes.NON_WITNESS_UTXO]),value:Xr}}nonWitnessUtxo$1.encode=encode$d;nonWitnessUtxo$1.expected="Buffer";function check$9(Xr){return Buffer$3.isBuffer(Xr)}nonWitnessUtxo$1.check=check$9;function canAdd$6(Xr,eo){return!!Xr&&!!eo&&Xr.nonWitnessUtxo===void 0}nonWitnessUtxo$1.canAdd=canAdd$6;var partialSig$1={};Object.defineProperty(partialSig$1,"__esModule",{value:!0});const typeFields_1$b=typeFields;function decode$f(Xr){if(Xr.key[0]!==typeFields_1$b.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+Xr.key.toString("hex"));if(!(Xr.key.length===34||Xr.key.length===66)||![2,3,4].includes(Xr.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+Xr.key.toString("hex"));return{pubkey:Xr.key.slice(1),signature:Xr.value}}partialSig$1.decode=decode$f;function encode$c(Xr){const eo=Buffer$3.from([typeFields_1$b.InputTypes.PARTIAL_SIG]);return{key:Buffer$3.concat([eo,Xr.pubkey]),value:Xr.signature}}partialSig$1.encode=encode$c;partialSig$1.expected="{ pubkey: Buffer; signature: Buffer; }";function check$8(Xr){return Buffer$3.isBuffer(Xr.pubkey)&&Buffer$3.isBuffer(Xr.signature)&&[33,65].includes(Xr.pubkey.length)&&[2,3,4].includes(Xr.pubkey[0])&&isDerSigWithSighash(Xr.signature)}partialSig$1.check=check$8;function isDerSigWithSighash(Xr){if(!Buffer$3.isBuffer(Xr)||Xr.length<9||Xr[0]!==48||Xr.length!==Xr[1]+3||Xr[2]!==2)return!1;const eo=Xr[3];if(eo>33||eo<1||Xr[3+eo+1]!==2)return!1;const to=Xr[3+eo+2];return!(to>33||to<1||Xr.length!==3+eo+2+to+2)}function canAddToArray$2(Xr,eo,to){const ro=eo.pubkey.toString("hex");return to.has(ro)?!1:(to.add(ro),Xr.filter(no=>no.pubkey.equals(eo.pubkey)).length===0)}partialSig$1.canAddToArray=canAddToArray$2;var porCommitment$1={};Object.defineProperty(porCommitment$1,"__esModule",{value:!0});const typeFields_1$a=typeFields;function decode$e(Xr){if(Xr.key[0]!==typeFields_1$a.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+Xr.key.toString("hex"));return Xr.value.toString("utf8")}porCommitment$1.decode=decode$e;function encode$b(Xr){return{key:Buffer$3.from([typeFields_1$a.InputTypes.POR_COMMITMENT]),value:Buffer$3.from(Xr,"utf8")}}porCommitment$1.encode=encode$b;porCommitment$1.expected="string";function check$7(Xr){return typeof Xr=="string"}porCommitment$1.check=check$7;function canAdd$5(Xr,eo){return!!Xr&&!!eo&&Xr.porCommitment===void 0}porCommitment$1.canAdd=canAdd$5;var sighashType$1={};Object.defineProperty(sighashType$1,"__esModule",{value:!0});const typeFields_1$9=typeFields;function decode$d(Xr){if(Xr.key[0]!==typeFields_1$9.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+Xr.key.toString("hex"));return Xr.value.readUInt32LE(0)}sighashType$1.decode=decode$d;function encode$a(Xr){const eo=Buffer$3.from([typeFields_1$9.InputTypes.SIGHASH_TYPE]),to=Buffer$3.allocUnsafe(4);return to.writeUInt32LE(Xr,0),{key:eo,value:to}}sighashType$1.encode=encode$a;sighashType$1.expected="number";function check$6(Xr){return typeof Xr=="number"}sighashType$1.check=check$6;function canAdd$4(Xr,eo){return!!Xr&&!!eo&&Xr.sighashType===void 0}sighashType$1.canAdd=canAdd$4;var tapKeySig$1={};Object.defineProperty(tapKeySig$1,"__esModule",{value:!0});const typeFields_1$8=typeFields;function decode$c(Xr){if(Xr.key[0]!==typeFields_1$8.InputTypes.TAP_KEY_SIG||Xr.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+Xr.key.toString("hex"));if(!check$5(Xr.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return Xr.value}tapKeySig$1.decode=decode$c;function encode$9(Xr){return{key:Buffer$3.from([typeFields_1$8.InputTypes.TAP_KEY_SIG]),value:Xr}}tapKeySig$1.encode=encode$9;tapKeySig$1.expected="Buffer";function check$5(Xr){return Buffer$3.isBuffer(Xr)&&(Xr.length===64||Xr.length===65)}tapKeySig$1.check=check$5;function canAdd$3(Xr,eo){return!!Xr&&!!eo&&Xr.tapKeySig===void 0}tapKeySig$1.canAdd=canAdd$3;var tapLeafScript$1={};Object.defineProperty(tapLeafScript$1,"__esModule",{value:!0});const typeFields_1$7=typeFields;function decode$b(Xr){if(Xr.key[0]!==typeFields_1$7.InputTypes.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+Xr.key.toString("hex"));if((Xr.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+Xr.key.toString("hex"));const eo=Xr.value[Xr.value.length-1];if((Xr.key[1]&254)!==eo)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+Xr.key.toString("hex"));const to=Xr.value.slice(0,-1);return{controlBlock:Xr.key.slice(1),script:to,leafVersion:eo}}tapLeafScript$1.decode=decode$b;function encode$8(Xr){const eo=Buffer$3.from([typeFields_1$7.InputTypes.TAP_LEAF_SCRIPT]),to=Buffer$3.from([Xr.leafVersion]);return{key:Buffer$3.concat([eo,Xr.controlBlock]),value:Buffer$3.concat([Xr.script,to])}}tapLeafScript$1.encode=encode$8;tapLeafScript$1.expected="{ controlBlock: Buffer; leafVersion: number, script: Buffer; }";function check$4(Xr){return Buffer$3.isBuffer(Xr.controlBlock)&&(Xr.controlBlock.length-1)%32===0&&(Xr.controlBlock[0]&254)===Xr.leafVersion&&Buffer$3.isBuffer(Xr.script)}tapLeafScript$1.check=check$4;function canAddToArray$1(Xr,eo,to){const ro=eo.controlBlock.toString("hex");return to.has(ro)?!1:(to.add(ro),Xr.filter(no=>no.controlBlock.equals(eo.controlBlock)).length===0)}tapLeafScript$1.canAddToArray=canAddToArray$1;var tapMerkleRoot$1={};Object.defineProperty(tapMerkleRoot$1,"__esModule",{value:!0});const typeFields_1$6=typeFields;function decode$a(Xr){if(Xr.key[0]!==typeFields_1$6.InputTypes.TAP_MERKLE_ROOT||Xr.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+Xr.key.toString("hex"));if(!check$3(Xr.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return Xr.value}tapMerkleRoot$1.decode=decode$a;function encode$7(Xr){return{key:Buffer$3.from([typeFields_1$6.InputTypes.TAP_MERKLE_ROOT]),value:Xr}}tapMerkleRoot$1.encode=encode$7;tapMerkleRoot$1.expected="Buffer";function check$3(Xr){return Buffer$3.isBuffer(Xr)&&Xr.length===32}tapMerkleRoot$1.check=check$3;function canAdd$2(Xr,eo){return!!Xr&&!!eo&&Xr.tapMerkleRoot===void 0}tapMerkleRoot$1.canAdd=canAdd$2;var tapScriptSig$1={};Object.defineProperty(tapScriptSig$1,"__esModule",{value:!0});const typeFields_1$5=typeFields;function decode$9(Xr){if(Xr.key[0]!==typeFields_1$5.InputTypes.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+Xr.key.toString("hex"));if(Xr.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+Xr.key.toString("hex"));if(Xr.value.length!==64&&Xr.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+Xr.key.toString("hex"));const eo=Xr.key.slice(1,33),to=Xr.key.slice(33);return{pubkey:eo,leafHash:to,signature:Xr.value}}tapScriptSig$1.decode=decode$9;function encode$6(Xr){const eo=Buffer$3.from([typeFields_1$5.InputTypes.TAP_SCRIPT_SIG]);return{key:Buffer$3.concat([eo,Xr.pubkey,Xr.leafHash]),value:Xr.signature}}tapScriptSig$1.encode=encode$6;tapScriptSig$1.expected="{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }";function check$2(Xr){return Buffer$3.isBuffer(Xr.pubkey)&&Buffer$3.isBuffer(Xr.leafHash)&&Buffer$3.isBuffer(Xr.signature)&&Xr.pubkey.length===32&&Xr.leafHash.length===32&&(Xr.signature.length===64||Xr.signature.length===65)}tapScriptSig$1.check=check$2;function canAddToArray(Xr,eo,to){const ro=eo.pubkey.toString("hex")+eo.leafHash.toString("hex");return to.has(ro)?!1:(to.add(ro),Xr.filter(no=>no.pubkey.equals(eo.pubkey)&&no.leafHash.equals(eo.leafHash)).length===0)}tapScriptSig$1.canAddToArray=canAddToArray;var witnessUtxo$1={},tools={},varint={};Object.defineProperty(varint,"__esModule",{value:!0});const MAX_SAFE_INTEGER=9007199254740991;function checkUInt53(Xr){if(Xr<0||Xr>MAX_SAFE_INTEGER||Xr%1!==0)throw new RangeError("value out of range")}function encode$5(Xr,eo,to){if(checkUInt53(Xr),eo||(eo=Buffer$3.allocUnsafe(encodingLength(Xr))),!Buffer$3.isBuffer(eo))throw new TypeError("buffer must be a Buffer instance");return to||(to=0),Xr<253?(eo.writeUInt8(Xr,to),Object.assign(encode$5,{bytes:1})):Xr<=65535?(eo.writeUInt8(253,to),eo.writeUInt16LE(Xr,to+1),Object.assign(encode$5,{bytes:3})):Xr<=4294967295?(eo.writeUInt8(254,to),eo.writeUInt32LE(Xr,to+1),Object.assign(encode$5,{bytes:5})):(eo.writeUInt8(255,to),eo.writeUInt32LE(Xr>>>0,to+1),eo.writeUInt32LE(Xr/4294967296|0,to+5),Object.assign(encode$5,{bytes:9})),eo}varint.encode=encode$5;function decode$8(Xr,eo){if(!Buffer$3.isBuffer(Xr))throw new TypeError("buffer must be a Buffer instance");eo||(eo=0);const to=Xr.readUInt8(eo);if(to<253)return Object.assign(decode$8,{bytes:1}),to;if(to===253)return Object.assign(decode$8,{bytes:3}),Xr.readUInt16LE(eo+1);if(to===254)return Object.assign(decode$8,{bytes:5}),Xr.readUInt32LE(eo+1);{Object.assign(decode$8,{bytes:9});const ro=Xr.readUInt32LE(eo+1),io=Xr.readUInt32LE(eo+5)*4294967296+ro;return checkUInt53(io),io}}varint.decode=decode$8;function encodingLength(Xr){return checkUInt53(Xr),Xr<253?1:Xr<=65535?3:Xr<=4294967295?5:9}varint.encodingLength=encodingLength;Object.defineProperty(tools,"__esModule",{value:!0});const varuint$6=varint;tools.range=Xr=>[...Array(Xr).keys()];function reverseBuffer(Xr){if(Xr.length<1)return Xr;let eo=Xr.length-1,to=0;for(let ro=0;roeo)throw new Error("RangeError: value out of range");if(Math.floor(Xr)!==Xr)throw new Error("value has a fractional component")}function readUInt64LE(Xr,eo){const to=Xr.readUInt32LE(eo);let ro=Xr.readUInt32LE(eo+4);return ro*=4294967296,verifuint(ro+to,9007199254740991),ro+to}tools.readUInt64LE=readUInt64LE;function writeUInt64LE(Xr,eo,to){return verifuint(eo,9007199254740991),Xr.writeInt32LE(eo&-1,to),Xr.writeUInt32LE(Math.floor(eo/4294967296),to+4),to+8}tools.writeUInt64LE=writeUInt64LE;Object.defineProperty(witnessUtxo$1,"__esModule",{value:!0});const typeFields_1$4=typeFields,tools_1$2=tools,varuint$5=varint;function decode$7(Xr){if(Xr.key[0]!==typeFields_1$4.InputTypes.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+Xr.key.toString("hex"));const eo=tools_1$2.readUInt64LE(Xr.value,0);let to=8;const ro=varuint$5.decode(Xr.value,to);to+=varuint$5.encodingLength(ro);const no=Xr.value.slice(to);if(no.length!==ro)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:no,value:eo}}witnessUtxo$1.decode=decode$7;function encode$4(Xr){const{script:eo,value:to}=Xr,ro=varuint$5.encodingLength(eo.length),no=Buffer$3.allocUnsafe(8+ro+eo.length);return tools_1$2.writeUInt64LE(no,to,0),varuint$5.encode(eo.length,no,8),eo.copy(no,8+ro),{key:Buffer$3.from([typeFields_1$4.InputTypes.WITNESS_UTXO]),value:no}}witnessUtxo$1.encode=encode$4;witnessUtxo$1.expected="{ script: Buffer; value: number; }";function check$1(Xr){return Buffer$3.isBuffer(Xr.script)&&typeof Xr.value=="number"}witnessUtxo$1.check=check$1;function canAdd$1(Xr,eo){return!!Xr&&!!eo&&Xr.witnessUtxo===void 0}witnessUtxo$1.canAdd=canAdd$1;var tapTree$1={};Object.defineProperty(tapTree$1,"__esModule",{value:!0});const typeFields_1$3=typeFields,varuint$4=varint;function decode$6(Xr){if(Xr.key[0]!==typeFields_1$3.OutputTypes.TAP_TREE||Xr.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+Xr.key.toString("hex"));let eo=0;const to=[];for(;eo[Buffer$3.of(ro.depth,ro.leafVersion),varuint$4.encode(ro.script.length),ro.script]));return{key:eo,value:Buffer$3.concat(to)}}tapTree$1.encode=encode$3;tapTree$1.expected="{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }";function check(Xr){return Array.isArray(Xr.leaves)&&Xr.leaves.every(eo=>eo.depth>=0&&eo.depth<=128&&(eo.leafVersion&254)===eo.leafVersion&&Buffer$3.isBuffer(eo.script))}tapTree$1.check=check;function canAdd(Xr,eo){return!!Xr&&!!eo&&Xr.tapTree===void 0}tapTree$1.canAdd=canAdd;var bip32Derivation$2={};Object.defineProperty(bip32Derivation$2,"__esModule",{value:!0});const range$2=Xr=>[...Array(Xr).keys()],isValidDERKey=Xr=>Xr.length===33&&[2,3].includes(Xr[0])||Xr.length===65&&Xr[0]===4;function makeConverter$4(Xr,eo=isValidDERKey){function to(ao){if(ao.key[0]!==Xr)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+ao.key.toString("hex"));const so=ao.key.slice(1);if(!eo(so))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+ao.key.toString("hex"));if(ao.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const co={masterFingerprint:ao.value.slice(0,4),pubkey:so,path:"m"};for(const lo of range$2(ao.value.length/4-1)){const fo=ao.value.readUInt32LE(lo*4+4),ho=!!(fo&2147483648),go=fo&2147483647;co.path+="/"+go.toString(10)+(ho?"'":"")}return co}function ro(ao){const so=Buffer$3.from([Xr]),co=Buffer$3.concat([so,ao.pubkey]),lo=ao.path.split("/"),fo=Buffer$3.allocUnsafe(lo.length*4);ao.masterFingerprint.copy(fo,0);let ho=4;return lo.slice(1).forEach(go=>{const yo=go.slice(-1)==="'";let vo=2147483647&parseInt(yo?go.slice(0,-1):go,10);yo&&(vo+=2147483648),fo.writeUInt32LE(vo,ho),ho+=4}),{key:co,value:fo}}const no="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }";function io(ao){return Buffer$3.isBuffer(ao.pubkey)&&Buffer$3.isBuffer(ao.masterFingerprint)&&typeof ao.path=="string"&&eo(ao.pubkey)&&ao.masterFingerprint.length===4}function oo(ao,so,co){const lo=so.pubkey.toString("hex");return co.has(lo)?!1:(co.add(lo),ao.filter(fo=>fo.pubkey.equals(so.pubkey)).length===0)}return{decode:to,encode:ro,check:io,expected:no,canAddToArray:oo}}bip32Derivation$2.makeConverter=makeConverter$4;var checkPubkey$1={};Object.defineProperty(checkPubkey$1,"__esModule",{value:!0});function makeChecker(Xr){return eo;function eo(to){let ro;if(Xr.includes(to.key[0])&&(ro=to.key.slice(1),!(ro.length===33||ro.length===65)||![2,3,4].includes(ro[0])))throw new Error("Format Error: invalid pubkey in key 0x"+to.key.toString("hex"));return ro}}checkPubkey$1.makeChecker=makeChecker;var redeemScript$1={};Object.defineProperty(redeemScript$1,"__esModule",{value:!0});function makeConverter$3(Xr){function eo(oo){if(oo.key[0]!==Xr)throw new Error("Decode Error: could not decode redeemScript with key 0x"+oo.key.toString("hex"));return oo.value}function to(oo){return{key:Buffer$3.from([Xr]),value:oo}}const ro="Buffer";function no(oo){return Buffer$3.isBuffer(oo)}function io(oo,ao){return!!oo&&!!ao&&oo.redeemScript===void 0}return{decode:eo,encode:to,check:no,expected:ro,canAdd:io}}redeemScript$1.makeConverter=makeConverter$3;var tapBip32Derivation$1={};Object.defineProperty(tapBip32Derivation$1,"__esModule",{value:!0});const varuint$3=varint,bip32Derivation$1=bip32Derivation$2,isValidBIP340Key=Xr=>Xr.length===32;function makeConverter$2(Xr){const eo=bip32Derivation$1.makeConverter(Xr,isValidBIP340Key);function to(oo){const ao=varuint$3.decode(oo.value),so=varuint$3.encodingLength(ao),co=eo.decode({key:oo.key,value:oo.value.slice(so+ao*32)}),lo=new Array(ao);for(let fo=0,ho=so;foBuffer$3.isBuffer(ao)&&ao.length===32)&&eo.check(oo)}return{decode:to,encode:ro,check:io,expected:no,canAddToArray:eo.canAddToArray}}tapBip32Derivation$1.makeConverter=makeConverter$2;var tapInternalKey$1={};Object.defineProperty(tapInternalKey$1,"__esModule",{value:!0});function makeConverter$1(Xr){function eo(oo){if(oo.key[0]!==Xr||oo.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+oo.key.toString("hex"));if(oo.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return oo.value}function to(oo){return{key:Buffer$3.from([Xr]),value:oo}}const ro="Buffer";function no(oo){return Buffer$3.isBuffer(oo)&&oo.length===32}function io(oo,ao){return!!oo&&!!ao&&oo.tapInternalKey===void 0}return{decode:eo,encode:to,check:no,expected:ro,canAdd:io}}tapInternalKey$1.makeConverter=makeConverter$1;var witnessScript$1={};Object.defineProperty(witnessScript$1,"__esModule",{value:!0});function makeConverter(Xr){function eo(oo){if(oo.key[0]!==Xr)throw new Error("Decode Error: could not decode witnessScript with key 0x"+oo.key.toString("hex"));return oo.value}function to(oo){return{key:Buffer$3.from([Xr]),value:oo}}const ro="Buffer";function no(oo){return Buffer$3.isBuffer(oo)}function io(oo,ao){return!!oo&&!!ao&&oo.witnessScript===void 0}return{decode:eo,encode:to,check:no,expected:ro,canAdd:io}}witnessScript$1.makeConverter=makeConverter;Object.defineProperty(converter,"__esModule",{value:!0});const typeFields_1$2=typeFields,globalXpub=globalXpub$1,unsignedTx=unsignedTx$1,finalScriptSig=finalScriptSig$1,finalScriptWitness=finalScriptWitness$1,nonWitnessUtxo=nonWitnessUtxo$1,partialSig=partialSig$1,porCommitment=porCommitment$1,sighashType=sighashType$1,tapKeySig=tapKeySig$1,tapLeafScript=tapLeafScript$1,tapMerkleRoot=tapMerkleRoot$1,tapScriptSig=tapScriptSig$1,witnessUtxo=witnessUtxo$1,tapTree=tapTree$1,bip32Derivation=bip32Derivation$2,checkPubkey=checkPubkey$1,redeemScript=redeemScript$1,tapBip32Derivation=tapBip32Derivation$1,tapInternalKey=tapInternalKey$1,witnessScript=witnessScript$1,globals={unsignedTx,globalXpub,checkPubkey:checkPubkey.makeChecker([])};converter.globals=globals;const inputs={nonWitnessUtxo,partialSig,sighashType,finalScriptSig,finalScriptWitness,porCommitment,witnessUtxo,bip32Derivation:bip32Derivation.makeConverter(typeFields_1$2.InputTypes.BIP32_DERIVATION),redeemScript:redeemScript.makeConverter(typeFields_1$2.InputTypes.REDEEM_SCRIPT),witnessScript:witnessScript.makeConverter(typeFields_1$2.InputTypes.WITNESS_SCRIPT),checkPubkey:checkPubkey.makeChecker([typeFields_1$2.InputTypes.PARTIAL_SIG,typeFields_1$2.InputTypes.BIP32_DERIVATION]),tapKeySig,tapScriptSig,tapLeafScript,tapBip32Derivation:tapBip32Derivation.makeConverter(typeFields_1$2.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:tapInternalKey.makeConverter(typeFields_1$2.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot};converter.inputs=inputs;const outputs={bip32Derivation:bip32Derivation.makeConverter(typeFields_1$2.OutputTypes.BIP32_DERIVATION),redeemScript:redeemScript.makeConverter(typeFields_1$2.OutputTypes.REDEEM_SCRIPT),witnessScript:witnessScript.makeConverter(typeFields_1$2.OutputTypes.WITNESS_SCRIPT),checkPubkey:checkPubkey.makeChecker([typeFields_1$2.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:tapBip32Derivation.makeConverter(typeFields_1$2.OutputTypes.TAP_BIP32_DERIVATION),tapTree,tapInternalKey:tapInternalKey.makeConverter(typeFields_1$2.OutputTypes.TAP_INTERNAL_KEY)};converter.outputs=outputs;Object.defineProperty(fromBuffer,"__esModule",{value:!0});const convert$3=converter,tools_1$1=tools,varuint$2=varint,typeFields_1$1=typeFields;function psbtFromBuffer(Xr,eo){let to=0;function ro(){const wo=varuint$2.decode(Xr,to);to+=varuint$2.encodingLength(wo);const Eo=Xr.slice(to,to+wo);return to+=wo,Eo}function no(){const wo=Xr.readUInt32BE(to);return to+=4,wo}function io(){const wo=Xr.readUInt8(to);return to+=1,wo}function oo(){const wo=ro(),Eo=ro();return{key:wo,value:Eo}}function ao(){if(to>=Xr.length)throw new Error("Format Error: Unexpected End of PSBT");const wo=Xr.readUInt8(to)===0;return wo&&to++,wo}if(no()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(io()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const so=[],co={};for(;!ao();){const wo=oo(),Eo=wo.key.toString("hex");if(co[Eo])throw new Error("Format Error: Keys must be unique for global keymap: key "+Eo);co[Eo]=1,so.push(wo)}const lo=so.filter(wo=>wo.key[0]===typeFields_1$1.GlobalTypes.UNSIGNED_TX);if(lo.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const fo=eo(lo[0].value),{inputCount:ho,outputCount:go}=fo.getInputOutputCounts(),yo=[],vo=[];for(const wo of tools_1$1.range(ho)){const Eo={},ko=[];for(;!ao();){const Ao=oo(),Po=Ao.key.toString("hex");if(Eo[Po])throw new Error("Format Error: Keys must be unique for each input: input index "+wo+" key "+Po);Eo[Po]=1,ko.push(Ao)}yo.push(ko)}for(const wo of tools_1$1.range(go)){const Eo={},ko=[];for(;!ao();){const Ao=oo(),Po=Ao.key.toString("hex");if(Eo[Po])throw new Error("Format Error: Keys must be unique for each output: output index "+wo+" key "+Po);Eo[Po]=1,ko.push(Ao)}vo.push(ko)}return psbtFromKeyVals(fo,{globalMapKeyVals:so,inputKeyVals:yo,outputKeyVals:vo})}fromBuffer.psbtFromBuffer=psbtFromBuffer;function checkKeyBuffer(Xr,eo,to){if(!eo.equals(Buffer$3.from([to])))throw new Error(`Format Error: Invalid ${Xr} key: ${eo.toString("hex")}`)}fromBuffer.checkKeyBuffer=checkKeyBuffer;function psbtFromKeyVals(Xr,{globalMapKeyVals:eo,inputKeyVals:to,outputKeyVals:ro}){const no={unsignedTx:Xr};let io=0;for(const lo of eo)switch(lo.key[0]){case typeFields_1$1.GlobalTypes.UNSIGNED_TX:if(checkKeyBuffer("global",lo.key,typeFields_1$1.GlobalTypes.UNSIGNED_TX),io>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");io++;break;case typeFields_1$1.GlobalTypes.GLOBAL_XPUB:no.globalXpub===void 0&&(no.globalXpub=[]),no.globalXpub.push(convert$3.globals.globalXpub.decode(lo));break;default:no.unknownKeyVals||(no.unknownKeyVals=[]),no.unknownKeyVals.push(lo)}const oo=to.length,ao=ro.length,so=[],co=[];for(const lo of tools_1$1.range(oo)){const fo={};for(const ho of to[lo])switch(convert$3.inputs.checkPubkey(ho),ho.key[0]){case typeFields_1$1.InputTypes.NON_WITNESS_UTXO:if(checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.NON_WITNESS_UTXO),fo.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");fo.nonWitnessUtxo=convert$3.inputs.nonWitnessUtxo.decode(ho);break;case typeFields_1$1.InputTypes.WITNESS_UTXO:if(checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.WITNESS_UTXO),fo.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");fo.witnessUtxo=convert$3.inputs.witnessUtxo.decode(ho);break;case typeFields_1$1.InputTypes.PARTIAL_SIG:fo.partialSig===void 0&&(fo.partialSig=[]),fo.partialSig.push(convert$3.inputs.partialSig.decode(ho));break;case typeFields_1$1.InputTypes.SIGHASH_TYPE:if(checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.SIGHASH_TYPE),fo.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");fo.sighashType=convert$3.inputs.sighashType.decode(ho);break;case typeFields_1$1.InputTypes.REDEEM_SCRIPT:if(checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.REDEEM_SCRIPT),fo.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");fo.redeemScript=convert$3.inputs.redeemScript.decode(ho);break;case typeFields_1$1.InputTypes.WITNESS_SCRIPT:if(checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.WITNESS_SCRIPT),fo.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");fo.witnessScript=convert$3.inputs.witnessScript.decode(ho);break;case typeFields_1$1.InputTypes.BIP32_DERIVATION:fo.bip32Derivation===void 0&&(fo.bip32Derivation=[]),fo.bip32Derivation.push(convert$3.inputs.bip32Derivation.decode(ho));break;case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG:checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.FINAL_SCRIPTSIG),fo.finalScriptSig=convert$3.inputs.finalScriptSig.decode(ho);break;case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS:checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS),fo.finalScriptWitness=convert$3.inputs.finalScriptWitness.decode(ho);break;case typeFields_1$1.InputTypes.POR_COMMITMENT:checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.POR_COMMITMENT),fo.porCommitment=convert$3.inputs.porCommitment.decode(ho);break;case typeFields_1$1.InputTypes.TAP_KEY_SIG:checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.TAP_KEY_SIG),fo.tapKeySig=convert$3.inputs.tapKeySig.decode(ho);break;case typeFields_1$1.InputTypes.TAP_SCRIPT_SIG:fo.tapScriptSig===void 0&&(fo.tapScriptSig=[]),fo.tapScriptSig.push(convert$3.inputs.tapScriptSig.decode(ho));break;case typeFields_1$1.InputTypes.TAP_LEAF_SCRIPT:fo.tapLeafScript===void 0&&(fo.tapLeafScript=[]),fo.tapLeafScript.push(convert$3.inputs.tapLeafScript.decode(ho));break;case typeFields_1$1.InputTypes.TAP_BIP32_DERIVATION:fo.tapBip32Derivation===void 0&&(fo.tapBip32Derivation=[]),fo.tapBip32Derivation.push(convert$3.inputs.tapBip32Derivation.decode(ho));break;case typeFields_1$1.InputTypes.TAP_INTERNAL_KEY:checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.TAP_INTERNAL_KEY),fo.tapInternalKey=convert$3.inputs.tapInternalKey.decode(ho);break;case typeFields_1$1.InputTypes.TAP_MERKLE_ROOT:checkKeyBuffer("input",ho.key,typeFields_1$1.InputTypes.TAP_MERKLE_ROOT),fo.tapMerkleRoot=convert$3.inputs.tapMerkleRoot.decode(ho);break;default:fo.unknownKeyVals||(fo.unknownKeyVals=[]),fo.unknownKeyVals.push(ho)}so.push(fo)}for(const lo of tools_1$1.range(ao)){const fo={};for(const ho of ro[lo])switch(convert$3.outputs.checkPubkey(ho),ho.key[0]){case typeFields_1$1.OutputTypes.REDEEM_SCRIPT:if(checkKeyBuffer("output",ho.key,typeFields_1$1.OutputTypes.REDEEM_SCRIPT),fo.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");fo.redeemScript=convert$3.outputs.redeemScript.decode(ho);break;case typeFields_1$1.OutputTypes.WITNESS_SCRIPT:if(checkKeyBuffer("output",ho.key,typeFields_1$1.OutputTypes.WITNESS_SCRIPT),fo.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");fo.witnessScript=convert$3.outputs.witnessScript.decode(ho);break;case typeFields_1$1.OutputTypes.BIP32_DERIVATION:fo.bip32Derivation===void 0&&(fo.bip32Derivation=[]),fo.bip32Derivation.push(convert$3.outputs.bip32Derivation.decode(ho));break;case typeFields_1$1.OutputTypes.TAP_INTERNAL_KEY:checkKeyBuffer("output",ho.key,typeFields_1$1.OutputTypes.TAP_INTERNAL_KEY),fo.tapInternalKey=convert$3.outputs.tapInternalKey.decode(ho);break;case typeFields_1$1.OutputTypes.TAP_TREE:checkKeyBuffer("output",ho.key,typeFields_1$1.OutputTypes.TAP_TREE),fo.tapTree=convert$3.outputs.tapTree.decode(ho);break;case typeFields_1$1.OutputTypes.TAP_BIP32_DERIVATION:fo.tapBip32Derivation===void 0&&(fo.tapBip32Derivation=[]),fo.tapBip32Derivation.push(convert$3.outputs.tapBip32Derivation.decode(ho));break;default:fo.unknownKeyVals||(fo.unknownKeyVals=[]),fo.unknownKeyVals.push(ho)}co.push(fo)}return{globalMap:no,inputs:so,outputs:co}}fromBuffer.psbtFromKeyVals=psbtFromKeyVals;var toBuffer$5={};Object.defineProperty(toBuffer$5,"__esModule",{value:!0});const convert$2=converter,tools_1=tools;function psbtToBuffer({globalMap:Xr,inputs:eo,outputs:to}){const{globalKeyVals:ro,inputKeyVals:no,outputKeyVals:io}=psbtToKeyVals({globalMap:Xr,inputs:eo,outputs:to}),oo=tools_1.keyValsToBuffer(ro),ao=fo=>fo.length===0?[Buffer$3.from([0])]:fo.map(tools_1.keyValsToBuffer),so=ao(no),co=ao(io),lo=Buffer$3.allocUnsafe(5);return lo.writeUIntBE(482972169471,0,5),Buffer$3.concat([lo,oo].concat(so,co))}toBuffer$5.psbtToBuffer=psbtToBuffer;const sortKeyVals=(Xr,eo)=>Xr.key.compare(eo.key);function keyValsFromMap(Xr,eo){const to=new Set,ro=Object.entries(Xr).reduce((io,[oo,ao])=>{if(oo==="unknownKeyVals")return io;const so=eo[oo];if(so===void 0)return io;const co=(Array.isArray(ao)?ao:[ao]).map(so.encode);return co.map(fo=>fo.key.toString("hex")).forEach(fo=>{if(to.has(fo))throw new Error("Serialize Error: Duplicate key: "+fo);to.add(fo)}),io.concat(co)},[]),no=Xr.unknownKeyVals?Xr.unknownKeyVals.filter(io=>!to.has(io.key.toString("hex"))):[];return ro.concat(no).sort(sortKeyVals)}function psbtToKeyVals({globalMap:Xr,inputs:eo,outputs:to}){return{globalKeyVals:keyValsFromMap(Xr,convert$2.globals),inputKeyVals:eo.map(ro=>keyValsFromMap(ro,convert$2.inputs)),outputKeyVals:to.map(ro=>keyValsFromMap(ro,convert$2.outputs))}}toBuffer$5.psbtToKeyVals=psbtToKeyVals;(function(Xr){function eo(to){for(var ro in to)Xr.hasOwnProperty(ro)||(Xr[ro]=to[ro])}Object.defineProperty(Xr,"__esModule",{value:!0}),eo(fromBuffer),eo(toBuffer$5)})(parser);Object.defineProperty(combiner,"__esModule",{value:!0});const parser_1$1=parser;function combine(Xr){const eo=Xr[0],to=parser_1$1.psbtToKeyVals(eo),ro=Xr.slice(1);if(ro.length===0)throw new Error("Combine: Nothing to combine");const no=getTx(eo);if(no===void 0)throw new Error("Combine: Self missing transaction");const io=getKeySet(to.globalKeyVals),oo=to.inputKeyVals.map(getKeySet),ao=to.outputKeyVals.map(getKeySet);for(const so of ro){const co=getTx(so);if(co===void 0||!co.toBuffer().equals(no.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const lo=parser_1$1.psbtToKeyVals(so);getKeySet(lo.globalKeyVals).forEach(keyPusher(io,to.globalKeyVals,lo.globalKeyVals)),lo.inputKeyVals.map(getKeySet).forEach((yo,vo)=>yo.forEach(keyPusher(oo[vo],to.inputKeyVals[vo],lo.inputKeyVals[vo]))),lo.outputKeyVals.map(getKeySet).forEach((yo,vo)=>yo.forEach(keyPusher(ao[vo],to.outputKeyVals[vo],lo.outputKeyVals[vo])))}return parser_1$1.psbtFromKeyVals(no,{globalMapKeyVals:to.globalKeyVals,inputKeyVals:to.inputKeyVals,outputKeyVals:to.outputKeyVals})}combiner.combine=combine;function keyPusher(Xr,eo,to){return ro=>{if(Xr.has(ro))return;const no=to.filter(io=>io.key.toString("hex")===ro)[0];eo.push(no),Xr.add(ro)}}function getTx(Xr){return Xr.globalMap.unsignedTx}function getKeySet(Xr){const eo=new Set;return Xr.forEach(to=>{const ro=to.key.toString("hex");if(eo.has(ro))throw new Error("Combine: KeyValue Map keys should be unique");eo.add(ro)}),eo}var utils$4={};(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0});const eo=converter;function to(go,yo){const vo=go[yo];if(vo===void 0)throw new Error(`No input #${yo}`);return vo}Xr.checkForInput=to;function ro(go,yo){const vo=go[yo];if(vo===void 0)throw new Error(`No output #${yo}`);return vo}Xr.checkForOutput=ro;function no(go,yo,vo){if(go.key[0]wo.key.equals(go.key)).length!==0)throw new Error(`Duplicate Key: ${go.key.toString("hex")}`)}Xr.checkHasKey=no;function io(go){let yo=0;return Object.keys(go).forEach(vo=>{Number(isNaN(Number(vo)))&&yo++}),yo}Xr.getEnumLength=io;function oo(go,yo){let vo=!1;if(yo.nonWitnessUtxo||yo.witnessUtxo){const wo=!!yo.redeemScript,Eo=!!yo.witnessScript,ko=!wo||!!yo.finalScriptSig,Ao=!Eo||!!yo.finalScriptWitness,Po=!!yo.finalScriptSig||!!yo.finalScriptWitness;vo=ko&&Ao&&Po}if(vo===!1)throw new Error(`Input #${go} has too much or too little data to clean`)}Xr.inputCheckUncleanFinalized=oo;function ao(go,yo,vo,wo){throw new Error(`Data for ${go} key ${yo} is incorrect: Expected ${vo} and got ${JSON.stringify(wo)}`)}function so(go){return(yo,vo)=>{for(const wo of Object.keys(yo)){const Eo=yo[wo],{canAdd:ko,canAddToArray:Ao,check:Po,expected:jo}=eo[go+"s"][wo]||{},Mo=!!Ao;if(Po)if(Mo){if(!Array.isArray(Eo)||vo[wo]&&!Array.isArray(vo[wo]))throw new Error(`Key type ${wo} must be an array`);Eo.every(Po)||ao(go,wo,jo,Eo);const No=vo[wo]||[],Do=new Set;if(!Eo.every(Fo=>Ao(No,Fo,Do)))throw new Error("Can not add duplicate data to array");vo[wo]=No.concat(Eo)}else{if(Po(Eo)||ao(go,wo,jo,Eo),!ko(vo,Eo))throw new Error(`Can not add duplicate data to ${go}`);vo[wo]=Eo}}}}Xr.updateGlobal=so("global"),Xr.updateInput=so("input"),Xr.updateOutput=so("output");function co(go,yo){const vo=go.length-1,wo=to(go,vo);Xr.updateInput(yo,wo)}Xr.addInputAttributes=co;function lo(go,yo){const vo=go.length-1,wo=ro(go,vo);Xr.updateOutput(yo,wo)}Xr.addOutputAttributes=lo;function fo(go,yo){if(!Buffer$3.isBuffer(yo)||yo.length<4)throw new Error("Set Version: Invalid Transaction");return yo.writeUInt32LE(go,0),yo}Xr.defaultVersionSetter=fo;function ho(go,yo){if(!Buffer$3.isBuffer(yo)||yo.length<4)throw new Error("Set Locktime: Invalid Transaction");return yo.writeUInt32LE(go,yo.length-4),yo}Xr.defaultLocktimeSetter=ho})(utils$4);Object.defineProperty(psbt,"__esModule",{value:!0});const combiner_1=combiner,parser_1=parser,typeFields_1=typeFields,utils_1$3=utils$4;let Psbt$1=class{constructor(eo){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:eo}}static fromBase64(eo,to){const ro=Buffer$3.from(eo,"base64");return this.fromBuffer(ro,to)}static fromHex(eo,to){const ro=Buffer$3.from(eo,"hex");return this.fromBuffer(ro,to)}static fromBuffer(eo,to){const ro=parser_1.psbtFromBuffer(eo,to),no=new this(ro.globalMap.unsignedTx);return Object.assign(no,ro),no}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return parser_1.psbtToBuffer(this)}updateGlobal(eo){return utils_1$3.updateGlobal(eo,this.globalMap),this}updateInput(eo,to){const ro=utils_1$3.checkForInput(this.inputs,eo);return utils_1$3.updateInput(to,ro),this}updateOutput(eo,to){const ro=utils_1$3.checkForOutput(this.outputs,eo);return utils_1$3.updateOutput(to,ro),this}addUnknownKeyValToGlobal(eo){return utils_1$3.checkHasKey(eo,this.globalMap.unknownKeyVals,utils_1$3.getEnumLength(typeFields_1.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(eo),this}addUnknownKeyValToInput(eo,to){const ro=utils_1$3.checkForInput(this.inputs,eo);return utils_1$3.checkHasKey(to,ro.unknownKeyVals,utils_1$3.getEnumLength(typeFields_1.InputTypes)),ro.unknownKeyVals||(ro.unknownKeyVals=[]),ro.unknownKeyVals.push(to),this}addUnknownKeyValToOutput(eo,to){const ro=utils_1$3.checkForOutput(this.outputs,eo);return utils_1$3.checkHasKey(to,ro.unknownKeyVals,utils_1$3.getEnumLength(typeFields_1.OutputTypes)),ro.unknownKeyVals||(ro.unknownKeyVals=[]),ro.unknownKeyVals.push(to),this}addInput(eo){this.globalMap.unsignedTx.addInput(eo),this.inputs.push({unknownKeyVals:[]});const to=eo.unknownKeyVals||[],ro=this.inputs.length-1;if(!Array.isArray(to))throw new Error("unknownKeyVals must be an Array");return to.forEach(no=>this.addUnknownKeyValToInput(ro,no)),utils_1$3.addInputAttributes(this.inputs,eo),this}addOutput(eo){this.globalMap.unsignedTx.addOutput(eo),this.outputs.push({unknownKeyVals:[]});const to=eo.unknownKeyVals||[],ro=this.outputs.length-1;if(!Array.isArray(to))throw new Error("unknownKeyVals must be an Array");return to.forEach(no=>this.addUnknownKeyValToOutput(ro,no)),utils_1$3.addOutputAttributes(this.outputs,eo),this}clearFinalizedInput(eo){const to=utils_1$3.checkForInput(this.inputs,eo);utils_1$3.inputCheckUncleanFinalized(eo,to);for(const ro of Object.keys(to))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(ro)||delete to[ro];return this}combine(...eo){const to=combiner_1.combine([this].concat(eo));return Object.assign(this,to),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}};psbt.Psbt=Psbt$1;var bip371={},psbtutils={};Object.defineProperty(psbtutils,"__esModule",{value:!0});psbtutils.signatureBlocksAction=psbtutils.checkInputForSig=psbtutils.pubkeyInScript=psbtutils.pubkeyPositionInScript=psbtutils.witnessStackToScriptWitness=psbtutils.isP2TR=psbtutils.isP2SHScript=psbtutils.isP2WSHScript=psbtutils.isP2WPKH=psbtutils.isP2PKH=psbtutils.isP2PK=psbtutils.isP2MS=void 0;const varuint$1=varint,bscript$1=script$1,transaction_1$2=transaction,crypto_1=crypto$3,payments$1=payments$3;function isPaymentFactory(Xr){return eo=>{try{return Xr({output:eo}),!0}catch{return!1}}}psbtutils.isP2MS=isPaymentFactory(payments$1.p2ms);psbtutils.isP2PK=isPaymentFactory(payments$1.p2pk);psbtutils.isP2PKH=isPaymentFactory(payments$1.p2pkh);psbtutils.isP2WPKH=isPaymentFactory(payments$1.p2wpkh);psbtutils.isP2WSHScript=isPaymentFactory(payments$1.p2wsh);psbtutils.isP2SHScript=isPaymentFactory(payments$1.p2sh);psbtutils.isP2TR=isPaymentFactory(payments$1.p2tr);function witnessStackToScriptWitness(Xr){let eo=Buffer$3.allocUnsafe(0);function to(oo){eo=Buffer$3.concat([eo,Buffer$3.from(oo)])}function ro(oo){const ao=eo.length,so=varuint$1.encodingLength(oo);eo=Buffer$3.concat([eo,Buffer$3.allocUnsafe(so)]),varuint$1.encode(oo,eo,ao)}function no(oo){ro(oo.length),to(oo)}function io(oo){ro(oo.length),oo.forEach(no)}return io(Xr),eo}psbtutils.witnessStackToScriptWitness=witnessStackToScriptWitness;function pubkeyPositionInScript(Xr,eo){const to=(0,crypto_1.hash160)(Xr),ro=Xr.slice(1,33),no=bscript$1.decompile(eo);if(no===null)throw new Error("Unknown script error");return no.findIndex(io=>typeof io=="number"?!1:io.equals(Xr)||io.equals(to)||io.equals(ro))}psbtutils.pubkeyPositionInScript=pubkeyPositionInScript;function pubkeyInScript(Xr,eo){return pubkeyPositionInScript(Xr,eo)!==-1}psbtutils.pubkeyInScript=pubkeyInScript;function checkInputForSig(Xr,eo){return extractPartialSigs(Xr).some(ro=>signatureBlocksAction(ro,bscript$1.signature.decode,eo))}psbtutils.checkInputForSig=checkInputForSig;function signatureBlocksAction(Xr,eo,to){const{hashType:ro}=eo(Xr),no=[];switch(ro&transaction_1$2.Transaction.SIGHASH_ANYONECANPAY&&no.push("addInput"),ro&31){case transaction_1$2.Transaction.SIGHASH_ALL:break;case transaction_1$2.Transaction.SIGHASH_SINGLE:case transaction_1$2.Transaction.SIGHASH_NONE:no.push("addOutput"),no.push("setInputSequence");break}return no.indexOf(to)===-1}psbtutils.signatureBlocksAction=signatureBlocksAction;function extractPartialSigs(Xr){let eo=[];if((Xr.partialSig||[]).length===0){if(!Xr.finalScriptSig&&!Xr.finalScriptWitness)return[];eo=getPsigsFromInputFinalScripts(Xr)}else eo=Xr.partialSig;return eo.map(to=>to.signature)}function getPsigsFromInputFinalScripts(Xr){const eo=Xr.finalScriptSig?bscript$1.decompile(Xr.finalScriptSig)||[]:[],to=Xr.finalScriptWitness?bscript$1.decompile(Xr.finalScriptWitness)||[]:[];return eo.concat(to).filter(ro=>Buffer$3.isBuffer(ro)&&bscript$1.isCanonicalScriptSignature(ro)).map(ro=>({signature:ro}))}Object.defineProperty(bip371,"__esModule",{value:!0});bip371.checkTaprootInputForSigs=bip371.tapTreeFromList=bip371.tapTreeToList=bip371.tweakInternalPubKey=bip371.checkTaprootOutputFields=bip371.checkTaprootInputFields=bip371.isTaprootOutput=bip371.isTaprootInput=bip371.serializeTaprootSignature=bip371.tapScriptFinalizer=bip371.toXOnly=void 0;const types_1=types$7,transaction_1$1=transaction,psbtutils_1$1=psbtutils,bip341_1$1=bip341,payments_1=payments$3,psbtutils_2=psbtutils,toXOnly=Xr=>Xr.length===32?Xr:Xr.slice(1,33);bip371.toXOnly=toXOnly;function tapScriptFinalizer(Xr,eo,to){const ro=findTapLeafToFinalize(eo,Xr,to);try{const io=sortSignatures(eo,ro).concat(ro.script).concat(ro.controlBlock);return{finalScriptWitness:(0,psbtutils_1$1.witnessStackToScriptWitness)(io)}}catch(no){throw new Error(`Can not finalize taproot input #${Xr}: ${no}`)}}bip371.tapScriptFinalizer=tapScriptFinalizer;function serializeTaprootSignature(Xr,eo){const to=eo?Buffer$3.from([eo]):Buffer$3.from([]);return Buffer$3.concat([Xr,to])}bip371.serializeTaprootSignature=serializeTaprootSignature;function isTaprootInput(Xr){return Xr&&!!(Xr.tapInternalKey||Xr.tapMerkleRoot||Xr.tapLeafScript&&Xr.tapLeafScript.length||Xr.tapBip32Derivation&&Xr.tapBip32Derivation.length||Xr.witnessUtxo&&(0,psbtutils_1$1.isP2TR)(Xr.witnessUtxo.script))}bip371.isTaprootInput=isTaprootInput;function isTaprootOutput(Xr,eo){return Xr&&!!(Xr.tapInternalKey||Xr.tapTree||Xr.tapBip32Derivation&&Xr.tapBip32Derivation.length||eo&&(0,psbtutils_1$1.isP2TR)(eo))}bip371.isTaprootOutput=isTaprootOutput;function checkTaprootInputFields(Xr,eo,to){checkMixedTaprootAndNonTaprootInputFields(Xr,eo,to),checkIfTapLeafInTree(Xr,eo,to)}bip371.checkTaprootInputFields=checkTaprootInputFields;function checkTaprootOutputFields(Xr,eo,to){checkMixedTaprootAndNonTaprootOutputFields(Xr,eo,to),checkTaprootScriptPubkey(Xr,eo)}bip371.checkTaprootOutputFields=checkTaprootOutputFields;function checkTaprootScriptPubkey(Xr,eo){if(!eo.tapTree&&!eo.tapInternalKey)return;const to=eo.tapInternalKey||Xr.tapInternalKey,ro=eo.tapTree||Xr.tapTree;if(to){const{script:no}=Xr,io=getTaprootScripPubkey(to,ro);if(no&&!no.equals(io))throw new Error("Error adding output. Script or address missmatch.")}}function getTaprootScripPubkey(Xr,eo){const to=eo&&tapTreeFromList(eo.leaves),{output:ro}=(0,payments_1.p2tr)({internalPubkey:Xr,scriptTree:to});return ro}function tweakInternalPubKey(Xr,eo){const to=eo.tapInternalKey,ro=to&&(0,bip341_1$1.tweakKey)(to,eo.tapMerkleRoot);if(!ro)throw new Error(`Cannot tweak tap internal key for input #${Xr}. Public key: ${to&&to.toString("hex")}`);return ro.x}bip371.tweakInternalPubKey=tweakInternalPubKey;function tapTreeToList(Xr){if(!(0,types_1.isTaptree)(Xr))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return _tapTreeToList(Xr)}bip371.tapTreeToList=tapTreeToList;function tapTreeFromList(Xr=[]){return Xr.length===1&&Xr[0].depth===0?{output:Xr[0].script,version:Xr[0].leafVersion}:instertLeavesInTree(Xr)}bip371.tapTreeFromList=tapTreeFromList;function checkTaprootInputForSigs(Xr,eo){return extractTaprootSigs(Xr).some(ro=>(0,psbtutils_2.signatureBlocksAction)(ro,decodeSchnorrSignature,eo))}bip371.checkTaprootInputForSigs=checkTaprootInputForSigs;function decodeSchnorrSignature(Xr){return{signature:Xr.slice(0,64),hashType:Xr.slice(64)[0]||transaction_1$1.Transaction.SIGHASH_DEFAULT}}function extractTaprootSigs(Xr){const eo=[];if(Xr.tapKeySig&&eo.push(Xr.tapKeySig),Xr.tapScriptSig&&eo.push(...Xr.tapScriptSig.map(to=>to.signature)),!eo.length){const to=getTapKeySigFromWithness(Xr.finalScriptWitness);to&&eo.push(to)}return eo}function getTapKeySigFromWithness(Xr){if(!Xr)return;const eo=Xr.slice(2);if(eo.length===64||eo.length===65)return eo}function _tapTreeToList(Xr,eo=[],to=0){if(to>bip341_1$1.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return Xr?(0,types_1.isTapleaf)(Xr)?(eo.push({depth:to,leafVersion:Xr.version||bip341_1$1.LEAF_VERSION_TAPSCRIPT,script:Xr.output}),eo):(Xr[0]&&_tapTreeToList(Xr[0],eo,to+1),Xr[1]&&_tapTreeToList(Xr[1],eo,to+1),eo):[]}function instertLeavesInTree(Xr){let eo;for(const to of Xr)if(eo=instertLeafInTree(to,eo),!eo)throw new Error("No room left to insert tapleaf in tree");return eo}function instertLeafInTree(Xr,eo,to=0){if(to>bip341_1$1.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(Xr.depth===to)return eo?void 0:{output:Xr.script,version:Xr.leafVersion};if((0,types_1.isTapleaf)(eo))return;const ro=instertLeafInTree(Xr,eo&&eo[0],to+1);if(ro)return[ro,eo&&eo[1]];const no=instertLeafInTree(Xr,eo&&eo[1],to+1);if(no)return[eo&&eo[0],no]}function checkMixedTaprootAndNonTaprootInputFields(Xr,eo,to){const ro=isTaprootInput(Xr)&&hasNonTaprootFields(eo),no=hasNonTaprootFields(Xr)&&isTaprootInput(eo),io=Xr===eo&&isTaprootInput(eo)&&hasNonTaprootFields(eo);if(ro||no||io)throw new Error(`Invalid arguments for Psbt.${to}. Cannot use both taproot and non-taproot fields.`)}function checkMixedTaprootAndNonTaprootOutputFields(Xr,eo,to){const ro=isTaprootOutput(Xr)&&hasNonTaprootFields(eo),no=hasNonTaprootFields(Xr)&&isTaprootOutput(eo),io=Xr===eo&&isTaprootOutput(eo)&&hasNonTaprootFields(eo);if(ro||no||io)throw new Error(`Invalid arguments for Psbt.${to}. Cannot use both taproot and non-taproot fields.`)}function checkIfTapLeafInTree(Xr,eo,to){if(eo.tapMerkleRoot){const ro=(eo.tapLeafScript||[]).every(io=>isTapLeafInTree(io,eo.tapMerkleRoot)),no=(Xr.tapLeafScript||[]).every(io=>isTapLeafInTree(io,eo.tapMerkleRoot));if(!ro||!no)throw new Error(`Invalid arguments for Psbt.${to}. Tapleaf not part of taptree.`)}else if(Xr.tapMerkleRoot&&!(eo.tapLeafScript||[]).every(no=>isTapLeafInTree(no,Xr.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${to}. Tapleaf not part of taptree.`)}function isTapLeafInTree(Xr,eo){if(!eo)return!0;const to=(0,bip341_1$1.tapleafHash)({output:Xr.script,version:Xr.leafVersion});return(0,bip341_1$1.rootHashFromPath)(Xr.controlBlock,to).equals(eo)}function sortSignatures(Xr,eo){const to=(0,bip341_1$1.tapleafHash)({output:eo.script,version:eo.leafVersion});return(Xr.tapScriptSig||[]).filter(ro=>ro.leafHash.equals(to)).map(ro=>addPubkeyPositionInScript(eo.script,ro)).sort((ro,no)=>no.positionInScript-ro.positionInScript).map(ro=>ro.signature)}function addPubkeyPositionInScript(Xr,eo){return Object.assign({positionInScript:(0,psbtutils_1$1.pubkeyPositionInScript)(eo.pubkey,Xr)},eo)}function findTapLeafToFinalize(Xr,eo,to){if(!Xr.tapScriptSig||!Xr.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${eo}. No tapleaf script signature provided.`);const ro=(Xr.tapLeafScript||[]).sort((no,io)=>no.controlBlock.length-io.controlBlock.length).find(no=>canFinalizeLeaf(no,Xr.tapScriptSig,to));if(!ro)throw new Error(`Can not finalize taproot input #${eo}. Signature for tapleaf script not found.`);return ro}function canFinalizeLeaf(Xr,eo,to){const ro=(0,bip341_1$1.tapleafHash)({output:Xr.script,version:Xr.leafVersion});return(!to||to.equals(ro))&&eo.find(io=>io.leafHash.equals(ro))!==void 0}function hasNonTaprootFields(Xr){return Xr&&!!(Xr.redeemScript||Xr.witnessScript||Xr.bip32Derivation&&Xr.bip32Derivation.length)}Object.defineProperty(psbt$1,"__esModule",{value:!0});psbt$1.Psbt=void 0;const bip174_1=psbt,varuint=varint,utils_1$2=utils$4,address_1=address,bufferutils_1=bufferutils,networks_1=networks$1,payments=payments$3,bip341_1=bip341,bscript=script$1,transaction_1=transaction,bip371_1=bip371,psbtutils_1=psbtutils,DEFAULT_OPTS={network:networks_1.bitcoin,maximumFeeRate:5e3};class Psbt{static fromBase64(eo,to={}){const ro=Buffer$3.from(eo,"base64");return this.fromBuffer(ro,to)}static fromHex(eo,to={}){const ro=Buffer$3.from(eo,"hex");return this.fromBuffer(ro,to)}static fromBuffer(eo,to={}){const ro=bip174_1.Psbt.fromBuffer(eo,transactionFromBuffer),no=new Psbt(to,ro);return checkTxForDupeIns(no.__CACHE.__TX,no.__CACHE),no}constructor(eo={},to=new bip174_1.Psbt(new PsbtTransaction)){this.data=to,this.opts=Object.assign({},DEFAULT_OPTS,eo),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const ro=(no,io,oo,ao)=>Object.defineProperty(no,io,{enumerable:oo,writable:ao});ro(this,"__CACHE",!1,!0),ro(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(eo){this.setVersion(eo)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(eo){this.setLocktime(eo)}get txInputs(){return this.__CACHE.__TX.ins.map(eo=>({hash:(0,bufferutils_1.cloneBuffer)(eo.hash),index:eo.index,sequence:eo.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(eo=>{let to;try{to=(0,address_1.fromOutputScript)(eo.script,this.opts.network)}catch{}return{script:(0,bufferutils_1.cloneBuffer)(eo.script),value:eo.value,address:to}})}combine(...eo){return this.data.combine(...eo.map(to=>to.data)),this}clone(){const eo=Psbt.fromBuffer(this.data.toBuffer());return eo.opts=JSON.parse(JSON.stringify(this.opts)),eo}setMaximumFeeRate(eo){check32Bit(eo),this.opts.maximumFeeRate=eo}setVersion(eo){check32Bit(eo),checkInputsForPartialSig(this.data.inputs,"setVersion");const to=this.__CACHE;return to.__TX.version=eo,to.__EXTRACTED_TX=void 0,this}setLocktime(eo){check32Bit(eo),checkInputsForPartialSig(this.data.inputs,"setLocktime");const to=this.__CACHE;return to.__TX.locktime=eo,to.__EXTRACTED_TX=void 0,this}setInputSequence(eo,to){check32Bit(to),checkInputsForPartialSig(this.data.inputs,"setInputSequence");const ro=this.__CACHE;if(ro.__TX.ins.length<=eo)throw new Error("Input index too high");return ro.__TX.ins[eo].sequence=to,ro.__EXTRACTED_TX=void 0,this}addInputs(eo){return eo.forEach(to=>this.addInput(to)),this}addInput(eo){if(arguments.length>1||!eo||eo.hash===void 0||eo.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");(0,bip371_1.checkTaprootInputFields)(eo,eo,"addInput"),checkInputsForPartialSig(this.data.inputs,"addInput"),eo.witnessScript&&checkInvalidP2WSH(eo.witnessScript);const to=this.__CACHE;this.data.addInput(eo);const ro=to.__TX.ins[to.__TX.ins.length-1];checkTxInputCache(to,ro);const no=this.data.inputs.length-1,io=this.data.inputs[no];return io.nonWitnessUtxo&&addNonWitnessTxCache(this.__CACHE,io,no),to.__FEE=void 0,to.__FEE_RATE=void 0,to.__EXTRACTED_TX=void 0,this}addOutputs(eo){return eo.forEach(to=>this.addOutput(to)),this}addOutput(eo){if(arguments.length>1||!eo||eo.value===void 0||eo.address===void 0&&eo.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");checkInputsForPartialSig(this.data.inputs,"addOutput");const{address:to}=eo;if(typeof to=="string"){const{network:no}=this.opts,io=(0,address_1.toOutputScript)(to,no);eo=Object.assign(eo,{script:io})}(0,bip371_1.checkTaprootOutputFields)(eo,eo,"addOutput");const ro=this.__CACHE;return this.data.addOutput(eo),ro.__FEE=void 0,ro.__FEE_RATE=void 0,ro.__EXTRACTED_TX=void 0,this}extractTransaction(eo){if(!this.data.inputs.every(isFinalized))throw new Error("Not finalized");const to=this.__CACHE;if(eo||checkFees(this,to,this.opts),to.__EXTRACTED_TX)return to.__EXTRACTED_TX;const ro=to.__TX.clone();return inputFinalizeGetAmts(this.data.inputs,ro,to,!0),ro}getFeeRate(){return getTxCacheValue("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return getTxCacheValue("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return(0,utils_1$2.checkForInput)(this.data.inputs,0),range$1(this.data.inputs.length).forEach(eo=>this.finalizeInput(eo)),this}finalizeInput(eo,to){const ro=(0,utils_1$2.checkForInput)(this.data.inputs,eo);return(0,bip371_1.isTaprootInput)(ro)?this._finalizeTaprootInput(eo,ro,void 0,to):this._finalizeInput(eo,ro,to)}finalizeTaprootInput(eo,to,ro=bip371_1.tapScriptFinalizer){const no=(0,utils_1$2.checkForInput)(this.data.inputs,eo);if((0,bip371_1.isTaprootInput)(no))return this._finalizeTaprootInput(eo,no,to,ro);throw new Error(`Cannot finalize input #${eo}. Not Taproot.`)}_finalizeInput(eo,to,ro=getFinalScripts){const{script:no,isP2SH:io,isP2WSH:oo,isSegwit:ao}=getScriptFromInput(eo,to,this.__CACHE);if(!no)throw new Error(`No script found for input #${eo}`);checkPartialSigSighashes(to);const{finalScriptSig:so,finalScriptWitness:co}=ro(eo,to,no,ao,io,oo);if(so&&this.data.updateInput(eo,{finalScriptSig:so}),co&&this.data.updateInput(eo,{finalScriptWitness:co}),!so&&!co)throw new Error(`Unknown error finalizing input #${eo}`);return this.data.clearFinalizedInput(eo),this}_finalizeTaprootInput(eo,to,ro,no=bip371_1.tapScriptFinalizer){if(!to.witnessUtxo)throw new Error(`Cannot finalize input #${eo}. Missing withness utxo.`);if(to.tapKeySig){const io=payments.p2tr({output:to.witnessUtxo.script,signature:to.tapKeySig}),oo=(0,psbtutils_1.witnessStackToScriptWitness)(io.witness);this.data.updateInput(eo,{finalScriptWitness:oo})}else{const{finalScriptWitness:io}=no(eo,to,ro);this.data.updateInput(eo,{finalScriptWitness:io})}return this.data.clearFinalizedInput(eo),this}getInputType(eo){const to=(0,utils_1$2.checkForInput)(this.data.inputs,eo),ro=getScriptFromUtxo(eo,to,this.__CACHE),no=getMeaningfulScript(ro,eo,"input",to.redeemScript||redeemFromFinalScriptSig(to.finalScriptSig),to.witnessScript||redeemFromFinalWitnessScript(to.finalScriptWitness)),io=no.type==="raw"?"":no.type+"-",oo=classifyScript(no.meaningfulScript);return io+oo}inputHasPubkey(eo,to){const ro=(0,utils_1$2.checkForInput)(this.data.inputs,eo);return pubkeyInInput(to,ro,eo,this.__CACHE)}inputHasHDKey(eo,to){const ro=(0,utils_1$2.checkForInput)(this.data.inputs,eo),no=bip32DerivationIsMine(to);return!!ro.bip32Derivation&&ro.bip32Derivation.some(no)}outputHasPubkey(eo,to){const ro=(0,utils_1$2.checkForOutput)(this.data.outputs,eo);return pubkeyInOutput(to,ro,eo,this.__CACHE)}outputHasHDKey(eo,to){const ro=(0,utils_1$2.checkForOutput)(this.data.outputs,eo),no=bip32DerivationIsMine(to);return!!ro.bip32Derivation&&ro.bip32Derivation.some(no)}validateSignaturesOfAllInputs(eo){return(0,utils_1$2.checkForInput)(this.data.inputs,0),range$1(this.data.inputs.length).map(ro=>this.validateSignaturesOfInput(ro,eo)).reduce((ro,no)=>no===!0&&ro,!0)}validateSignaturesOfInput(eo,to,ro){const no=this.data.inputs[eo];return(0,bip371_1.isTaprootInput)(no)?this.validateSignaturesOfTaprootInput(eo,to,ro):this._validateSignaturesOfInput(eo,to,ro)}_validateSignaturesOfInput(eo,to,ro){const no=this.data.inputs[eo],io=(no||{}).partialSig;if(!no||!io||io.length<1)throw new Error("No signatures to validate");if(typeof to!="function")throw new Error("Need validator function to validate signatures");const oo=ro?io.filter(fo=>fo.pubkey.equals(ro)):io;if(oo.length<1)throw new Error("No signatures for this pubkey");const ao=[];let so,co,lo;for(const fo of oo){const ho=bscript.signature.decode(fo.signature),{hash:go,script:yo}=lo!==ho.hashType?getHashForSig(eo,Object.assign({},no,{sighashType:ho.hashType}),this.__CACHE,!0):{hash:so,script:co};lo=ho.hashType,so=go,co=yo,checkScriptForPubkey(fo.pubkey,yo,"verify"),ao.push(to(fo.pubkey,go,ho.signature))}return ao.every(fo=>fo===!0)}validateSignaturesOfTaprootInput(eo,to,ro){const no=this.data.inputs[eo],io=(no||{}).tapKeySig,oo=(no||{}).tapScriptSig;if(!no&&!io&&!(oo&&!oo.length))throw new Error("No signatures to validate");if(typeof to!="function")throw new Error("Need validator function to validate signatures");ro=ro&&(0,bip371_1.toXOnly)(ro);const ao=ro?getTaprootHashesForSig(eo,no,this.data.inputs,ro,this.__CACHE):getAllTaprootHashesForSig(eo,no,this.data.inputs,this.__CACHE);if(!ao.length)throw new Error("No signatures for this pubkey");const so=ao.find(lo=>!lo.leafHash);let co=0;if(io&&so){if(!to(so.pubkey,so.hash,trimTaprootSig(io)))return!1;co++}if(oo)for(const lo of oo){const fo=ao.find(ho=>lo.pubkey.equals(ho.pubkey));if(fo){if(!to(lo.pubkey,fo.hash,trimTaprootSig(lo.signature)))return!1;co++}}return co>0}signAllInputsHD(eo,to=[transaction_1.Transaction.SIGHASH_ALL]){if(!eo||!eo.publicKey||!eo.fingerprint)throw new Error("Need HDSigner to sign input");const ro=[];for(const no of range$1(this.data.inputs.length))try{this.signInputHD(no,eo,to),ro.push(!0)}catch{ro.push(!1)}if(ro.every(no=>no===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(eo,to=[transaction_1.Transaction.SIGHASH_ALL]){return new Promise((ro,no)=>{if(!eo||!eo.publicKey||!eo.fingerprint)return no(new Error("Need HDSigner to sign input"));const io=[],oo=[];for(const ao of range$1(this.data.inputs.length))oo.push(this.signInputHDAsync(ao,eo,to).then(()=>{io.push(!0)},()=>{io.push(!1)}));return Promise.all(oo).then(()=>{if(io.every(ao=>ao===!1))return no(new Error("No inputs were signed"));ro()})})}signInputHD(eo,to,ro=[transaction_1.Transaction.SIGHASH_ALL]){if(!to||!to.publicKey||!to.fingerprint)throw new Error("Need HDSigner to sign input");return getSignersFromHD(eo,this.data.inputs,to).forEach(io=>this.signInput(eo,io,ro)),this}signInputHDAsync(eo,to,ro=[transaction_1.Transaction.SIGHASH_ALL]){return new Promise((no,io)=>{if(!to||!to.publicKey||!to.fingerprint)return io(new Error("Need HDSigner to sign input"));const ao=getSignersFromHD(eo,this.data.inputs,to).map(so=>this.signInputAsync(eo,so,ro));return Promise.all(ao).then(()=>{no()}).catch(io)})}signAllInputs(eo,to){if(!eo||!eo.publicKey)throw new Error("Need Signer to sign input");const ro=[];for(const no of range$1(this.data.inputs.length))try{this.signInput(no,eo,to),ro.push(!0)}catch{ro.push(!1)}if(ro.every(no=>no===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(eo,to){return new Promise((ro,no)=>{if(!eo||!eo.publicKey)return no(new Error("Need Signer to sign input"));const io=[],oo=[];for(const[ao]of this.data.inputs.entries())oo.push(this.signInputAsync(ao,eo,to).then(()=>{io.push(!0)},()=>{io.push(!1)}));return Promise.all(oo).then(()=>{if(io.every(ao=>ao===!1))return no(new Error("No inputs were signed"));ro()})})}signInput(eo,to,ro){if(!to||!to.publicKey)throw new Error("Need Signer to sign input");const no=(0,utils_1$2.checkForInput)(this.data.inputs,eo);return(0,bip371_1.isTaprootInput)(no)?this._signTaprootInput(eo,no,to,void 0,ro):this._signInput(eo,to,ro)}signTaprootInput(eo,to,ro,no){if(!to||!to.publicKey)throw new Error("Need Signer to sign input");const io=(0,utils_1$2.checkForInput)(this.data.inputs,eo);if((0,bip371_1.isTaprootInput)(io))return this._signTaprootInput(eo,io,to,ro,no);throw new Error(`Input #${eo} is not of type Taproot.`)}_signInput(eo,to,ro=[transaction_1.Transaction.SIGHASH_ALL]){const{hash:no,sighashType:io}=getHashAndSighashType(this.data.inputs,eo,to.publicKey,this.__CACHE,ro),oo=[{pubkey:to.publicKey,signature:bscript.signature.encode(to.sign(no),io)}];return this.data.updateInput(eo,{partialSig:oo}),this}_signTaprootInput(eo,to,ro,no,io=[transaction_1.Transaction.SIGHASH_DEFAULT]){const oo=this.checkTaprootHashesForSig(eo,to,ro,no,io),ao=oo.filter(co=>!co.leafHash).map(co=>(0,bip371_1.serializeTaprootSignature)(ro.signSchnorr(co.hash),to.sighashType))[0],so=oo.filter(co=>!!co.leafHash).map(co=>({pubkey:(0,bip371_1.toXOnly)(ro.publicKey),signature:(0,bip371_1.serializeTaprootSignature)(ro.signSchnorr(co.hash),to.sighashType),leafHash:co.leafHash}));return ao&&this.data.updateInput(eo,{tapKeySig:ao}),so.length&&this.data.updateInput(eo,{tapScriptSig:so}),this}signInputAsync(eo,to,ro){return Promise.resolve().then(()=>{if(!to||!to.publicKey)throw new Error("Need Signer to sign input");const no=(0,utils_1$2.checkForInput)(this.data.inputs,eo);return(0,bip371_1.isTaprootInput)(no)?this._signTaprootInputAsync(eo,no,to,void 0,ro):this._signInputAsync(eo,to,ro)})}signTaprootInputAsync(eo,to,ro,no){return Promise.resolve().then(()=>{if(!to||!to.publicKey)throw new Error("Need Signer to sign input");const io=(0,utils_1$2.checkForInput)(this.data.inputs,eo);if((0,bip371_1.isTaprootInput)(io))return this._signTaprootInputAsync(eo,io,to,ro,no);throw new Error(`Input #${eo} is not of type Taproot.`)})}_signInputAsync(eo,to,ro=[transaction_1.Transaction.SIGHASH_ALL]){const{hash:no,sighashType:io}=getHashAndSighashType(this.data.inputs,eo,to.publicKey,this.__CACHE,ro);return Promise.resolve(to.sign(no)).then(oo=>{const ao=[{pubkey:to.publicKey,signature:bscript.signature.encode(oo,io)}];this.data.updateInput(eo,{partialSig:ao})})}async _signTaprootInputAsync(eo,to,ro,no,io=[transaction_1.Transaction.SIGHASH_DEFAULT]){const oo=this.checkTaprootHashesForSig(eo,to,ro,no,io),ao=[],so=oo.filter(lo=>!lo.leafHash)[0];if(so){const lo=Promise.resolve(ro.signSchnorr(so.hash)).then(fo=>({tapKeySig:(0,bip371_1.serializeTaprootSignature)(fo,to.sighashType)}));ao.push(lo)}const co=oo.filter(lo=>!!lo.leafHash);if(co.length){const lo=co.map(fo=>Promise.resolve(ro.signSchnorr(fo.hash)).then(ho=>({tapScriptSig:[{pubkey:(0,bip371_1.toXOnly)(ro.publicKey),signature:(0,bip371_1.serializeTaprootSignature)(ho,to.sighashType),leafHash:fo.leafHash}]})));ao.push(...lo)}return Promise.all(ao).then(lo=>{lo.forEach(fo=>this.data.updateInput(eo,fo))})}checkTaprootHashesForSig(eo,to,ro,no,io){if(typeof ro.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${eo}.`);const oo=getTaprootHashesForSig(eo,to,this.data.inputs,ro.publicKey,this.__CACHE,no,io);if(!oo||!oo.length)throw new Error(`Can not sign for input #${eo} with the key ${ro.publicKey.toString("hex")}`);return oo}toBuffer(){return checkCache(this.__CACHE),this.data.toBuffer()}toHex(){return checkCache(this.__CACHE),this.data.toHex()}toBase64(){return checkCache(this.__CACHE),this.data.toBase64()}updateGlobal(eo){return this.data.updateGlobal(eo),this}updateInput(eo,to){return to.witnessScript&&checkInvalidP2WSH(to.witnessScript),(0,bip371_1.checkTaprootInputFields)(this.data.inputs[eo],to,"updateInput"),this.data.updateInput(eo,to),to.nonWitnessUtxo&&addNonWitnessTxCache(this.__CACHE,this.data.inputs[eo],eo),this}updateOutput(eo,to){const ro=this.data.outputs[eo];return(0,bip371_1.checkTaprootOutputFields)(ro,to,"updateOutput"),this.data.updateOutput(eo,to),this}addUnknownKeyValToGlobal(eo){return this.data.addUnknownKeyValToGlobal(eo),this}addUnknownKeyValToInput(eo,to){return this.data.addUnknownKeyValToInput(eo,to),this}addUnknownKeyValToOutput(eo,to){return this.data.addUnknownKeyValToOutput(eo,to),this}clearFinalizedInput(eo){return this.data.clearFinalizedInput(eo),this}}psbt$1.Psbt=Psbt;const transactionFromBuffer=Xr=>new PsbtTransaction(Xr);class PsbtTransaction{constructor(eo=Buffer$3.from([2,0,0,0,0,0,0,0,0,0])){this.tx=transaction_1.Transaction.fromBuffer(eo),checkTxEmpty(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(eo){if(eo.hash===void 0||eo.index===void 0||!Buffer$3.isBuffer(eo.hash)&&typeof eo.hash!="string"||typeof eo.index!="number")throw new Error("Error adding input.");const to=typeof eo.hash=="string"?(0,bufferutils_1.reverseBuffer)(Buffer$3.from(eo.hash,"hex")):eo.hash;this.tx.addInput(to,eo.index,eo.sequence)}addOutput(eo){if(eo.script===void 0||eo.value===void 0||!Buffer$3.isBuffer(eo.script)||typeof eo.value!="number")throw new Error("Error adding output.");this.tx.addOutput(eo.script,eo.value)}toBuffer(){return this.tx.toBuffer()}}function canFinalize(Xr,eo,to){switch(to){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return hasSigs(1,Xr.partialSig);case"multisig":const ro=payments.p2ms({output:eo});return hasSigs(ro.m,Xr.partialSig,ro.pubkeys);default:return!1}}function checkCache(Xr){if(Xr.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function hasSigs(Xr,eo,to){if(!eo)return!1;let ro;if(to?ro=to.map(no=>{const io=compressPubkey(no);return eo.find(oo=>oo.pubkey.equals(io))}).filter(no=>!!no):ro=eo,ro.length>Xr)throw new Error("Too many signatures");return ro.length===Xr}function isFinalized(Xr){return!!Xr.finalScriptSig||!!Xr.finalScriptWitness}function bip32DerivationIsMine(Xr){return eo=>!(!eo.masterFingerprint.equals(Xr.fingerprint)||!Xr.derivePath(eo.path).publicKey.equals(eo.pubkey))}function check32Bit(Xr){if(typeof Xr!="number"||Xr!==Math.floor(Xr)||Xr>4294967295||Xr<0)throw new Error("Invalid 32 bit integer")}function checkFees(Xr,eo,to){const ro=eo.__FEE_RATE||Xr.getFeeRate(),no=eo.__EXTRACTED_TX.virtualSize(),io=ro*no;if(ro>=to.maximumFeeRate)throw new Error(`Warning: You are paying around ${(io/1e8).toFixed(8)} in fees, which is ${ro} satoshi per byte for a transaction with a VSize of ${no} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function checkInputsForPartialSig(Xr,eo){Xr.forEach(to=>{if((0,bip371_1.isTaprootInput)(to)?(0,bip371_1.checkTaprootInputForSigs)(to,eo):(0,psbtutils_1.checkInputForSig)(to,eo))throw new Error("Can not modify transaction, signatures exist.")})}function checkPartialSigSighashes(Xr){if(!Xr.sighashType||!Xr.partialSig)return;const{partialSig:eo,sighashType:to}=Xr;eo.forEach(ro=>{const{hashType:no}=bscript.signature.decode(ro.signature);if(to!==no)throw new Error("Signature sighash does not match input sighash type")})}function checkScriptForPubkey(Xr,eo,to){if(!(0,psbtutils_1.pubkeyInScript)(Xr,eo))throw new Error(`Can not ${to} for this input with the key ${Xr.toString("hex")}`)}function checkTxEmpty(Xr){if(!Xr.ins.every(to=>to.script&&to.script.length===0&&to.witness&&to.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function checkTxForDupeIns(Xr,eo){Xr.ins.forEach(to=>{checkTxInputCache(eo,to)})}function checkTxInputCache(Xr,eo){const to=(0,bufferutils_1.reverseBuffer)(Buffer$3.from(eo.hash)).toString("hex")+":"+eo.index;if(Xr.__TX_IN_CACHE[to])throw new Error("Duplicate input detected.");Xr.__TX_IN_CACHE[to]=1}function scriptCheckerFactory(Xr,eo){return(to,ro,no,io)=>{const oo=Xr({redeem:{output:no}}).output;if(!ro.equals(oo))throw new Error(`${eo} for ${io} #${to} doesn't match the scriptPubKey in the prevout`)}}const checkRedeemScript=scriptCheckerFactory(payments.p2sh,"Redeem script"),checkWitnessScript=scriptCheckerFactory(payments.p2wsh,"Witness script");function getTxCacheValue(Xr,eo,to,ro){if(!to.every(isFinalized))throw new Error(`PSBT must be finalized to calculate ${eo}`);if(Xr==="__FEE_RATE"&&ro.__FEE_RATE)return ro.__FEE_RATE;if(Xr==="__FEE"&&ro.__FEE)return ro.__FEE;let no,io=!0;if(ro.__EXTRACTED_TX?(no=ro.__EXTRACTED_TX,io=!1):no=ro.__TX.clone(),inputFinalizeGetAmts(to,no,ro,io),Xr==="__FEE_RATE")return ro.__FEE_RATE;if(Xr==="__FEE")return ro.__FEE}function getFinalScripts(Xr,eo,to,ro,no,io){const oo=classifyScript(to);if(!canFinalize(eo,to,oo))throw new Error(`Can not finalize input #${Xr}`);return prepareFinalScripts(to,oo,eo.partialSig,ro,no,io)}function prepareFinalScripts(Xr,eo,to,ro,no,io){let oo,ao;const so=getPayment(Xr,eo,to),co=io?payments.p2wsh({redeem:so}):null,lo=no?payments.p2sh({redeem:co||so}):null;return ro?(co?ao=(0,psbtutils_1.witnessStackToScriptWitness)(co.witness):ao=(0,psbtutils_1.witnessStackToScriptWitness)(so.witness),lo&&(oo=lo.input)):lo?oo=lo.input:oo=so.input,{finalScriptSig:oo,finalScriptWitness:ao}}function getHashAndSighashType(Xr,eo,to,ro,no){const io=(0,utils_1$2.checkForInput)(Xr,eo),{hash:oo,sighashType:ao,script:so}=getHashForSig(eo,io,ro,!1,no);return checkScriptForPubkey(to,so,"sign"),{hash:oo,sighashType:ao}}function getHashForSig(Xr,eo,to,ro,no){const io=to.__TX,oo=eo.sighashType||transaction_1.Transaction.SIGHASH_ALL;checkSighashTypeAllowed(oo,no);let ao,so;if(eo.nonWitnessUtxo){const fo=nonWitnessUtxoTxFromCache(to,eo,Xr),ho=io.ins[Xr].hash,go=fo.getHash();if(!ho.equals(go))throw new Error(`Non-witness UTXO hash for input #${Xr} doesn't match the hash specified in the prevout`);const yo=io.ins[Xr].index;so=fo.outs[yo]}else if(eo.witnessUtxo)so=eo.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:co,type:lo}=getMeaningfulScript(so.script,Xr,"input",eo.redeemScript,eo.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(lo)>=0)ao=io.hashForWitnessV0(Xr,co,so.value,oo);else if((0,psbtutils_1.isP2WPKH)(co)){const fo=payments.p2pkh({hash:co.slice(2)}).output;ao=io.hashForWitnessV0(Xr,fo,so.value,oo)}else{if(eo.nonWitnessUtxo===void 0&&to.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${Xr} has witnessUtxo but non-segwit script: ${co.toString("hex")}`);!ro&&to.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecesor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant. ********************* PROCEED WITH CAUTION! -*********************`),ao=io.hashForSignature(Xr,co,oo)}return{script:co,sighashType:oo,hash:ao}}function getAllTaprootHashesForSig(Xr,eo,to,ro){const no=[];if(eo.tapInternalKey){const oo=getPrevoutTaprootKey(Xr,eo,ro);oo&&no.push(oo)}if(eo.tapScriptSig){const oo=eo.tapScriptSig.map(ao=>ao.pubkey);no.push(...oo)}return no.map(oo=>getTaprootHashesForSig(Xr,eo,to,oo,ro)).flat()}function getPrevoutTaprootKey(Xr,eo,to){const{script:ro}=getScriptAndAmountFromUtxo(Xr,eo,to);return(0,psbtutils_1.isP2TR)(ro)?ro.subarray(2,34):null}function trimTaprootSig(Xr){return Xr.length===64?Xr:Xr.subarray(0,64)}function getTaprootHashesForSig(Xr,eo,to,ro,no,io,oo){const ao=no.__TX,so=eo.sighashType||transaction_1.Transaction.SIGHASH_DEFAULT;checkSighashTypeAllowed(so,oo);const co=to.map((yo,vo)=>getScriptAndAmountFromUtxo(vo,yo,no)),lo=co.map(yo=>yo.script),fo=co.map(yo=>yo.value),ho=[];if(eo.tapInternalKey&&!io){const yo=getPrevoutTaprootKey(Xr,eo,no)||Buffer$3.from([]);if((0,bip371_1.toXOnly)(ro).equals(yo)){const vo=ao.hashForWitnessV1(Xr,lo,fo,so);ho.push({pubkey:ro,hash:vo})}}const go=(eo.tapLeafScript||[]).filter(yo=>(0,psbtutils_1.pubkeyInScript)(ro,yo.script)).map(yo=>{const vo=(0,bip341_1.tapleafHash)({output:yo.script,version:yo.leafVersion});return Object.assign({hash:vo},yo)}).filter(yo=>!io||io.equals(yo.hash)).map(yo=>{const vo=ao.hashForWitnessV1(Xr,lo,fo,transaction_1.Transaction.SIGHASH_DEFAULT,yo.hash);return{pubkey:ro,hash:vo,leafHash:yo.hash}});return ho.concat(go)}function checkSighashTypeAllowed(Xr,eo){if(eo&&eo.indexOf(Xr)<0){const to=sighashTypeToString(Xr);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${to}`)}}function getPayment(Xr,eo,to){let ro;switch(eo){case"multisig":const no=getSortedSigs(Xr,to);ro=payments.p2ms({output:Xr,signatures:no});break;case"pubkey":ro=payments.p2pk({output:Xr,signature:to[0].signature});break;case"pubkeyhash":ro=payments.p2pkh({output:Xr,pubkey:to[0].pubkey,signature:to[0].signature});break;case"witnesspubkeyhash":ro=payments.p2wpkh({output:Xr,pubkey:to[0].pubkey,signature:to[0].signature});break}return ro}function getScriptFromInput(Xr,eo,to){const ro=to.__TX,no={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(no.isP2SH=!!eo.redeemScript,no.isP2WSH=!!eo.witnessScript,eo.witnessScript)no.script=eo.witnessScript;else if(eo.redeemScript)no.script=eo.redeemScript;else if(eo.nonWitnessUtxo){const io=nonWitnessUtxoTxFromCache(to,eo,Xr),oo=ro.ins[Xr].index;no.script=io.outs[oo].script}else eo.witnessUtxo&&(no.script=eo.witnessUtxo.script);return(eo.witnessScript||(0,psbtutils_1.isP2WPKH)(no.script))&&(no.isSegwit=!0),no}function getSignersFromHD(Xr,eo,to){const ro=(0,utils_1$2.checkForInput)(eo,Xr);if(!ro.bip32Derivation||ro.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const no=ro.bip32Derivation.map(oo=>{if(oo.masterFingerprint.equals(to.fingerprint))return oo}).filter(oo=>!!oo);if(no.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return no.map(oo=>{const ao=to.derivePath(oo.path);if(!oo.pubkey.equals(ao.publicKey))throw new Error("pubkey did not match bip32Derivation");return ao})}function getSortedSigs(Xr,eo){return payments.p2ms({output:Xr}).pubkeys.map(ro=>(eo.filter(no=>no.pubkey.equals(ro))[0]||{}).signature).filter(ro=>!!ro)}function scriptWitnessToWitnessStack(Xr){let eo=0;function to(oo){return eo+=oo,Xr.slice(eo-oo,eo)}function ro(){const oo=varuint.decode(Xr,eo);return eo+=varuint.decode.bytes,oo}function no(){return to(ro())}function io(){const oo=ro(),ao=[];for(let so=0;so{if(ro&&so.finalScriptSig&&(eo.ins[co].script=so.finalScriptSig),ro&&so.finalScriptWitness&&(eo.ins[co].witness=scriptWitnessToWitnessStack(so.finalScriptWitness)),so.witnessUtxo)no+=so.witnessUtxo.value;else if(so.nonWitnessUtxo){const lo=nonWitnessUtxoTxFromCache(to,so,co),fo=eo.ins[co].index,ho=lo.outs[fo];no+=ho.value}});const io=eo.outs.reduce((so,co)=>so+co.value,0),oo=no-io;if(oo<0)throw new Error("Outputs are spending more than Inputs");const ao=eo.virtualSize();to.__FEE=oo,to.__EXTRACTED_TX=eo,to.__FEE_RATE=Math.floor(oo/ao)}function nonWitnessUtxoTxFromCache(Xr,eo,to){const ro=Xr.__NON_WITNESS_UTXO_TX_CACHE;return ro[to]||addNonWitnessTxCache(Xr,eo,to),ro[to]}function getScriptFromUtxo(Xr,eo,to){const{script:ro}=getScriptAndAmountFromUtxo(Xr,eo,to);return ro}function getScriptAndAmountFromUtxo(Xr,eo,to){if(eo.witnessUtxo!==void 0)return{script:eo.witnessUtxo.script,value:eo.witnessUtxo.value};if(eo.nonWitnessUtxo!==void 0){const no=nonWitnessUtxoTxFromCache(to,eo,Xr).outs[to.__TX.ins[Xr].index];return{script:no.script,value:no.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function pubkeyInInput(Xr,eo,to,ro){const no=getScriptFromUtxo(to,eo,ro),{meaningfulScript:io}=getMeaningfulScript(no,to,"input",eo.redeemScript,eo.witnessScript);return(0,psbtutils_1.pubkeyInScript)(Xr,io)}function pubkeyInOutput(Xr,eo,to,ro){const no=ro.__TX.outs[to].script,{meaningfulScript:io}=getMeaningfulScript(no,to,"output",eo.redeemScript,eo.witnessScript);return(0,psbtutils_1.pubkeyInScript)(Xr,io)}function redeemFromFinalScriptSig(Xr){if(!Xr)return;const eo=bscript.decompile(Xr);if(!eo)return;const to=eo[eo.length-1];if(!(!Buffer$3.isBuffer(to)||isPubkeyLike(to)||isSigLike(to)||!bscript.decompile(to)))return to}function redeemFromFinalWitnessScript(Xr){if(!Xr)return;const eo=scriptWitnessToWitnessStack(Xr),to=eo[eo.length-1];if(!(isPubkeyLike(to)||!bscript.decompile(to)))return to}function compressPubkey(Xr){if(Xr.length===65){const eo=Xr[64]&1,to=Xr.slice(0,33);return to[0]=2|eo,to}return Xr.slice()}function isPubkeyLike(Xr){return Xr.length===33&&bscript.isCanonicalPubKey(Xr)}function isSigLike(Xr){return bscript.isCanonicalScriptSignature(Xr)}function getMeaningfulScript(Xr,eo,to,ro,no){const io=(0,psbtutils_1.isP2SHScript)(Xr),oo=io&&ro&&(0,psbtutils_1.isP2WSHScript)(ro),ao=(0,psbtutils_1.isP2WSHScript)(Xr);if(io&&ro===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((ao||oo)&&no===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let so;return oo?(so=no,checkRedeemScript(eo,Xr,ro,to),checkWitnessScript(eo,ro,no,to),checkInvalidP2WSH(so)):ao?(so=no,checkWitnessScript(eo,Xr,no,to),checkInvalidP2WSH(so)):io?(so=ro,checkRedeemScript(eo,Xr,ro,to)):so=Xr,{meaningfulScript:so,type:oo?"p2sh-p2wsh":io?"p2sh":ao?"p2wsh":"raw"}}function checkInvalidP2WSH(Xr){if((0,psbtutils_1.isP2WPKH)(Xr)||(0,psbtutils_1.isP2SHScript)(Xr))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function classifyScript(Xr){return(0,psbtutils_1.isP2WPKH)(Xr)?"witnesspubkeyhash":(0,psbtutils_1.isP2PKH)(Xr)?"pubkeyhash":(0,psbtutils_1.isP2MS)(Xr)?"multisig":(0,psbtutils_1.isP2PK)(Xr)?"pubkey":"nonstandard"}function range$1(Xr){return[...Array(Xr).keys()]}(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.initEccLib=Xr.Transaction=Xr.opcodes=Xr.Psbt=Xr.Block=Xr.script=Xr.payments=Xr.networks=Xr.crypto=Xr.address=void 0;const eo=address;Xr.address=eo;const to=crypto$3;Xr.crypto=to;const ro=networks$1;Xr.networks=ro;const no=payments$3;Xr.payments=no;const io=script$1;Xr.script=io;var oo=block;Object.defineProperty(Xr,"Block",{enumerable:!0,get:function(){return oo.Block}});var ao=psbt$1;Object.defineProperty(Xr,"Psbt",{enumerable:!0,get:function(){return ao.Psbt}});var so=ops;Object.defineProperty(Xr,"opcodes",{enumerable:!0,get:function(){return so.OPS}});var co=transaction;Object.defineProperty(Xr,"Transaction",{enumerable:!0,get:function(){return co.Transaction}});var lo=ecc_lib;Object.defineProperty(Xr,"initEccLib",{enumerable:!0,get:function(){return lo.initEccLib}})})(src$3);const extractAddressFromInput=(Xr,eo,to)=>{var ro;let no;if(!((ro=to.witnessUtxo)===null||ro===void 0)&&ro.script?no=to.witnessUtxo.script:to.nonWitnessUtxo&&(no=src$3.Transaction.fromBuffer(to.nonWitnessUtxo).outs[Xr.txInputs[eo].index].script),!!no)try{return src$3.address.fromOutputScript(no)}catch{throw new Error("address not found in output script")}},validateAddress=(Xr,eo,to,ro)=>{const no=extractAddressFromInput(Xr,to,ro);if(!no)throw new DynamicError(`validateAddress - input not found for the given address: ${eo}`);if(no!==eo)throw new DynamicError("validateAddress - address mismatch with index")},getSigHashType=Xr=>{var eo;if(Xr!=null&&Xr.sighashType)return Xr.sighashType;let to=!1;if(!((eo=Xr.witnessUtxo)===null||eo===void 0)&&eo.script)try{src$3.payments.p2tr({output:Xr.witnessUtxo.script}),to=!0}catch{logger$9.debug("address is not taproot")}return to?src$3.Transaction.SIGHASH_DEFAULT:src$3.Transaction.SIGHASH_ALL},validateSigHash=(Xr,eo)=>{const to=getSigHashType(eo);if(Xr!=null&&Xr.length&&!Xr.includes(to))throw new Error(`validatePsbt - sigHashType ${to} not in allowed list`)},validatePsbt=(Xr,eo,to)=>{if(to!=null&&to.length)for(const ro of to){const{address:no,signingIndexes:io,disableAddressValidation:oo=!0}=ro;if(!(io!=null&&io.length))return;if(!no)throw new Error("validatePsbt - address not provided");for(const ao of io){const so=Xr.data.inputs[ao];if(!so)throw new Error("validatePsbt - requested input not found");oo||validateAddress(Xr,no,ao,so),validateSigHash(eo,so)}}},convertNetworkTypeForPsbt=Xr=>({[BitcoinNetworkType.Mainnet]:src$3.networks.bitcoin,[BitcoinNetworkType.Testnet]:src$3.networks.testnet,[BitcoinNetworkType.Signet]:void 0})[Xr];class BitcoinBtcKitConnector extends BitcoinWalletConnector{constructor(eo,to){super(eo),this.currentNetwork=BitcoinNetworkType.Mainnet,this.btcKit=to}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const[to]=yield this.getConnectedAccounts();if(to)return to;const ro=yield this.btcKit.request("getAddresses",{types:["p2tr","p2wpkh"]});if(!("result"in ro)){logger$9.error("Fetch public address error",ro);return}const{addresses:no}=ro.result,io=no==null?void 0:no.find(so=>so.type==="p2tr"),oo=no==null?void 0:no.find(so=>so.type==="p2wpkh"),ao=(eo=io==null?void 0:io.address)!==null&&eo!==void 0?eo:oo==null?void 0:oo.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:ao,ordinalsAddress:io,paymentAddress:oo}),ao})}signMessage(eo){return __awaiter$i(this,void 0,void 0,function*(){if(!(yield this.getConnectedAccounts()).length)return;const to=yield this.btcKit.request("signMessage",{message:eo,paymentType:"p2tr"}).catch(({error:no})=>{throw no});if(!("result"in to))throw logger$9.error("Signature error",to),new Error("Failed to sign message");const{signature:ro}=to.result;return this.isHardwareWalletEnabled?JSON.stringify({signedTransaction:{data:ro}}):ro})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){if(!(yield this.getAddress())||!this.btcKit)return;const ro=yield this.btcKit.request("sendTransfer",{address:eo.recipientAddress,amount:eo.amount.toString(),network:this.convertNetworkTypeToNetworkMode()});if(!("result"in ro))throw logger$9.error("Transaction error",ro),new Error("Failed to send transaction");return ro.result.txid})}convertNetworkTypeToNetworkMode(){return this.currentNetwork===BitcoinNetworkType.Mainnet?"mainnet":"testnet"}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){var to,ro;if(!(yield this.getAddress())||!this.btcKit)return;const io=convertNetworkTypeForPsbt(this.currentNetwork),oo=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64,{network:io});!((to=eo.signature)===null||to===void 0)&&to.length&&validatePsbt(oo,eo.allowedSighash,eo.signature);const ao={allowedSighash:eo.allowedSighash,hex:oo.toHex(),signAtIndex:(ro=eo.signature)===null||ro===void 0?void 0:ro.flatMap(lo=>lo.signingIndexes).filter(Number.isInteger)},so=yield this.btcKit.request("signPsbt",Object.assign({broadcast:!1,network:this.convertNetworkTypeToNetworkMode()},ao));if(!so||!("result"in so)||!("hex"in so.result))throw new Error("signPsbt - failed to sign PSBT");const co=so.result.hex;return{signedPsbt:src$3.Psbt.fromHex(co,{network:io}).toBase64()}})}}const fetchBtcKitConnectors=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).map(([to,ro])=>{var no,io;const oo=(no=ro.injectedConfig)===null||no===void 0?void 0:no.find(so=>so.chain==="btc"&&so.providerInterface===BTCKIT_INTERFACE);if(!(!((io=oo==null?void 0:oo.windowLocations)===null||io===void 0)&&io.length))return;const ao=getProvidersFromWindow(oo.windowLocations[0]);return class extends BitcoinBtcKitConnector{constructor(so){super(Object.assign(Object.assign({},so),{overrideKey:to,walletData:ro}),ao==null?void 0:ao[0]),this.name=ro.shortName||ro.name}}}).filter(to=>!!to)},createPsbtOptions=(Xr,eo)=>{var to;const ro={autoFinalized:!1};if(eo.signature){validatePsbt(Xr,eo.allowedSighash,eo.signature);const no=[];for(const io of eo.signature)if(!((to=io.signingIndexes)===null||to===void 0)&&to.length)for(const oo of io.signingIndexes)no.push({address:io.address,disableAddressValidation:io.disableAddressValidation,index:oo,sighashTypes:eo.allowedSighash});ro.toSignInputs=no}return ro},createSignPsbtOptionsForSatsConnect=(Xr,eo,to=!1)=>{var ro,no,io;!((ro=eo.signature)===null||ro===void 0)&&ro.length&&validatePsbt(Xr,eo.allowedSighash,eo.signature),logger$9.logVerboseTroubleshootingMessage("createSignPsbtOptionsForSatsConnect",{isLegacyConnector:to,psbtFromBase64:Xr,request:eo});const oo=((io=(no=eo.signature)===null||no===void 0?void 0:no.map(ao=>{var so;return((so=ao.signingIndexes)!==null&&so!==void 0?so:[]).map(co=>({address:ao.address,sigHash:to?getSigHashType(Xr.data.inputs[co]):eo.allowedSighash[0],signingIndexes:[co]}))}))!==null&&io!==void 0?io:[]).flat();return logger$9.logVerboseTroubleshootingMessage("createSignPsbtOptionsForSatsConnect",{inputsToSign:oo}),oo};class BitcoinSatsConnectConnector extends BitcoinWalletConnector{constructor(eo){var to,ro,no;super(eo),this.isLegacy=!1,this.currentNetwork=BitcoinNetworkType.Mainnet,!((ro=(to=eo.walletData)===null||to===void 0?void 0:to.injectedConfig)===null||ro===void 0)&&ro.length&&(this.providerId=(no=eo.walletData.injectedConfig[0].walletStandard)===null||no===void 0?void 0:no.providerId)}getGenericUserCancelledError(){const eo=new Error;return eo.code="-32000",eo}getAddresses(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const to=yield request("getAddresses",{purposes:[AddressPurpose.Payment,AddressPurpose.Ordinals]});if(to.status!=="success")throw to.error;const{addresses:ro}=to.result,no=ro==null?void 0:ro.find(ao=>ao.purpose===AddressPurpose.Ordinals),io=ro==null?void 0:ro.find(ao=>ao.purpose===AddressPurpose.Payment),oo=(eo=no==null?void 0:no.address)!==null&&eo!==void 0?eo:io==null?void 0:io.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:oo,ordinalsAddress:no,paymentAddress:io}),oo})}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const to=findWalletBookWallet(this.walletBook,this.key),ro=(eo=to==null?void 0:to.mobile)===null||eo===void 0?void 0:eo.inAppBrowser;if(isMobile$1()&&!this.isInstalledOnBrowser()&&ro&&this.mobileExperience==="in-app-browser"){const io=template$1(ro)({encodedDappURI:encodeURIComponent(window.location.toString())});window.location.href=io;return}try{const no=yield request("wallet_requestPermissions",void 0);if(no.status!=="success")throw no.error;return yield this.getAddresses()}catch{throw this.getGenericUserCancelledError()}})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){try{const ro=yield request("signMessage",{address:to,message:eo});if(ro.status!=="success")throw ro.error;return this.isHardwareWalletEnabled?JSON.stringify({signedTransaction:{data:ro.result.signature}}):ro.result.signature}catch{throw this.getGenericUserCancelledError()}})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){try{const to=yield request("sendTransfer",{recipients:[{address:eo.recipientAddress,amount:Number(eo.amount)}]});if(to.status!=="success")throw to.error;return to.result.txid}catch{throw this.getGenericUserCancelledError()}})}signTransaction(eo){return __awaiter$i(this,void 0,void 0,function*(){const{allowedSignHash:to,psbtBase64:ro,broadcast:no,inputsToSign:io}=eo,oo={allowedSignHash:to,broadcast:no,psbt:ro,signInputs:io.reduce((ao,so)=>(ao[so.address]||(ao[so.address]=[]),ao[so.address].push(...so.signingIndexes),ao),{})};logger$9.logVerboseTroubleshootingMessage("[BitcoinSatsConnectConnector] signTransaction",{signPbstPayload:oo});try{const ao=yield request("signPsbt",oo);if(ao.status!=="success")throw ao.error;return{psbtBase64:ao.result.psbt,txId:ao.result.txid}}catch{throw this.getGenericUserCancelledError()}})}signTransactions(eo){return __awaiter$i(this,void 0,void 0,function*(){const{message:to,psbts:ro,network:no}=eo;return logger$9.logVerboseTroubleshootingMessage("[BitcoinSatsConnectConnector] signTransactions",{transactions:eo}),new Promise((io,oo)=>{signMultipleTransactions({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var ao,so;return(so=(ao=this.wallet)===null||ao===void 0?void 0:ao.features[SATSCONNECT_FEATURE])===null||so===void 0?void 0:so.provider}),onCancel:()=>{const ao=this.getGenericUserCancelledError();oo(ao)},onFinish:ao=>{io(ao)},payload:{message:to||"Sign Transaction",network:no,psbts:ro}})})})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){var to;if(!(!((to=eo.allowedSighash)===null||to===void 0)&&to.length))throw new Error("allowedSighash cannot be an empty array");const ro=convertNetworkTypeForPsbt(this.currentNetwork),no=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64,{network:ro});logger$9.logVerboseTroubleshootingMessage("signPsbt",{isLegacy:this.isLegacy,psbtFromBase64:no,request:eo});const io=yield this.signTransaction({allowedSignHash:eo.allowedSighash[0],broadcast:!1,inputsToSign:createSignPsbtOptionsForSatsConnect(no,eo,this.isLegacy),psbtBase64:eo.unsignedPsbtBase64});if(!io)throw new Error("Failed to sign transaction with sats-connect");return{signedPsbt:io.psbtBase64}})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){var to;const ro=convertNetworkTypeForPsbt(this.currentNetwork),no={message:"Sign Transaction",network:{type:this.currentNetwork},psbts:[]};for(const oo of eo){const ao=src$3.Psbt.fromBase64(oo.unsignedPsbtBase64,{network:ro}),so=createSignPsbtOptionsForSatsConnect(ao,oo,this.isLegacy);no.psbts.push({inputsToSign:so,psbtBase64:oo.unsignedPsbtBase64})}logger$9.logVerboseTroubleshootingMessage("signPsbts",no);const io=yield this.signTransactions(no);return(to=io==null?void 0:io.map(oo=>oo.psbtBase64))!==null&&to!==void 0?to:[]})}validateActiveWallet(eo){return __awaiter$i(this,void 0,void 0,function*(){logger$9.debug("validateActiveWallet - skipping validation for xverse",{expectedAddress:eo})})}handleXverseAccountChange(){return __awaiter$i(this,void 0,void 0,function*(){const{handleAccountChange:eo}=eventListenerHandlers(this),to=yield this.getAddresses();if(!to)return;eo([to])})}setupEventListeners(){if(this.key!=="xverse"){super.setupEventListeners();return}try{const eo=addListener("accountChange",this.handleXverseAccountChange.bind(this));this.teardownEventListeners=()=>{logger$9.debug("[BitcoinSatsConnectConnector] teardownEventListeners"),eo()}}catch(eo){logger$9.debug("[BitcoinSatsConnectConnector] setupEventListeners",{connector:this.key,error:eo})}}}const hasSatsConnectFeature=Xr=>SATSCONNECT_FEATURE in Xr,supportsSatsConnect=Xr=>{var eo,to,ro,no;if(Xr.key===XVERSE_KEY)return!0;const io=(ro=(to=(eo=findWalletBookWallet(Xr.walletBook,Xr.key))===null||eo===void 0?void 0:eo.injectedConfig)===null||to===void 0?void 0:to.find(oo=>oo.chain==="btc"))===null||ro===void 0?void 0:ro.walletStandard;return!!(Xr.wallet&&hasSatsConnectFeature(Xr.wallet.features)||!((no=io==null?void 0:io.features)===null||no===void 0)&&no.includes(SATSCONNECT_FEATURE))};class BitcoinSatsConnectLegacyConnector extends BitcoinSatsConnectConnector{constructor(){super(...arguments),this.isLegacy=!0}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;if(!supportsSatsConnect(this))return;const to=findWalletBookWallet(this.walletBook,this.key),ro=(eo=to==null?void 0:to.mobile)===null||eo===void 0?void 0:eo.inAppBrowser;if(isMobile$1()&&!this.isInstalledOnBrowser()&&ro&&this.mobileExperience==="in-app-browser"){const io=template$1(ro)({encodedDappURI:encodeURIComponent(window.location.toString())});window.location.href=io;return}return new Promise((no,io)=>{getAddress({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var oo,ao;return(ao=(oo=this.wallet)===null||oo===void 0?void 0:oo.features[SATSCONNECT_FEATURE])===null||ao===void 0?void 0:ao.provider}),onCancel:()=>{const oo=new Error;oo.code="-32000",io(oo)},onFinish:oo=>__awaiter$i(this,void 0,void 0,function*(){var ao;const{addresses:so}=oo,co=so==null?void 0:so.find(ho=>ho.purpose===AddressPurpose.Ordinals),lo=so==null?void 0:so.find(ho=>ho.purpose===AddressPurpose.Payment),fo=(ao=co==null?void 0:co.address)!==null&&ao!==void 0?ao:lo==null?void 0:lo.address;yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:fo,ordinalsAddress:co,paymentAddress:lo}),no(fo)}),payload:{message:"Address for receiving Ordinals and payments",network:{type:this.currentNetwork},purposes:[AddressPurpose.Ordinals,AddressPurpose.Payment]}})})})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){if(supportsSatsConnect(this))return new Promise((ro,no)=>{signMessage$1({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var io,oo;return(oo=(io=this.wallet)===null||io===void 0?void 0:io.features[SATSCONNECT_FEATURE])===null||oo===void 0?void 0:oo.provider}),onCancel:()=>{const io=new Error;io.code="-32000",no(io)},onFinish:io=>__awaiter$i(this,void 0,void 0,function*(){if(this.isHardwareWalletEnabled)return ro(JSON.stringify({signedTransaction:{data:io}}));ro(io)}),payload:{address:to,message:eo,network:{type:this.currentNetwork}}})})})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){var to;const ro=yield this.getAddress(),no=(to=(yield this.getAdditionalAddresses(ro)).find(io=>io.type==="payment"))===null||to===void 0?void 0:to.address;if(!(!no||!supportsSatsConnect(this)))return new Promise((io,oo)=>{sendBtcTransaction({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var ao,so;return(so=(ao=this.wallet)===null||ao===void 0?void 0:ao.features[SATSCONNECT_FEATURE])===null||so===void 0?void 0:so.provider}),onCancel:()=>{const ao=new Error;ao.code="-32000",oo(ao)},onFinish:ao=>{io(ao)},payload:{network:{type:this.currentNetwork},recipients:[{address:eo.recipientAddress,amountSats:BigInt(eo.amount)}],senderAddress:no}})})})}signTransaction(eo){return __awaiter$i(this,void 0,void 0,function*(){const{message:to,psbtBase64:ro,broadcast:no,inputsToSign:io}=eo;return new Promise((oo,ao)=>{signTransaction$1({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var so,co;return(co=(so=this.wallet)===null||so===void 0?void 0:so.features[SATSCONNECT_FEATURE])===null||co===void 0?void 0:co.provider}),onCancel:()=>{const so=new Error;so.code="-32000",ao(so)},onFinish:so=>{oo(so)},payload:{broadcast:no,inputsToSign:io,message:to||"Sign Transaction",network:{type:this.currentNetwork},psbtBase64:ro}})})})}signTransactions(eo){return __awaiter$i(this,void 0,void 0,function*(){const{message:to,psbts:ro,network:no}=eo;return new Promise((io,oo)=>{signMultipleTransactions({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var ao,so;return(so=(ao=this.wallet)===null||ao===void 0?void 0:ao.features[SATSCONNECT_FEATURE])===null||so===void 0?void 0:so.provider}),onCancel:()=>{const ao=new Error;ao.code="-32000",oo(ao)},onFinish:ao=>{io(ao)},payload:{message:to||"Sign Transaction",network:no,psbts:ro}})})})}}const fetchSatsConnectConnectors=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).filter(([to,ro])=>{var no;return(no=ro.injectedConfig)===null||no===void 0?void 0:no.find(io=>{var oo;return io.chain==="btc"&&!!(!((oo=io.walletStandard)===null||oo===void 0)&&oo.features.includes(SATSCONNECT_FEATURE))})}).map(([to,ro])=>{var no;const{shortName:io,injectedConfig:oo}=ro,ao=io||ro.name;return!((no=oo==null?void 0:oo[0].walletStandard)===null||no===void 0)&&no.providerId?class extends BitcoinSatsConnectConnector{constructor(so){super(Object.assign(Object.assign({},so),{overrideKey:to,walletData:ro})),this.name=ao}}:class extends BitcoinSatsConnectLegacyConnector{constructor(so){super(Object.assign(Object.assign({},so),{overrideKey:to,walletData:ro})),this.name=ao}}})},sighashNumberToString=Xr=>{switch(Xr){case src$3.Transaction.SIGHASH_ALL:return"ALL";case src$3.Transaction.SIGHASH_NONE:return"NONE";case src$3.Transaction.SIGHASH_SINGLE:return"SINGLE";case src$3.Transaction.SIGHASH_ALL+src$3.Transaction.SIGHASH_ANYONECANPAY:return"ALL|ANYONECANPAY";case src$3.Transaction.SIGHASH_NONE+src$3.Transaction.SIGHASH_ANYONECANPAY:return"NONE|ANYONECANPAY";case src$3.Transaction.SIGHASH_SINGLE+src$3.Transaction.SIGHASH_ANYONECANPAY:return"SINGLE|ANYONECANPAY";default:return}},decodeBase64=Xr=>Uint8Array.from(Buffer$3.from(Xr,"base64")),encodeBase64=Xr=>Buffer$3.from(Xr).toString("base64");class PhantomConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"phantombtc"})),this.name="Phantom"}connectWithInstalledExtension(){return __awaiter$i(this,void 0,void 0,function*(){var eo,to;let ro,no;if(!((eo=this.walletMethods)===null||eo===void 0)&&eo.connect){const{accounts:oo}=yield this.walletMethods.connect();[ro,no]=oo.map(so=>({address:so.address,publicKey:Buffer$3.from(so.publicKey).toString("hex")})),no||(no=ro)}else{const oo=this.getProvider();if(!oo)return;const ao=yield oo.requestAccounts();no=ao==null?void 0:ao.find(so=>so.purpose==="ordinals"),ro=ao==null?void 0:ao.find(so=>so.purpose==="payment")}const io=(to=no==null?void 0:no.address)!==null&&to!==void 0?to:ro==null?void 0:ro.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:io,ordinalsAddress:no,paymentAddress:ro}),io})}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){if(this.isInstalledOnBrowser())return this.connectWithInstalledExtension();isMobile$1()&&handleMobileWalletRedirect({nativeLink:"phantom://browse",universalLink:"https://phantom.app/ul/browse"})})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){var ro;if(!((ro=this.walletMethods)===null||ro===void 0)&&ro.signMessage){const[no]=yield this.walletMethods.signMessage({account:{address:to},message:new TextEncoder().encode(eo)});return Buffer$3.from(no.signature).toString("base64")}else{const no=this.getProvider();if(!no)return;const io=yield no.signMessage(to,new TextEncoder().encode(eo));return Buffer$3.from(io.signature).toString("base64")}})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){var to,ro,no,io,oo;const[ao]=yield this.getConnectedAccounts();if(!ao)return;const so=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),co=createPsbtOptions(so,eo);if(!((to=this.walletMethods)===null||to===void 0)&&to.signTransaction){const[lo]=yield this.walletMethods.signTransaction({inputsToSign:(no=(ro=co.toSignInputs)===null||ro===void 0?void 0:ro.map(fo=>({account:{address:fo.address},sigHash:fo.sighashTypes&&sighashNumberToString(fo.sighashTypes[0]),signingIndexes:[fo.index]})))!==null&&no!==void 0?no:[],psbt:decodeBase64(eo.unsignedPsbtBase64)});return{signedPsbt:Buffer$3.from(lo.signedPsbt).toString("base64")}}else{const lo=this.getProvider();if(!lo)return;const fo=(oo=(io=eo.signature)===null||io===void 0?void 0:io.map(go=>{var yo;return{address:go.address,sigHash:eo.allowedSighash[0],signingIndexes:(yo=go.signingIndexes)!==null&&yo!==void 0?yo:[]}}))!==null&&oo!==void 0?oo:[],ho=yield lo.signPSBT(decodeBase64(eo.unsignedPsbtBase64),{inputsToSign:fo});return{signedPsbt:encodeBase64(Uint8Array.from(ho))}}})}}class OkxConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"okxwalletbtc"})),this.name="OKX Wallet"}get walletBookWallet(){return this.walletBook.wallets[this.key]}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){if(!this.isInstalledOnBrowser()&&isMobile$1()&&this.walletBookWallet.mobile&&this.walletBookWallet.mobile.inAppBrowser&&this.mobileExperience==="in-app-browser"){const oo=template$1(this.walletBookWallet.mobile.inAppBrowser)({encodedDappURI:encodeURIComponent(window.location.toString())});window.location.assign(oo);return}const eo=this.getProvider();if(!eo)return;const{address:to,publicKey:ro}=yield eo.connect(),no={address:to,publicKey:ro};return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:to,ordinalsAddress:no}),to})}signMessage(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(to)return to.signMessage(eo,"bip322-simple")})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!(!(yield this.getAddress())||!to))return to.sendBitcoin(eo.recipientAddress,eo.amount.toString())})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),no=yield to.signPsbt(ro.toHex(),createPsbtOptions(ro,eo));return{signedPsbt:src$3.Psbt.fromHex(no).toBase64()}})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=[],no=[];for(const oo of eo){const ao=src$3.Psbt.fromBase64(oo.unsignedPsbtBase64);ro.push(ao.toHex()),no.push(createPsbtOptions(ao,oo))}return(yield to.signPsbts(ro,no)).map(oo=>src$3.Psbt.fromHex(oo).toBase64())})}}class OylConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"oylwallet"})),this.name="Oyl Wallet",this.overrideKey="oylwallet"}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const to=this.getProvider();if(!to)return;const ro=yield to.getAddresses(),no=ro.taproot,io=ro.nativeSegwit,oo=(eo=no==null?void 0:no.address)!==null&&eo!==void 0?eo:io==null?void 0:io.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:oo,ordinalsAddress:no,paymentAddress:io}),oo})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){const ro=this.getProvider();if(!ro)return;const{signature:no}=yield ro.signMessage({address:to,message:eo});return no})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),no=createPsbtOptions(ro,eo),{psbt:io}=yield to.signPsbt({broadcast:!1,finalize:no.autoFinalized,psbt:ro.toHex()});return{signedPsbt:src$3.Psbt.fromHex(io).toBase64()}})}}class UnisatConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"unisat"})),this.name="UniSat",this.overrideKey="unisat"}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){const eo=this.getProvider();if(!eo)return;const[to]=yield eo.requestAccounts(),ro=yield eo.getPublicKey(),no={address:to,publicKey:ro};return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:to,ordinalsAddress:no}),to})}signMessage(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(to)return to.signMessage(eo,"bip322-simple")})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!(!(yield this.getAddress())||!to))return to.sendBitcoin(eo.recipientAddress,Number(eo.amount))})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),no=yield to.signPsbt(ro.toHex(),createPsbtOptions(ro,eo));return{signedPsbt:src$3.Psbt.fromHex(no).toBase64()}})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=[],no=[];for(const oo of eo){const ao=src$3.Psbt.fromBase64(oo.unsignedPsbtBase64);ro.push(ao.toHex()),no.push(createPsbtOptions(ao,oo))}return(yield to.signPsbts(ro,no)).map(oo=>src$3.Psbt.fromHex(oo).toBase64())})}getConnectedAccounts(){return __awaiter$i(this,void 0,void 0,function*(){const eo=this.getProvider();return eo?eo.getAccounts():[]})}}class UnknownInjectedConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"unknown"})),this.name="Unknown",this.overrideKey="unknown"}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){})}}class FallbackBitcoinConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"fallbackconnector"})),this.name="Fallback Connector",this.overrideKey="fallbackconnector",this.isAvailable=!1}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){})}}assertPackageVersion("@dynamic-labs/bitcoin",version$j);const BitcoinWalletConnectors=Xr=>[...fetchSatsConnectConnectors(Xr),...fetchBtcKitConnectors(Xr),PhantomConnector,OkxConnector,OylConnector,UnisatConnector,UnknownInjectedConnector,FallbackBitcoinConnector];var version$h="3.4.4";function __awaiter$f(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;class CosmosWallet extends Wallet$1{getProvider(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this._connector.getProvider();if(!eo)throw new Error("unable to retrieve Cosmos provider");try{return cloneObjectWithOverrides(eo,{sendEthereumTx:(to,ro)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.sendEthereumTx(to,ro)}),sendTx:(to,ro,no)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.sendTx(to,ro,no)}),signAmino:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signAmino(to,ro,no,io)}),signArbitrary:(to,ro,no)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signArbitrary(to,ro,no)}),signDirect:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signDirect(to,ro,no,io)}),signDirectAux:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signDirectAux(to,ro,no,io)}),signEthereum:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signEthereum(to,ro,no,io)}),signICNSAdr36:(to,ro,no,io,oo)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signICNSAdr36(to,ro,no,io,oo)})})}catch(to){return logger$9.warn(`Failed to add logic to auto-sync the wallet. Provider might be out of sync for wallet: ${this._connector.name} (${this.address})`,to),eo}})}getOfflineSigner(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this._connector.getOfflineSigner();if(!eo)throw new Error("unable to retrieve Cosmos offline signer");try{return cloneObjectWithOverrides(eo,{signAmino:(to,ro)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signAmino(to,ro)}),signDirect:(to,ro)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signDirect(to,ro)})})}catch(to){return logger$9.warn(`Failed to add logic to auto-sync the wallet. Signer might be out of sync for wallet: ${this._connector.name} (${this.address})`,to),eo}})}}class CosmosWalletConnector extends WalletConnectorBase{constructor(eo){super(eo),this.ChainWallet=CosmosWallet,this.connectedChain="COSMOS",this.supportedChains=["COSMOS"],this.evmNetworks=parseEvmNetworks(eo.cosmosNetworks),this.chainIdMapping=this.evmNetworks.map(to=>({cosmosNetworkId:to.name,dynamicChainId:parseChainId(to.networkId),evmNetwork:to}))}getSelectedNetwork(){const eo=this.chainIdMapping.find(to=>to.cosmosNetworkId===this.getChainId());return eo==null?void 0:eo.evmNetwork}getNetwork(){return __awaiter$f(this,void 0,void 0,function*(){var eo;return(eo=this.getSelectedNetwork())===null||eo===void 0?void 0:eo.chainId})}getLcdUrl(){var eo;return(eo=this.getSelectedNetwork())===null||eo===void 0?void 0:eo.lcdUrl}getDenom(){var eo;return(eo=this.getSelectedNetwork())===null||eo===void 0?void 0:eo.nativeCurrency.denom}getBalance(eo){return __awaiter$f(this,void 0,void 0,function*(){try{return(yield fetch(`${this.getLcdUrl()}/cosmos/bank/v1beta1/balances/${eo}`).then(no=>no.json())).balances.reduce((no,io)=>io.denom===this.getDenom()?Number(io.amount)/1e6:no,0).toString()}catch(to){return logger$9.error(to),"0"}})}getConnectedAccounts(){return __awaiter$f(this,void 0,void 0,function*(){return[yield this.getAddress()]})}endSession(){return __awaiter$f(this,void 0,void 0,function*(){this.setChainId(null)})}}const DYNAMIC_KEPLR_NETWORK_ID="dynamic_keplr_network_id";class KeplrWalletConnector extends CosmosWalletConnector{constructor(eo){super(eo),this.switchNetworkOnlyFromWallet=!0,this.name="Keplr",this.overrideKey="keplr",this._handleAccountChange=this._handleAccountChange.bind(this)}getDefaultChainId(){return this.chainIdMapping.length===0||this.chainIdMapping.find(eo=>eo.cosmosNetworkId==="cosmoshub-4")?"cosmoshub-4":this.chainIdMapping[0].cosmosNetworkId}getChainId(){const eo=this.getDefaultChainId(),to=localStorage.getItem(DYNAMIC_KEPLR_NETWORK_ID);return to??eo}setChainId(eo){eo?localStorage.setItem(DYNAMIC_KEPLR_NETWORK_ID,eo):localStorage.removeItem(DYNAMIC_KEPLR_NETWORK_ID)}getAccount(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this.keplr.getOfflineSigner(this.getChainId()).getAccounts();if(!eo)throw new Error("No accounts found");const[to]=eo;return to})}get keplr(){if(typeof window>"u")throw new Error("Keplr is not available");return window.keplr}connect(){return __awaiter$f(this,void 0,void 0,function*(){yield this.keplr.enable(this.chainIdMapping.map(eo=>eo.cosmosNetworkId))})}getAddress(){return __awaiter$f(this,void 0,void 0,function*(){return yield this.connect(),(yield this.getAccount()).address})}getProvider(){return __awaiter$f(this,void 0,void 0,function*(){return this.keplr})}getOfflineSigner(){return __awaiter$f(this,void 0,void 0,function*(){return this.keplr.getOfflineSigner(this.getChainId())})}isInstalledOnBrowser(){return typeof window.keplr<"u"}_handleAccountChange(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this.getAddress();this.emit("accountChange",{accounts:[eo]})})}setupEventListeners(){window.addEventListener("keplr_keystorechange",this._handleAccountChange)}teardownEventListeners(){window.removeEventListener("keplr_keystorechange",this._handleAccountChange),this.setChainId(null)}getSignDoc(eo){return{account_number:"0",chain_id:this.getChainId(),fee:{amount:[],gas:"0"},memo:"",msgs:[{type:"custom/MsgSignText",value:{text:eo}}],sequence:"0"}}signMessage(eo){return __awaiter$f(this,void 0,void 0,function*(){const to=this.getSignDoc(eo),ro=yield this.getAddress(),no=yield this.keplr.signAmino(this.getChainId(),ro,to);if(!no)throw new Error("Could not sign message");return JSON.stringify(no)})}supportsNetworkSwitching(){return!0}switchNetwork(eo){return __awaiter$f(this,arguments,void 0,function*({networkChainId:to}){to&&this.chainIdMapping.forEach(ro=>{ro.dynamicChainId===to&&(this.setChainId(ro.cosmosNetworkId),this.emit("chainChange",{chain:to.toString()}))})})}}assertPackageVersion("@dynamic-labs/cosmos",version$h);const CosmosWalletConnectors=()=>[KeplrWalletConnector];typeof window<"u"&&(window.global=globalThis,Object.assign(window,{Buffer:Buffer$1$1}));var version$g="3.4.4",version$f="3.4.4";function __awaiter$e(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}function __classPrivateFieldGet$3(Xr,eo,to,ro){if(to==="a"&&!ro)throw new TypeError("Private accessor was defined without a getter");if(typeof eo=="function"?Xr!==eo||!ro:!eo.has(Xr))throw new TypeError("Cannot read private member from an object whose class did not declare it");return to==="m"?ro:to==="a"?ro.call(Xr):ro?ro.value:eo.get(Xr)}function __classPrivateFieldSet$3(Xr,eo,to,ro,no){if(typeof eo=="function"?Xr!==eo||!no:!eo.has(Xr))throw new TypeError("Cannot write private member to an object whose class did not declare it");return no?no.value=to:eo.set(Xr,to),to}typeof SuppressedError=="function"&&SuppressedError;const DEFAULT_JWK_MEMBER_BYTE_LENGTH=32;function stringToBase64urlString(Xr){const eo=btoa$1(Xr);return base64StringToBase64UrlEncodedString(eo)}function hexStringToBase64url(Xr,eo){const to=Xr.padStart(Math.ceil(Xr.length/2)*2,"0"),ro=uint8ArrayFromHexString(to,eo);return stringToBase64urlString(ro.reduce((no,io)=>no+String.fromCharCode(io),""))}function base64StringToBase64UrlEncodedString(Xr){return Xr.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uint8ArrayToHexString(Xr){return Xr.reduce((eo,to)=>eo+to.toString(16).padStart(2,"0"),"")}const uint8ArrayFromHexString=(Xr,eo)=>{const to=/^[0-9A-Fa-f]+$/;if(!Xr||Xr.length%2!=0||!to.test(Xr))throw new Error(`cannot create uint8array from invalid hex string: "${Xr}"`);const ro=new Uint8Array(Xr.match(/../g).map(io=>parseInt(io,16)));if(!eo)return ro;if(Xr.length/2>eo)throw new Error("hex value cannot fit in a buffer of "+eo+" byte(s)");let no=new Uint8Array(eo);return no.set(ro,eo-ro.length),no};function btoa$1(Xr){if(arguments.length===0)throw new TypeError("1 argument required, but only 0 present.");let eo;for(Xr=`${Xr}`,eo=0;eo255)throw new Error(`InvalidCharacterError: found code point greater than 255:${Xr.charCodeAt(eo)} at position ${eo}`);let to="";for(eo=0;eo>2,ro[1]=(Xr.charCodeAt(eo)&3)<<4,Xr.length>eo+1&&(ro[1]|=Xr.charCodeAt(eo+1)>>4,ro[2]=(Xr.charCodeAt(eo+1)&15)<<2),Xr.length>eo+2&&(ro[2]|=Xr.charCodeAt(eo+2)>>6,ro[3]=Xr.charCodeAt(eo+2)&63);for(let no=0;no"u"?to+="=":to+=btoaLookup(ro[no])}return to}function btoaLookup(Xr){const eo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";if(Xr>=0&&Xr<64)return eo[Xr]}const stampHeaderName$2="X-Stamp",isCryptoEnabledBrowser=typeof window<"u"&&typeof window.document<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u",isNode=typeof process$1$1<"u"&&process$1$1.versions!=null&&process$1$1.versions.node!=null,signWithApiKey=async Xr=>isCryptoEnabledBrowser?(await __vitePreload(()=>import("./webcrypto-3I5ubJVL.js"),__vite__mapDeps([0,1])).then(to=>to.signWithApiKey))(Xr):isNode?(await __vitePreload(()=>import("./nodecrypto-Co9-WRDE.js"),__vite__mapDeps([2,1])).then(to=>to.signWithApiKey))(Xr):(await __vitePreload(()=>import("./purejs-IJPcfd_M.js"),[]).then(to=>to.signWithApiKey))(Xr);class ApiKeyStamper{constructor(eo){this.apiPublicKey=eo.apiPublicKey,this.apiPrivateKey=eo.apiPrivateKey}async stamp(eo){const to=await signWithApiKey({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:eo}),ro={publicKey:this.apiPublicKey,scheme:"SIGNATURE_SCHEME_TK_API_P256",signature:to};return{stampHeaderName:stampHeaderName$2,stampHeaderValue:stringToBase64urlString(JSON.stringify(ro))}}}const base64UrlEncode=Xr=>Buffer$3.from(Xr).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),generateRandomBuffer=()=>{const Xr=new Uint8Array(32);return crypto.getRandomValues(Xr),Xr.buffer},transportMap={AUTHENTICATOR_TRANSPORT_BLE:AuthenticatorTransportProtocol.Ble,AUTHENTICATOR_TRANSPORT_HYBRID:AuthenticatorTransportProtocol.Hybrid,AUTHENTICATOR_TRANSPORT_INTERNAL:AuthenticatorTransportProtocol.Internal,AUTHENTICATOR_TRANSPORT_NFC:AuthenticatorTransportProtocol.Nfc,AUTHENTICATOR_TRANSPORT_USB:AuthenticatorTransportProtocol.Usb},convertAttestationTransports=Xr=>Xr.map(eo=>transportMap[eo]),TURNKEY_API_BASE_URL="https://api.turnkey.com",TURNKEY_API_KEY_EXPIRY_MESSAGE="Turnkey error 16: expired api key",TURNKEY_API_KEY_NOT_FOUND_MESSAGE="Turnkey error 16: could not find public key",WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE="The operation either timed out or was not allowed",WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE="The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",INVALID_PASSKEY_SELECTED_ERROR_MESSAGE="Turnkey error 5: webauthn authenticator not found in organization or parent organization",USER_CANCELLED_REQUEST_ERROR_MESSAGE="The user cancelled the request",TURNKEY_SDK_SESSION_KEY_RETRYABLE_ERRORS=[TURNKEY_API_KEY_EXPIRY_MESSAGE,TURNKEY_API_KEY_NOT_FOUND_MESSAGE],TURNKEY_SDK_BENIGN_ERRORS=[WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE,WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE,INVALID_PASSKEY_SELECTED_ERROR_MESSAGE,USER_CANCELLED_REQUEST_ERROR_MESSAGE];class DynamicEmbeddedWalletsLogger extends Logger$2{constructor(eo,to){super(eo,to)}error(eo,...to){const[ro]=to;!(ro!=null&&ro.message)||!TURNKEY_SDK_BENIGN_ERRORS.some(no=>ro.message.includes(no))?(Logger$2.events.emit("error",eo),this.log(LogLevel.ERROR,eo,...to)):this.warn(eo,...to)}}const logger$6=new DynamicEmbeddedWalletsLogger("Dynamic embedded wallets",LogLevel.INFO),stampHeaderName$1="X-Stamp";var IframeEventType;(function(Xr){Xr.PublicKeyReady="PUBLIC_KEY_READY",Xr.InjectCredentialBundle="INJECT_CREDENTIAL_BUNDLE",Xr.InjectKeyExportBundle="INJECT_KEY_EXPORT_BUNDLE",Xr.InjectWalletExportBundle="INJECT_WALLET_EXPORT_BUNDLE",Xr.InjectImportBundle="INJECT_IMPORT_BUNDLE",Xr.ExtractWalletEncryptedBundle="EXTRACT_WALLET_ENCRYPTED_BUNDLE",Xr.ExtractKeyEncryptedBundle="EXTRACT_KEY_ENCRYPTED_BUNDLE",Xr.ApplySettings="APPLY_SETTINGS",Xr.BundleInjected="BUNDLE_INJECTED",Xr.EncryptedBundleExtracted="ENCRYPTED_BUNDLE_EXTRACTED",Xr.SettingsApplied="SETTINGS_APPLIED",Xr.StampRequest="STAMP_REQUEST",Xr.Stamp="STAMP",Xr.Error="ERROR"})(IframeEventType||(IframeEventType={}));var KeyFormat;(function(Xr){Xr.Hexadecimal="HEXADECIMAL",Xr.Solana="SOLANA"})(KeyFormat||(KeyFormat={}));class IframeStamper{constructor(eo){if(typeof window>"u")throw new Error("Cannot initialize iframe in non-browser environment");if(!eo.iframeContainer)throw new Error("Iframe container cannot be found");if(this.container=eo.iframeContainer,this.container.querySelector(`#${eo.iframeElementId}`))throw new Error(`Iframe element with ID ${eo.iframeElementId} already exists`);let to=window.document.createElement("iframe");to.setAttribute("sandbox","allow-scripts allow-same-origin"),to.id=eo.iframeElementId,to.src=eo.iframeUrl,this.iframe=to;const ro=new URL(eo.iframeUrl);this.iframeOrigin=ro.origin,this.iframePublicKey=null}async init(){return this.container.appendChild(this.iframe),new Promise((eo,to)=>{window.addEventListener("message",ro=>{var no;ro.origin===this.iframeOrigin&&((no=ro.data)==null?void 0:no.type)===IframeEventType.PublicKeyReady&&(this.iframePublicKey=ro.data.value,eo(ro.data.value))},!1)})}clear(){this.iframe.remove()}publicKey(){return this.iframePublicKey}async injectCredentialBundle(eo){return new Promise((to,ro)=>{var no;(no=this.iframe.contentWindow)==null||no.postMessage({type:IframeEventType.InjectCredentialBundle,value:eo},"*"),window.addEventListener("message",io=>{var oo,ao;io.origin===this.iframeOrigin&&(((oo=io.data)==null?void 0:oo.type)===IframeEventType.BundleInjected&&to(io.data.value),((ao=io.data)==null?void 0:ao.type)===IframeEventType.Error&&ro(io.data.value))},!1)})}async injectKeyExportBundle(eo,to,ro){var no;return(no=this.iframe.contentWindow)==null||no.postMessage({type:IframeEventType.InjectKeyExportBundle,value:eo,keyFormat:ro,organizationId:to},"*"),new Promise((io,oo)=>{window.addEventListener("message",ao=>{var so,co;ao.origin===this.iframeOrigin&&(((so=ao.data)==null?void 0:so.type)===IframeEventType.BundleInjected&&io(ao.data.value),((co=ao.data)==null?void 0:co.type)===IframeEventType.Error&&oo(ao.data.value))},!1)})}async injectWalletExportBundle(eo,to){var ro;return(ro=this.iframe.contentWindow)==null||ro.postMessage({type:IframeEventType.InjectWalletExportBundle,value:eo,organizationId:to},"*"),new Promise((no,io)=>{window.addEventListener("message",oo=>{var ao,so;oo.origin===this.iframeOrigin&&(((ao=oo.data)==null?void 0:ao.type)===IframeEventType.BundleInjected&&no(oo.data.value),((so=oo.data)==null?void 0:so.type)===IframeEventType.Error&&io(oo.data.value))},!1)})}async injectImportBundle(eo,to,ro){var no;return(no=this.iframe.contentWindow)==null||no.postMessage({type:IframeEventType.InjectImportBundle,value:eo,organizationId:to,userId:ro},"*"),new Promise((io,oo)=>{window.addEventListener("message",ao=>{var so,co;ao.origin===this.iframeOrigin&&(((so=ao.data)==null?void 0:so.type)===IframeEventType.BundleInjected&&io(ao.data.value),((co=ao.data)==null?void 0:co.type)===IframeEventType.Error&&oo(ao.data.value))},!1)})}async extractWalletEncryptedBundle(){var eo;return(eo=this.iframe.contentWindow)==null||eo.postMessage({type:IframeEventType.ExtractWalletEncryptedBundle},"*"),new Promise((to,ro)=>{window.addEventListener("message",no=>{var io,oo;no.origin===this.iframeOrigin&&(((io=no.data)==null?void 0:io.type)===IframeEventType.EncryptedBundleExtracted&&to(no.data.value),((oo=no.data)==null?void 0:oo.type)===IframeEventType.Error&&ro(no.data.value))},!1)})}async extractKeyEncryptedBundle(eo){var to;return(to=this.iframe.contentWindow)==null||to.postMessage({type:IframeEventType.ExtractKeyEncryptedBundle,keyFormat:eo},"*"),new Promise((ro,no)=>{window.addEventListener("message",io=>{var oo,ao;io.origin===this.iframeOrigin&&(((oo=io.data)==null?void 0:oo.type)===IframeEventType.EncryptedBundleExtracted&&ro(io.data.value),((ao=io.data)==null?void 0:ao.type)===IframeEventType.Error&&no(io.data.value))},!1)})}async applySettings(eo){var ro;const to=JSON.stringify(eo);return(ro=this.iframe.contentWindow)==null||ro.postMessage({type:IframeEventType.ApplySettings,value:to},"*"),new Promise((no,io)=>{window.addEventListener("message",oo=>{var ao,so;oo.origin===this.iframeOrigin&&(((ao=oo.data)==null?void 0:ao.type)===IframeEventType.SettingsApplied&&no(oo.data.value),((so=oo.data)==null?void 0:so.type)===IframeEventType.Error&&io(oo.data.value))},!1)})}async stamp(eo){var ro;if(this.iframePublicKey===null)throw new Error("null iframe public key. Have you called/awaited .init()?");const to=this.iframeOrigin;return(ro=this.iframe.contentWindow)==null||ro.postMessage({type:IframeEventType.StampRequest,value:eo},"*"),new Promise(function(no,io){window.addEventListener("message",oo=>{var ao,so;oo.origin===to&&(((ao=oo.data)==null?void 0:ao.type)===IframeEventType.Stamp&&no({stampHeaderName:stampHeaderName$1,stampHeaderValue:oo.data.value}),((so=oo.data)==null?void 0:so.type)===IframeEventType.Error&&io(oo.data.value))},!1)})}}var browserPonyfill={exports:{}};(function(Xr,eo){var to=typeof self<"u"?self:commonjsGlobal,ro=function(){function io(){this.fetch=!1,this.DOMException=to.DOMException}return io.prototype=to,new io}();(function(io){(function(oo){var ao={searchParams:"URLSearchParams"in io,iterable:"Symbol"in io&&"iterator"in Symbol,blob:"FileReader"in io&&"Blob"in io&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in io,arrayBuffer:"ArrayBuffer"in io};function so(uo){return uo&&DataView.prototype.isPrototypeOf(uo)}if(ao.arrayBuffer)var co=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],lo=ArrayBuffer.isView||function(uo){return uo&&co.indexOf(Object.prototype.toString.call(uo))>-1};function fo(uo){if(typeof uo!="string"&&(uo=String(uo)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(uo))throw new TypeError("Invalid character in header field name");return uo.toLowerCase()}function ho(uo){return typeof uo!="string"&&(uo=String(uo)),uo}function go(uo){var po={next:function(){var bo=uo.shift();return{done:bo===void 0,value:bo}}};return ao.iterable&&(po[Symbol.iterator]=function(){return po}),po}function yo(uo){this.map={},uo instanceof yo?uo.forEach(function(po,bo){this.append(bo,po)},this):Array.isArray(uo)?uo.forEach(function(po){this.append(po[0],po[1])},this):uo&&Object.getOwnPropertyNames(uo).forEach(function(po){this.append(po,uo[po])},this)}yo.prototype.append=function(uo,po){uo=fo(uo),po=ho(po);var bo=this.map[uo];this.map[uo]=bo?bo+", "+po:po},yo.prototype.delete=function(uo){delete this.map[fo(uo)]},yo.prototype.get=function(uo){return uo=fo(uo),this.has(uo)?this.map[uo]:null},yo.prototype.has=function(uo){return this.map.hasOwnProperty(fo(uo))},yo.prototype.set=function(uo,po){this.map[fo(uo)]=ho(po)},yo.prototype.forEach=function(uo,po){for(var bo in this.map)this.map.hasOwnProperty(bo)&&uo.call(po,this.map[bo],bo,this)},yo.prototype.keys=function(){var uo=[];return this.forEach(function(po,bo){uo.push(bo)}),go(uo)},yo.prototype.values=function(){var uo=[];return this.forEach(function(po){uo.push(po)}),go(uo)},yo.prototype.entries=function(){var uo=[];return this.forEach(function(po,bo){uo.push([bo,po])}),go(uo)},ao.iterable&&(yo.prototype[Symbol.iterator]=yo.prototype.entries);function vo(uo){if(uo.bodyUsed)return Promise.reject(new TypeError("Already read"));uo.bodyUsed=!0}function wo(uo){return new Promise(function(po,bo){uo.onload=function(){po(uo.result)},uo.onerror=function(){bo(uo.error)}})}function Eo(uo){var po=new FileReader,bo=wo(po);return po.readAsArrayBuffer(uo),bo}function ko(uo){var po=new FileReader,bo=wo(po);return po.readAsText(uo),bo}function Ao(uo){for(var po=new Uint8Array(uo),bo=new Array(po.length),_o=0;_o-1?po:uo}function Do(uo,po){po=po||{};var bo=po.body;if(uo instanceof Do){if(uo.bodyUsed)throw new TypeError("Already read");this.url=uo.url,this.credentials=uo.credentials,po.headers||(this.headers=new yo(uo.headers)),this.method=uo.method,this.mode=uo.mode,this.signal=uo.signal,!bo&&uo._bodyInit!=null&&(bo=uo._bodyInit,uo.bodyUsed=!0)}else this.url=String(uo);if(this.credentials=po.credentials||this.credentials||"same-origin",(po.headers||!this.headers)&&(this.headers=new yo(po.headers)),this.method=No(po.method||this.method||"GET"),this.mode=po.mode||this.mode||null,this.signal=po.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&bo)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(bo)}Do.prototype.clone=function(){return new Do(this,{body:this._bodyInit})};function Fo(uo){var po=new FormData;return uo.trim().split("&").forEach(function(bo){if(bo){var _o=bo.split("="),$o=_o.shift().replace(/\+/g," "),Co=_o.join("=").replace(/\+/g," ");po.append(decodeURIComponent($o),decodeURIComponent(Co))}}),po}function Xo(uo){var po=new yo,bo=uo.replace(/\r?\n[\t ]+/g," ");return bo.split(/\r?\n/).forEach(function(_o){var $o=_o.split(":"),Co=$o.shift().trim();if(Co){var Ro=$o.join(":").trim();po.append(Co,Ro)}}),po}jo.call(Do.prototype);function Lo(uo,po){po||(po={}),this.type="default",this.status=po.status===void 0?200:po.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in po?po.statusText:"OK",this.headers=new yo(po.headers),this.url=po.url||"",this._initBody(uo)}jo.call(Lo.prototype),Lo.prototype.clone=function(){return new Lo(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new yo(this.headers),url:this.url})},Lo.error=function(){var uo=new Lo(null,{status:0,statusText:""});return uo.type="error",uo};var Bo=[301,302,303,307,308];Lo.redirect=function(uo,po){if(Bo.indexOf(po)===-1)throw new RangeError("Invalid status code");return new Lo(null,{status:po,headers:{location:uo}})},oo.DOMException=io.DOMException;try{new oo.DOMException}catch{oo.DOMException=function(po,bo){this.message=po,this.name=bo;var _o=Error(po);this.stack=_o.stack},oo.DOMException.prototype=Object.create(Error.prototype),oo.DOMException.prototype.constructor=oo.DOMException}function xo(uo,po){return new Promise(function(bo,_o){var $o=new Do(uo,po);if($o.signal&&$o.signal.aborted)return _o(new oo.DOMException("Aborted","AbortError"));var Co=new XMLHttpRequest;function Ro(){Co.abort()}Co.onload=function(){var So={status:Co.status,statusText:Co.statusText,headers:Xo(Co.getAllResponseHeaders()||"")};So.url="responseURL"in Co?Co.responseURL:So.headers.get("X-Request-URL");var mo="response"in Co?Co.response:Co.responseText;bo(new Lo(mo,So))},Co.onerror=function(){_o(new TypeError("Network request failed"))},Co.ontimeout=function(){_o(new TypeError("Network request failed"))},Co.onabort=function(){_o(new oo.DOMException("Aborted","AbortError"))},Co.open($o.method,$o.url,!0),$o.credentials==="include"?Co.withCredentials=!0:$o.credentials==="omit"&&(Co.withCredentials=!1),"responseType"in Co&&ao.blob&&(Co.responseType="blob"),$o.headers.forEach(function(So,mo){Co.setRequestHeader(mo,So)}),$o.signal&&($o.signal.addEventListener("abort",Ro),Co.onreadystatechange=function(){Co.readyState===4&&$o.signal.removeEventListener("abort",Ro)}),Co.send(typeof $o._bodyInit>"u"?null:$o._bodyInit)})}return xo.polyfill=!0,io.fetch||(io.fetch=xo,io.Headers=yo,io.Request=Do,io.Response=Lo),oo.Headers=yo,oo.Request=Do,oo.Response=Lo,oo.fetch=xo,Object.defineProperty(oo,"__esModule",{value:!0}),oo})({})})(ro),ro.fetch.ponyfill=!0,delete ro.fetch.polyfill;var no=ro;eo=no.fetch,eo.default=no.fetch,eo.fetch=no.fetch,eo.Headers=no.Headers,eo.Request=no.Request,eo.Response=no.Response,Xr.exports=eo})(browserPonyfill,browserPonyfill.exports);var browserPonyfillExports=browserPonyfill.exports;const fetchTransport=getDefaultExportFromCjs$2(browserPonyfillExports),fetch$2=browserPonyfillExports.fetch;class TurnkeyRequestError extends Error{constructor(eo){let to=`Turnkey error ${eo.code}: ${eo.message}`;eo.details!=null&&(to+=` (Details: ${JSON.stringify(eo.details)})`),super(to),this.name="TurnkeyRequestError",this.details=eo.details??null,this.code=eo.code}}const VERSION$3="@turnkey/http@2.12.2";class TurnkeyClient{constructor(eo,to){if(this.getActivity=async ro=>this.request("/public/v1/query/get_activity",ro),this.stampGetActivity=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_activity",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getApiKey=async ro=>this.request("/public/v1/query/get_api_key",ro),this.stampGetApiKey=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_api_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getApiKeys=async ro=>this.request("/public/v1/query/get_api_keys",ro),this.stampGetApiKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_api_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getAttestationDocument=async ro=>this.request("/public/v1/query/get_attestation",ro),this.stampGetAttestationDocument=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_attestation",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getAuthenticator=async ro=>this.request("/public/v1/query/get_authenticator",ro),this.stampGetAuthenticator=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_authenticator",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getAuthenticators=async ro=>this.request("/public/v1/query/get_authenticators",ro),this.stampGetAuthenticators=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_authenticators",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getOauthProviders=async ro=>this.request("/public/v1/query/get_oauth_providers",ro),this.stampGetOauthProviders=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_oauth_providers",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getOrganization=async ro=>this.request("/public/v1/query/get_organization",ro),this.stampGetOrganization=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_organization",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getOrganizationConfigs=async ro=>this.request("/public/v1/query/get_organization_configs",ro),this.stampGetOrganizationConfigs=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_organization_configs",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPolicy=async ro=>this.request("/public/v1/query/get_policy",ro),this.stampGetPolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPrivateKey=async ro=>this.request("/public/v1/query/get_private_key",ro),this.stampGetPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getUser=async ro=>this.request("/public/v1/query/get_user",ro),this.stampGetUser=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_user",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWallet=async ro=>this.request("/public/v1/query/get_wallet",ro),this.stampGetWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getActivities=async ro=>this.request("/public/v1/query/list_activities",ro),this.stampGetActivities=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_activities",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPolicies=async ro=>this.request("/public/v1/query/list_policies",ro),this.stampGetPolicies=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_policies",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.listPrivateKeyTags=async ro=>this.request("/public/v1/query/list_private_key_tags",ro),this.stampListPrivateKeyTags=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_private_key_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPrivateKeys=async ro=>this.request("/public/v1/query/list_private_keys",ro),this.stampGetPrivateKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_private_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getSubOrgIds=async ro=>this.request("/public/v1/query/list_suborgs",ro),this.stampGetSubOrgIds=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_suborgs",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.listUserTags=async ro=>this.request("/public/v1/query/list_user_tags",ro),this.stampListUserTags=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_user_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getUsers=async ro=>this.request("/public/v1/query/list_users",ro),this.stampGetUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWalletAccounts=async ro=>this.request("/public/v1/query/list_wallet_accounts",ro),this.stampGetWalletAccounts=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_wallet_accounts",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWallets=async ro=>this.request("/public/v1/query/list_wallets",ro),this.stampGetWallets=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_wallets",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWhoami=async ro=>this.request("/public/v1/query/whoami",ro),this.stampGetWhoami=async ro=>{const no=this.config.baseUrl+"/public/v1/query/whoami",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.approveActivity=async ro=>this.request("/public/v1/submit/approve_activity",ro),this.stampApproveActivity=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/approve_activity",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createApiKeys=async ro=>this.request("/public/v1/submit/create_api_keys",ro),this.stampCreateApiKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_api_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createApiOnlyUsers=async ro=>this.request("/public/v1/submit/create_api_only_users",ro),this.stampCreateApiOnlyUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_api_only_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createAuthenticators=async ro=>this.request("/public/v1/submit/create_authenticators",ro),this.stampCreateAuthenticators=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_authenticators",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createInvitations=async ro=>this.request("/public/v1/submit/create_invitations",ro),this.stampCreateInvitations=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_invitations",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createOauthProviders=async ro=>this.request("/public/v1/submit/create_oauth_providers",ro),this.stampCreateOauthProviders=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_oauth_providers",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPolicies=async ro=>this.request("/public/v1/submit/create_policies",ro),this.stampCreatePolicies=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_policies",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPolicy=async ro=>this.request("/public/v1/submit/create_policy",ro),this.stampCreatePolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPrivateKeyTag=async ro=>this.request("/public/v1/submit/create_private_key_tag",ro),this.stampCreatePrivateKeyTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_private_key_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPrivateKeys=async ro=>this.request("/public/v1/submit/create_private_keys",ro),this.stampCreatePrivateKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_private_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createReadOnlySession=async ro=>this.request("/public/v1/submit/create_read_only_session",ro),this.stampCreateReadOnlySession=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_read_only_session",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createReadWriteSession=async ro=>this.request("/public/v1/submit/create_read_write_session",ro),this.stampCreateReadWriteSession=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_read_write_session",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createSubOrganization=async ro=>this.request("/public/v1/submit/create_sub_organization",ro),this.stampCreateSubOrganization=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_sub_organization",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createUserTag=async ro=>this.request("/public/v1/submit/create_user_tag",ro),this.stampCreateUserTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_user_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createUsers=async ro=>this.request("/public/v1/submit/create_users",ro),this.stampCreateUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createWallet=async ro=>this.request("/public/v1/submit/create_wallet",ro),this.stampCreateWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createWalletAccounts=async ro=>this.request("/public/v1/submit/create_wallet_accounts",ro),this.stampCreateWalletAccounts=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_wallet_accounts",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteApiKeys=async ro=>this.request("/public/v1/submit/delete_api_keys",ro),this.stampDeleteApiKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_api_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteAuthenticators=async ro=>this.request("/public/v1/submit/delete_authenticators",ro),this.stampDeleteAuthenticators=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_authenticators",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteInvitation=async ro=>this.request("/public/v1/submit/delete_invitation",ro),this.stampDeleteInvitation=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_invitation",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteOauthProviders=async ro=>this.request("/public/v1/submit/delete_oauth_providers",ro),this.stampDeleteOauthProviders=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_oauth_providers",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deletePolicy=async ro=>this.request("/public/v1/submit/delete_policy",ro),this.stampDeletePolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deletePrivateKeyTags=async ro=>this.request("/public/v1/submit/delete_private_key_tags",ro),this.stampDeletePrivateKeyTags=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_private_key_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteUserTags=async ro=>this.request("/public/v1/submit/delete_user_tags",ro),this.stampDeleteUserTags=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_user_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteUsers=async ro=>this.request("/public/v1/submit/delete_users",ro),this.stampDeleteUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.emailAuth=async ro=>this.request("/public/v1/submit/email_auth",ro),this.stampEmailAuth=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/email_auth",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.exportPrivateKey=async ro=>this.request("/public/v1/submit/export_private_key",ro),this.stampExportPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/export_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.exportWallet=async ro=>this.request("/public/v1/submit/export_wallet",ro),this.stampExportWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/export_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.exportWalletAccount=async ro=>this.request("/public/v1/submit/export_wallet_account",ro),this.stampExportWalletAccount=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/export_wallet_account",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.importPrivateKey=async ro=>this.request("/public/v1/submit/import_private_key",ro),this.stampImportPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/import_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.importWallet=async ro=>this.request("/public/v1/submit/import_wallet",ro),this.stampImportWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/import_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.initImportPrivateKey=async ro=>this.request("/public/v1/submit/init_import_private_key",ro),this.stampInitImportPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/init_import_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.initImportWallet=async ro=>this.request("/public/v1/submit/init_import_wallet",ro),this.stampInitImportWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/init_import_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.initUserEmailRecovery=async ro=>this.request("/public/v1/submit/init_user_email_recovery",ro),this.stampInitUserEmailRecovery=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/init_user_email_recovery",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.oauth=async ro=>this.request("/public/v1/submit/oauth",ro),this.stampOauth=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/oauth",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.recoverUser=async ro=>this.request("/public/v1/submit/recover_user",ro),this.stampRecoverUser=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/recover_user",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.rejectActivity=async ro=>this.request("/public/v1/submit/reject_activity",ro),this.stampRejectActivity=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/reject_activity",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.removeOrganizationFeature=async ro=>this.request("/public/v1/submit/remove_organization_feature",ro),this.stampRemoveOrganizationFeature=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/remove_organization_feature",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.setOrganizationFeature=async ro=>this.request("/public/v1/submit/set_organization_feature",ro),this.stampSetOrganizationFeature=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/set_organization_feature",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.signRawPayload=async ro=>this.request("/public/v1/submit/sign_raw_payload",ro),this.stampSignRawPayload=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/sign_raw_payload",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.signRawPayloads=async ro=>this.request("/public/v1/submit/sign_raw_payloads",ro),this.stampSignRawPayloads=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/sign_raw_payloads",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.signTransaction=async ro=>this.request("/public/v1/submit/sign_transaction",ro),this.stampSignTransaction=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/sign_transaction",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updatePolicy=async ro=>this.request("/public/v1/submit/update_policy",ro),this.stampUpdatePolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updatePrivateKeyTag=async ro=>this.request("/public/v1/submit/update_private_key_tag",ro),this.stampUpdatePrivateKeyTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_private_key_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updateRootQuorum=async ro=>this.request("/public/v1/submit/update_root_quorum",ro),this.stampUpdateRootQuorum=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_root_quorum",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updateUser=async ro=>this.request("/public/v1/submit/update_user",ro),this.stampUpdateUser=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_user",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updateUserTag=async ro=>this.request("/public/v1/submit/update_user_tag",ro),this.stampUpdateUserTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_user_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},!eo.baseUrl)throw new Error("Missing base URL. Please verify env vars.");this.config=eo,this.stamper=to}async request(eo,to){const ro=this.config.baseUrl+eo,no=JSON.stringify(to),io=await this.stamper.stamp(no),oo=await fetch$2(ro,{method:"POST",headers:{[io.stampHeaderName]:io.stampHeaderValue,"X-Client-Version":VERSION$3},body:no,redirect:"follow"});if(!oo.ok){let so;try{so=await oo.json()}catch{throw new Error(`${oo.status} ${oo.statusText}`)}throw new TurnkeyRequestError(so)}return await oo.json()}}class TurnkeyActivityError extends Error{constructor(eo){const{message:to,cause:ro,activityId:no,activityStatus:io,activityType:oo}=eo;super(to),this.name="TurnkeyActivityError",this.activityId=no??null,this.activityStatus=io??null,this.activityType=oo??null,this.cause=ro??null}}function bufferToBase64url(Xr){const eo=new Uint8Array(Xr);let to="";for(const io of eo)to+=String.fromCharCode(io);return btoa(to).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}const copyValue="copy",convertValue="convert";function convert$1(Xr,eo,to){if(eo===copyValue)return to;if(eo===convertValue)return Xr(to);if(eo instanceof Array)return to.map(ro=>convert$1(Xr,eo[0],ro));if(eo instanceof Object){const ro={};for(const[no,io]of Object.entries(eo)){if(io.derive){const oo=io.derive(to);oo!==void 0&&(to[no]=oo)}if(!(no in to)){if(io.required)throw new Error(`Missing key: ${no}`);continue}if(to[no]==null){ro[no]=null;continue}ro[no]=convert$1(Xr,io.schema,to[no])}return ro}}function derived(Xr,eo){return{required:!0,schema:Xr,derive:eo}}function required(Xr){return{required:!0,schema:Xr}}function optional$3(Xr){return{required:!1,schema:Xr}}const simplifiedClientExtensionResultsSchema={appid:optional$3(copyValue),appidExclude:optional$3(copyValue),credProps:optional$3(copyValue)},publicKeyCredentialWithAssertion={type:required(copyValue),id:required(copyValue),rawId:required(convertValue),authenticatorAttachment:optional$3(copyValue),response:required({clientDataJSON:required(convertValue),authenticatorData:required(convertValue),signature:required(convertValue),userHandle:required(convertValue)}),clientExtensionResults:derived(simplifiedClientExtensionResultsSchema,Xr=>Xr.getClientExtensionResults())};function getResponseToJSON(Xr){return convert$1(bufferToBase64url,publicKeyCredentialWithAssertion,Xr)}async function get$3(Xr){const eo=await navigator.credentials.get(Xr);return eo.toJSON=()=>getResponseToJSON(eo),eo}const K$4=[1116352408,1899447441,-1245643825,-373957723,961987163,1508970993,-1841331548,-1424204075,-670586216,310598401,607225278,1426881987,1925078388,-2132889090,-1680079193,-1046744716,-459576895,-272742522,264347078,604807628,770255983,1249150122,1555081692,1996064986,-1740746414,-1473132947,-1341970488,-1084653625,-958395405,-710438585,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,-2117940946,-1838011259,-1564481375,-1474664885,-1035236496,-949202525,-778901479,-694614492,-200395387,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,-2067236844,-1933114872,-1866530822,-1538233109,-1090935817,-965641998];function createHash(Xr){return new Hash$1}let Hash$1=class{constructor(){this.A=1779033703,this.B=-1150833019,this.C=1013904242,this.D=-1521486534,this.E=1359893119,this.F=-1694144372,this.G=528734635,this.H=1541459225,this._size=0,this._sp=0,(!sharedBuffer||sharedOffset>=8e3)&&(sharedBuffer=new ArrayBuffer(8e3),sharedOffset=0),this._byte=new Uint8Array(sharedBuffer,sharedOffset,80),this._word=new Int32Array(sharedBuffer,sharedOffset,20),sharedOffset+=80}update(eo){if(typeof eo=="string")return this._utf8(eo);if(eo==null)throw new TypeError("Invalid type: "+typeof eo);const to=eo.byteOffset,ro=eo.byteLength;let no=ro/64|0,io=0;if(no&&!(to&3)&&!(this._size%64)){const ao=new Int32Array(eo.buffer,to,no*16);for(;no--;)this._int32(ao,io>>2),io+=64;this._size+=io}if(eo.BYTES_PER_ELEMENT!==1&&eo.buffer){const ao=new Uint8Array(eo.buffer,to+io,ro-io);return this._uint8(ao)}return io===ro?this:this._uint8(eo,io)}_uint8(eo,to){const{_byte:ro,_word:no}=this,io=eo.length;for(to=to|0;to=64&&this._int32(no),this._size+=ao-oo}return this}_utf8(eo){const{_byte:to,_word:ro}=this,no=eo.length;let io=this._sp;for(let oo=0;oo>>6,to[so++]=128|co&63):co<55296||co>57343?(to[so++]=224|co>>>12,to[so++]=128|co>>>6&63,to[so++]=128|co&63):io?(co=((io&1023)<<10)+(co&1023)+65536,to[so++]=240|co>>>18,to[so++]=128|co>>>12&63,to[so++]=128|co>>>6&63,to[so++]=128|co&63,io=0):io=co}so>=64&&(this._int32(ro),ro[0]=ro[16]),this._size+=so-ao}return this._sp=io,this}_int32(eo,to){let{A:ro,B:no,C:io,D:oo,E:ao,F:so,G:co,H:lo}=this,fo=0;for(to=to|0;fo<16;)W$5[fo++]=swap32(eo[to++]);for(fo=16;fo<64;fo++)W$5[fo]=gamma1(W$5[fo-2])+W$5[fo-7]+gamma0(W$5[fo-15])+W$5[fo-16]|0;for(fo=0;fo<64;fo++){const ho=lo+sigma1(ao)+ch(ao,so,co)+K$4[fo]+W$5[fo]|0,go=sigma0(ro)+maj(ro,no,io)|0;lo=co,co=so,so=ao,ao=oo+ho|0,oo=io,io=no,no=ro,ro=ho+go|0}this.A=ro+this.A|0,this.B=no+this.B|0,this.C=io+this.C|0,this.D=oo+this.D|0,this.E=ao+this.E|0,this.F=so+this.F|0,this.G=co+this.G|0,this.H=lo+this.H|0}digest(eo){const{_byte:to,_word:ro}=this;let no=this._size%64|0;for(to[no++]=128;no&3;)to[no++]=0;if(no>>=2,no>14){for(;no<16;)ro[no++]=0;no=0,this._int32(ro)}for(;no<16;)ro[no++]=0;const io=this._size*8,oo=(io&4294967295)>>>0,ao=(io-oo)/4294967296;return ao&&(ro[14]=swap32(ao)),oo&&(ro[15]=swap32(oo)),this._int32(ro),eo==="hex"?this._hex():this._bin()}_hex(){const{A:eo,B:to,C:ro,D:no,E:io,F:oo,G:ao,H:so}=this;return hex32(eo)+hex32(to)+hex32(ro)+hex32(no)+hex32(io)+hex32(oo)+hex32(ao)+hex32(so)}_bin(){const{A:eo,B:to,C:ro,D:no,E:io,F:oo,G:ao,H:so,_byte:co,_word:lo}=this;return lo[0]=swap32(eo),lo[1]=swap32(to),lo[2]=swap32(ro),lo[3]=swap32(no),lo[4]=swap32(io),lo[5]=swap32(oo),lo[6]=swap32(ao),lo[7]=swap32(so),co.slice(0,32)}};const W$5=new Int32Array(64);let sharedBuffer,sharedOffset=0;const hex32=Xr=>(Xr+4294967296).toString(16).substr(-8),swapLE=Xr=>Xr<<24&4278190080|Xr<<8&16711680|Xr>>8&65280|Xr>>24&255,swapBE=Xr=>Xr,swap32=isBE()?swapBE:swapLE,ch=(Xr,eo,to)=>to^Xr&(eo^to),maj=(Xr,eo,to)=>Xr&eo|to&(Xr|eo),sigma0=Xr=>(Xr>>>2|Xr<<30)^(Xr>>>13|Xr<<19)^(Xr>>>22|Xr<<10),sigma1=Xr=>(Xr>>>6|Xr<<26)^(Xr>>>11|Xr<<21)^(Xr>>>25|Xr<<7),gamma0=Xr=>(Xr>>>7|Xr<<25)^(Xr>>>18|Xr<<14)^Xr>>>3,gamma1=Xr=>(Xr>>>17|Xr<<15)^(Xr>>>19|Xr<<13)^Xr>>>10;function isBE(){return new Uint8Array(new Uint16Array([65279]).buffer)[0]===254}const stampHeaderName="X-Stamp-Webauthn",defaultTimeout=5*60*1e3,defaultUserVerification="preferred";class WebauthnStamper{constructor(eo){this.rpId=eo.rpId,this.timeout=eo.timeout||defaultTimeout,this.userVerification=eo.userVerification||defaultUserVerification,this.allowCredentials=eo.allowCredentials||[]}async stamp(eo){const to=getChallengeFromPayload(eo),ro={publicKey:{rpId:this.rpId,challenge:to,allowCredentials:this.allowCredentials,timeout:this.timeout,userVerification:this.userVerification}},io=(await get$3(ro)).toJSON(),oo={authenticatorData:io.response.authenticatorData,clientDataJson:io.response.clientDataJSON,credentialId:io.id,signature:io.response.signature};return{stampHeaderName,stampHeaderValue:JSON.stringify(oo)}}}function getChallengeFromPayload(Xr){const eo=createHash().update(Xr).digest("hex");return new TextEncoder().encode(eo)}var version$e="3.4.4";class WebauthnNotSupportedError extends Error{constructor(){super("Webauthn is not supported on this device")}}function __awaiter$d(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;function utf8StringToBuffer(Xr){return new TextEncoder().encode(Xr)}function bufferToBase64URLString(Xr){const eo=new Uint8Array(Xr);let to="";for(const no of eo)to+=String.fromCharCode(no);return btoa(to).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function base64URLStringToBuffer(Xr){const eo=Xr.replace(/-/g,"+").replace(/_/g,"/"),to=(4-eo.length%4)%4,ro=eo.padEnd(eo.length+to,"="),no=atob(ro),io=new ArrayBuffer(no.length),oo=new Uint8Array(io);for(let ao=0;aooo.type==="public-key").length===0?new WebAuthnError({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:Xr}):new WebAuthnError({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:Xr});if(Xr.name==="SecurityError"){const io=window.location.hostname;if(isValidDomain(io)){if(to.rp.id!==io)return new WebAuthnError({message:`The RP ID "${to.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:Xr})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:Xr})}else if(Xr.name==="TypeError"){if(to.user.id.byteLength<1||to.user.id.byteLength>64)return new WebAuthnError({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:Xr})}else if(Xr.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:Xr})}return Xr}class BaseWebAuthnAbortService{createNewAbortSignal(){if(this.controller){const to=new Error("Cancelling existing WebAuthn API call for new one");to.name="AbortError",this.controller.abort(to)}const eo=new AbortController;return this.controller=eo,eo.signal}cancelCeremony(){if(this.controller){const eo=new Error("Manually cancelling existing WebAuthn API call");eo.name="AbortError",this.controller.abort(eo),this.controller=void 0}}}const WebAuthnAbortService=new BaseWebAuthnAbortService,attachments=["cross-platform","platform"];function toAuthenticatorAttachment(Xr){if(Xr&&!(attachments.indexOf(Xr)<0))return Xr}async function startRegistration(Xr){var ho;if(!browserSupportsWebAuthn())throw new Error("WebAuthn is not supported in this browser");const to={publicKey:{...Xr,challenge:base64URLStringToBuffer(Xr.challenge),user:{...Xr.user,id:utf8StringToBuffer(Xr.user.id)},excludeCredentials:(ho=Xr.excludeCredentials)==null?void 0:ho.map(toPublicKeyCredentialDescriptor)}};to.signal=WebAuthnAbortService.createNewAbortSignal();let ro;try{ro=await navigator.credentials.create(to)}catch(go){throw identifyRegistrationError({error:go,options:to})}if(!ro)throw new Error("Registration was not completed");const{id:no,rawId:io,response:oo,type:ao}=ro;let so;typeof oo.getTransports=="function"&&(so=oo.getTransports());let co;if(typeof oo.getPublicKeyAlgorithm=="function")try{co=oo.getPublicKeyAlgorithm()}catch(go){warnOnBrokenImplementation("getPublicKeyAlgorithm()",go)}let lo;if(typeof oo.getPublicKey=="function")try{const go=oo.getPublicKey();go!==null&&(lo=bufferToBase64URLString(go))}catch(go){warnOnBrokenImplementation("getPublicKey()",go)}let fo;if(typeof oo.getAuthenticatorData=="function")try{fo=bufferToBase64URLString(oo.getAuthenticatorData())}catch(go){warnOnBrokenImplementation("getAuthenticatorData()",go)}return{id:no,rawId:bufferToBase64URLString(io),response:{attestationObject:bufferToBase64URLString(oo.attestationObject),clientDataJSON:bufferToBase64URLString(oo.clientDataJSON),transports:so,publicKeyAlgorithm:co,publicKey:lo,authenticatorData:fo},type:ao,clientExtensionResults:ro.getClientExtensionResults(),authenticatorAttachment:toAuthenticatorAttachment(ro.authenticatorAttachment)}}function warnOnBrokenImplementation(Xr,eo){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${Xr}. You should report this error to them. +*********************`),ao=io.hashForSignature(Xr,co,oo)}return{script:co,sighashType:oo,hash:ao}}function getAllTaprootHashesForSig(Xr,eo,to,ro){const no=[];if(eo.tapInternalKey){const oo=getPrevoutTaprootKey(Xr,eo,ro);oo&&no.push(oo)}if(eo.tapScriptSig){const oo=eo.tapScriptSig.map(ao=>ao.pubkey);no.push(...oo)}return no.map(oo=>getTaprootHashesForSig(Xr,eo,to,oo,ro)).flat()}function getPrevoutTaprootKey(Xr,eo,to){const{script:ro}=getScriptAndAmountFromUtxo(Xr,eo,to);return(0,psbtutils_1.isP2TR)(ro)?ro.subarray(2,34):null}function trimTaprootSig(Xr){return Xr.length===64?Xr:Xr.subarray(0,64)}function getTaprootHashesForSig(Xr,eo,to,ro,no,io,oo){const ao=no.__TX,so=eo.sighashType||transaction_1.Transaction.SIGHASH_DEFAULT;checkSighashTypeAllowed(so,oo);const co=to.map((yo,vo)=>getScriptAndAmountFromUtxo(vo,yo,no)),lo=co.map(yo=>yo.script),fo=co.map(yo=>yo.value),ho=[];if(eo.tapInternalKey&&!io){const yo=getPrevoutTaprootKey(Xr,eo,no)||Buffer$3.from([]);if((0,bip371_1.toXOnly)(ro).equals(yo)){const vo=ao.hashForWitnessV1(Xr,lo,fo,so);ho.push({pubkey:ro,hash:vo})}}const go=(eo.tapLeafScript||[]).filter(yo=>(0,psbtutils_1.pubkeyInScript)(ro,yo.script)).map(yo=>{const vo=(0,bip341_1.tapleafHash)({output:yo.script,version:yo.leafVersion});return Object.assign({hash:vo},yo)}).filter(yo=>!io||io.equals(yo.hash)).map(yo=>{const vo=ao.hashForWitnessV1(Xr,lo,fo,transaction_1.Transaction.SIGHASH_DEFAULT,yo.hash);return{pubkey:ro,hash:vo,leafHash:yo.hash}});return ho.concat(go)}function checkSighashTypeAllowed(Xr,eo){if(eo&&eo.indexOf(Xr)<0){const to=sighashTypeToString(Xr);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${to}`)}}function getPayment(Xr,eo,to){let ro;switch(eo){case"multisig":const no=getSortedSigs(Xr,to);ro=payments.p2ms({output:Xr,signatures:no});break;case"pubkey":ro=payments.p2pk({output:Xr,signature:to[0].signature});break;case"pubkeyhash":ro=payments.p2pkh({output:Xr,pubkey:to[0].pubkey,signature:to[0].signature});break;case"witnesspubkeyhash":ro=payments.p2wpkh({output:Xr,pubkey:to[0].pubkey,signature:to[0].signature});break}return ro}function getScriptFromInput(Xr,eo,to){const ro=to.__TX,no={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(no.isP2SH=!!eo.redeemScript,no.isP2WSH=!!eo.witnessScript,eo.witnessScript)no.script=eo.witnessScript;else if(eo.redeemScript)no.script=eo.redeemScript;else if(eo.nonWitnessUtxo){const io=nonWitnessUtxoTxFromCache(to,eo,Xr),oo=ro.ins[Xr].index;no.script=io.outs[oo].script}else eo.witnessUtxo&&(no.script=eo.witnessUtxo.script);return(eo.witnessScript||(0,psbtutils_1.isP2WPKH)(no.script))&&(no.isSegwit=!0),no}function getSignersFromHD(Xr,eo,to){const ro=(0,utils_1$2.checkForInput)(eo,Xr);if(!ro.bip32Derivation||ro.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const no=ro.bip32Derivation.map(oo=>{if(oo.masterFingerprint.equals(to.fingerprint))return oo}).filter(oo=>!!oo);if(no.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return no.map(oo=>{const ao=to.derivePath(oo.path);if(!oo.pubkey.equals(ao.publicKey))throw new Error("pubkey did not match bip32Derivation");return ao})}function getSortedSigs(Xr,eo){return payments.p2ms({output:Xr}).pubkeys.map(ro=>(eo.filter(no=>no.pubkey.equals(ro))[0]||{}).signature).filter(ro=>!!ro)}function scriptWitnessToWitnessStack(Xr){let eo=0;function to(oo){return eo+=oo,Xr.slice(eo-oo,eo)}function ro(){const oo=varuint.decode(Xr,eo);return eo+=varuint.decode.bytes,oo}function no(){return to(ro())}function io(){const oo=ro(),ao=[];for(let so=0;so{if(ro&&so.finalScriptSig&&(eo.ins[co].script=so.finalScriptSig),ro&&so.finalScriptWitness&&(eo.ins[co].witness=scriptWitnessToWitnessStack(so.finalScriptWitness)),so.witnessUtxo)no+=so.witnessUtxo.value;else if(so.nonWitnessUtxo){const lo=nonWitnessUtxoTxFromCache(to,so,co),fo=eo.ins[co].index,ho=lo.outs[fo];no+=ho.value}});const io=eo.outs.reduce((so,co)=>so+co.value,0),oo=no-io;if(oo<0)throw new Error("Outputs are spending more than Inputs");const ao=eo.virtualSize();to.__FEE=oo,to.__EXTRACTED_TX=eo,to.__FEE_RATE=Math.floor(oo/ao)}function nonWitnessUtxoTxFromCache(Xr,eo,to){const ro=Xr.__NON_WITNESS_UTXO_TX_CACHE;return ro[to]||addNonWitnessTxCache(Xr,eo,to),ro[to]}function getScriptFromUtxo(Xr,eo,to){const{script:ro}=getScriptAndAmountFromUtxo(Xr,eo,to);return ro}function getScriptAndAmountFromUtxo(Xr,eo,to){if(eo.witnessUtxo!==void 0)return{script:eo.witnessUtxo.script,value:eo.witnessUtxo.value};if(eo.nonWitnessUtxo!==void 0){const no=nonWitnessUtxoTxFromCache(to,eo,Xr).outs[to.__TX.ins[Xr].index];return{script:no.script,value:no.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function pubkeyInInput(Xr,eo,to,ro){const no=getScriptFromUtxo(to,eo,ro),{meaningfulScript:io}=getMeaningfulScript(no,to,"input",eo.redeemScript,eo.witnessScript);return(0,psbtutils_1.pubkeyInScript)(Xr,io)}function pubkeyInOutput(Xr,eo,to,ro){const no=ro.__TX.outs[to].script,{meaningfulScript:io}=getMeaningfulScript(no,to,"output",eo.redeemScript,eo.witnessScript);return(0,psbtutils_1.pubkeyInScript)(Xr,io)}function redeemFromFinalScriptSig(Xr){if(!Xr)return;const eo=bscript.decompile(Xr);if(!eo)return;const to=eo[eo.length-1];if(!(!Buffer$3.isBuffer(to)||isPubkeyLike(to)||isSigLike(to)||!bscript.decompile(to)))return to}function redeemFromFinalWitnessScript(Xr){if(!Xr)return;const eo=scriptWitnessToWitnessStack(Xr),to=eo[eo.length-1];if(!(isPubkeyLike(to)||!bscript.decompile(to)))return to}function compressPubkey(Xr){if(Xr.length===65){const eo=Xr[64]&1,to=Xr.slice(0,33);return to[0]=2|eo,to}return Xr.slice()}function isPubkeyLike(Xr){return Xr.length===33&&bscript.isCanonicalPubKey(Xr)}function isSigLike(Xr){return bscript.isCanonicalScriptSignature(Xr)}function getMeaningfulScript(Xr,eo,to,ro,no){const io=(0,psbtutils_1.isP2SHScript)(Xr),oo=io&&ro&&(0,psbtutils_1.isP2WSHScript)(ro),ao=(0,psbtutils_1.isP2WSHScript)(Xr);if(io&&ro===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((ao||oo)&&no===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let so;return oo?(so=no,checkRedeemScript(eo,Xr,ro,to),checkWitnessScript(eo,ro,no,to),checkInvalidP2WSH(so)):ao?(so=no,checkWitnessScript(eo,Xr,no,to),checkInvalidP2WSH(so)):io?(so=ro,checkRedeemScript(eo,Xr,ro,to)):so=Xr,{meaningfulScript:so,type:oo?"p2sh-p2wsh":io?"p2sh":ao?"p2wsh":"raw"}}function checkInvalidP2WSH(Xr){if((0,psbtutils_1.isP2WPKH)(Xr)||(0,psbtutils_1.isP2SHScript)(Xr))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function classifyScript(Xr){return(0,psbtutils_1.isP2WPKH)(Xr)?"witnesspubkeyhash":(0,psbtutils_1.isP2PKH)(Xr)?"pubkeyhash":(0,psbtutils_1.isP2MS)(Xr)?"multisig":(0,psbtutils_1.isP2PK)(Xr)?"pubkey":"nonstandard"}function range$1(Xr){return[...Array(Xr).keys()]}(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.initEccLib=Xr.Transaction=Xr.opcodes=Xr.Psbt=Xr.Block=Xr.script=Xr.payments=Xr.networks=Xr.crypto=Xr.address=void 0;const eo=address;Xr.address=eo;const to=crypto$3;Xr.crypto=to;const ro=networks$1;Xr.networks=ro;const no=payments$3;Xr.payments=no;const io=script$1;Xr.script=io;var oo=block;Object.defineProperty(Xr,"Block",{enumerable:!0,get:function(){return oo.Block}});var ao=psbt$1;Object.defineProperty(Xr,"Psbt",{enumerable:!0,get:function(){return ao.Psbt}});var so=ops;Object.defineProperty(Xr,"opcodes",{enumerable:!0,get:function(){return so.OPS}});var co=transaction;Object.defineProperty(Xr,"Transaction",{enumerable:!0,get:function(){return co.Transaction}});var lo=ecc_lib;Object.defineProperty(Xr,"initEccLib",{enumerable:!0,get:function(){return lo.initEccLib}})})(src$3);const extractAddressFromInput=(Xr,eo,to)=>{var ro;let no;if(!((ro=to.witnessUtxo)===null||ro===void 0)&&ro.script?no=to.witnessUtxo.script:to.nonWitnessUtxo&&(no=src$3.Transaction.fromBuffer(to.nonWitnessUtxo).outs[Xr.txInputs[eo].index].script),!!no)try{return src$3.address.fromOutputScript(no)}catch{throw new Error("address not found in output script")}},validateAddress=(Xr,eo,to,ro)=>{const no=extractAddressFromInput(Xr,to,ro);if(!no)throw new DynamicError(`validateAddress - input not found for the given address: ${eo}`);if(no!==eo)throw new DynamicError("validateAddress - address mismatch with index")},getSigHashType=Xr=>{var eo;if(Xr!=null&&Xr.sighashType)return Xr.sighashType;let to=!1;if(!((eo=Xr.witnessUtxo)===null||eo===void 0)&&eo.script)try{src$3.payments.p2tr({output:Xr.witnessUtxo.script}),to=!0}catch{logger$9.debug("address is not taproot")}return to?src$3.Transaction.SIGHASH_DEFAULT:src$3.Transaction.SIGHASH_ALL},validateSigHash=(Xr,eo)=>{const to=getSigHashType(eo);if(Xr!=null&&Xr.length&&!Xr.includes(to))throw new Error(`validatePsbt - sigHashType ${to} not in allowed list`)},validatePsbt=(Xr,eo,to)=>{if(to!=null&&to.length)for(const ro of to){const{address:no,signingIndexes:io,disableAddressValidation:oo=!0}=ro;if(!(io!=null&&io.length))return;if(!no)throw new Error("validatePsbt - address not provided");for(const ao of io){const so=Xr.data.inputs[ao];if(!so)throw new Error("validatePsbt - requested input not found");oo||validateAddress(Xr,no,ao,so),validateSigHash(eo,so)}}},convertNetworkTypeForPsbt=Xr=>({[BitcoinNetworkType.Mainnet]:src$3.networks.bitcoin,[BitcoinNetworkType.Testnet]:src$3.networks.testnet,[BitcoinNetworkType.Signet]:void 0})[Xr];class BitcoinBtcKitConnector extends BitcoinWalletConnector{constructor(eo,to){super(eo),this.currentNetwork=BitcoinNetworkType.Mainnet,this.btcKit=to}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const[to]=yield this.getConnectedAccounts();if(to)return to;const ro=yield this.btcKit.request("getAddresses",{types:["p2tr","p2wpkh"]});if(!("result"in ro)){logger$9.error("Fetch public address error",ro);return}const{addresses:no}=ro.result,io=no==null?void 0:no.find(so=>so.type==="p2tr"),oo=no==null?void 0:no.find(so=>so.type==="p2wpkh"),ao=(eo=io==null?void 0:io.address)!==null&&eo!==void 0?eo:oo==null?void 0:oo.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:ao,ordinalsAddress:io,paymentAddress:oo}),ao})}signMessage(eo){return __awaiter$i(this,void 0,void 0,function*(){if(!(yield this.getConnectedAccounts()).length)return;const to=yield this.btcKit.request("signMessage",{message:eo,paymentType:"p2tr"}).catch(({error:no})=>{throw no});if(!("result"in to))throw logger$9.error("Signature error",to),new Error("Failed to sign message");const{signature:ro}=to.result;return this.isHardwareWalletEnabled?JSON.stringify({signedTransaction:{data:ro}}):ro})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){if(!(yield this.getAddress())||!this.btcKit)return;const ro=yield this.btcKit.request("sendTransfer",{address:eo.recipientAddress,amount:eo.amount.toString(),network:this.convertNetworkTypeToNetworkMode()});if(!("result"in ro))throw logger$9.error("Transaction error",ro),new Error("Failed to send transaction");return ro.result.txid})}convertNetworkTypeToNetworkMode(){return this.currentNetwork===BitcoinNetworkType.Mainnet?"mainnet":"testnet"}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){var to,ro;if(!(yield this.getAddress())||!this.btcKit)return;const io=convertNetworkTypeForPsbt(this.currentNetwork),oo=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64,{network:io});!((to=eo.signature)===null||to===void 0)&&to.length&&validatePsbt(oo,eo.allowedSighash,eo.signature);const ao={allowedSighash:eo.allowedSighash,hex:oo.toHex(),signAtIndex:(ro=eo.signature)===null||ro===void 0?void 0:ro.flatMap(lo=>lo.signingIndexes).filter(Number.isInteger)},so=yield this.btcKit.request("signPsbt",Object.assign({broadcast:!1,network:this.convertNetworkTypeToNetworkMode()},ao));if(!so||!("result"in so)||!("hex"in so.result))throw new Error("signPsbt - failed to sign PSBT");const co=so.result.hex;return{signedPsbt:src$3.Psbt.fromHex(co,{network:io}).toBase64()}})}}const fetchBtcKitConnectors=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).map(([to,ro])=>{var no,io;const oo=(no=ro.injectedConfig)===null||no===void 0?void 0:no.find(so=>so.chain==="btc"&&so.providerInterface===BTCKIT_INTERFACE);if(!(!((io=oo==null?void 0:oo.windowLocations)===null||io===void 0)&&io.length))return;const ao=getProvidersFromWindow(oo.windowLocations[0]);return class extends BitcoinBtcKitConnector{constructor(so){super(Object.assign(Object.assign({},so),{overrideKey:to,walletData:ro}),ao==null?void 0:ao[0]),this.name=ro.shortName||ro.name}}}).filter(to=>!!to)},createPsbtOptions=(Xr,eo)=>{var to;const ro={autoFinalized:!1};if(eo.signature){validatePsbt(Xr,eo.allowedSighash,eo.signature);const no=[];for(const io of eo.signature)if(!((to=io.signingIndexes)===null||to===void 0)&&to.length)for(const oo of io.signingIndexes)no.push({address:io.address,disableAddressValidation:io.disableAddressValidation,index:oo,sighashTypes:eo.allowedSighash});ro.toSignInputs=no}return ro},createSignPsbtOptionsForSatsConnect=(Xr,eo,to=!1)=>{var ro,no,io;!((ro=eo.signature)===null||ro===void 0)&&ro.length&&validatePsbt(Xr,eo.allowedSighash,eo.signature),logger$9.logVerboseTroubleshootingMessage("createSignPsbtOptionsForSatsConnect",{isLegacyConnector:to,psbtFromBase64:Xr,request:eo});const oo=((io=(no=eo.signature)===null||no===void 0?void 0:no.map(ao=>{var so;return((so=ao.signingIndexes)!==null&&so!==void 0?so:[]).map(co=>({address:ao.address,sigHash:to?getSigHashType(Xr.data.inputs[co]):eo.allowedSighash[0],signingIndexes:[co]}))}))!==null&&io!==void 0?io:[]).flat();return logger$9.logVerboseTroubleshootingMessage("createSignPsbtOptionsForSatsConnect",{inputsToSign:oo}),oo};class BitcoinSatsConnectConnector extends BitcoinWalletConnector{constructor(eo){var to,ro,no;super(eo),this.isLegacy=!1,this.currentNetwork=BitcoinNetworkType.Mainnet,!((ro=(to=eo.walletData)===null||to===void 0?void 0:to.injectedConfig)===null||ro===void 0)&&ro.length&&(this.providerId=(no=eo.walletData.injectedConfig[0].walletStandard)===null||no===void 0?void 0:no.providerId)}getGenericUserCancelledError(){const eo=new Error;return eo.code="-32000",eo}getAddresses(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const to=yield request("getAddresses",{purposes:[AddressPurpose.Payment,AddressPurpose.Ordinals]});if(to.status!=="success")throw to.error;const{addresses:ro}=to.result,no=ro==null?void 0:ro.find(ao=>ao.purpose===AddressPurpose.Ordinals),io=ro==null?void 0:ro.find(ao=>ao.purpose===AddressPurpose.Payment),oo=(eo=no==null?void 0:no.address)!==null&&eo!==void 0?eo:io==null?void 0:io.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:oo,ordinalsAddress:no,paymentAddress:io}),oo})}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const to=findWalletBookWallet(this.walletBook,this.key),ro=(eo=to==null?void 0:to.mobile)===null||eo===void 0?void 0:eo.inAppBrowser;if(isMobile$1()&&!this.isInstalledOnBrowser()&&ro&&this.mobileExperience==="in-app-browser"){const io=template$1(ro)({encodedDappURI:encodeURIComponent(window.location.toString())});window.location.href=io;return}try{const no=yield request("wallet_requestPermissions",void 0);if(no.status!=="success")throw no.error;return yield this.getAddresses()}catch{throw this.getGenericUserCancelledError()}})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){try{const ro=yield request("signMessage",{address:to,message:eo});if(ro.status!=="success")throw ro.error;return this.isHardwareWalletEnabled?JSON.stringify({signedTransaction:{data:ro.result.signature}}):ro.result.signature}catch{throw this.getGenericUserCancelledError()}})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){try{const to=yield request("sendTransfer",{recipients:[{address:eo.recipientAddress,amount:Number(eo.amount)}]});if(to.status!=="success")throw to.error;return to.result.txid}catch{throw this.getGenericUserCancelledError()}})}signTransaction(eo){return __awaiter$i(this,void 0,void 0,function*(){const{allowedSignHash:to,psbtBase64:ro,broadcast:no,inputsToSign:io}=eo,oo={allowedSignHash:to,broadcast:no,psbt:ro,signInputs:io.reduce((ao,so)=>(ao[so.address]||(ao[so.address]=[]),ao[so.address].push(...so.signingIndexes),ao),{})};logger$9.logVerboseTroubleshootingMessage("[BitcoinSatsConnectConnector] signTransaction",{signPbstPayload:oo});try{const ao=yield request("signPsbt",oo);if(ao.status!=="success")throw ao.error;return{psbtBase64:ao.result.psbt,txId:ao.result.txid}}catch{throw this.getGenericUserCancelledError()}})}signTransactions(eo){return __awaiter$i(this,void 0,void 0,function*(){const{message:to,psbts:ro,network:no}=eo;return logger$9.logVerboseTroubleshootingMessage("[BitcoinSatsConnectConnector] signTransactions",{transactions:eo}),new Promise((io,oo)=>{signMultipleTransactions({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var ao,so;return(so=(ao=this.wallet)===null||ao===void 0?void 0:ao.features[SATSCONNECT_FEATURE])===null||so===void 0?void 0:so.provider}),onCancel:()=>{const ao=this.getGenericUserCancelledError();oo(ao)},onFinish:ao=>{io(ao)},payload:{message:to||"Sign Transaction",network:no,psbts:ro}})})})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){var to;if(!(!((to=eo.allowedSighash)===null||to===void 0)&&to.length))throw new Error("allowedSighash cannot be an empty array");const ro=convertNetworkTypeForPsbt(this.currentNetwork),no=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64,{network:ro});logger$9.logVerboseTroubleshootingMessage("signPsbt",{isLegacy:this.isLegacy,psbtFromBase64:no,request:eo});const io=yield this.signTransaction({allowedSignHash:eo.allowedSighash[0],broadcast:!1,inputsToSign:createSignPsbtOptionsForSatsConnect(no,eo,this.isLegacy),psbtBase64:eo.unsignedPsbtBase64});if(!io)throw new Error("Failed to sign transaction with sats-connect");return{signedPsbt:io.psbtBase64}})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){var to;const ro=convertNetworkTypeForPsbt(this.currentNetwork),no={message:"Sign Transaction",network:{type:this.currentNetwork},psbts:[]};for(const oo of eo){const ao=src$3.Psbt.fromBase64(oo.unsignedPsbtBase64,{network:ro}),so=createSignPsbtOptionsForSatsConnect(ao,oo,this.isLegacy);no.psbts.push({inputsToSign:so,psbtBase64:oo.unsignedPsbtBase64})}logger$9.logVerboseTroubleshootingMessage("signPsbts",no);const io=yield this.signTransactions(no);return(to=io==null?void 0:io.map(oo=>oo.psbtBase64))!==null&&to!==void 0?to:[]})}validateActiveWallet(eo){return __awaiter$i(this,void 0,void 0,function*(){logger$9.debug("validateActiveWallet - skipping validation for xverse",{expectedAddress:eo})})}handleXverseAccountChange(){return __awaiter$i(this,void 0,void 0,function*(){const{handleAccountChange:eo}=eventListenerHandlers(this),to=yield this.getAddresses();if(!to)return;eo([to])})}setupEventListeners(){if(this.key!=="xverse"){super.setupEventListeners();return}try{const eo=addListener("accountChange",this.handleXverseAccountChange.bind(this));this.teardownEventListeners=()=>{logger$9.debug("[BitcoinSatsConnectConnector] teardownEventListeners"),eo()}}catch(eo){logger$9.debug("[BitcoinSatsConnectConnector] setupEventListeners",{connector:this.key,error:eo})}}}const hasSatsConnectFeature=Xr=>SATSCONNECT_FEATURE in Xr,supportsSatsConnect=Xr=>{var eo,to,ro,no;if(Xr.key===XVERSE_KEY)return!0;const io=(ro=(to=(eo=findWalletBookWallet(Xr.walletBook,Xr.key))===null||eo===void 0?void 0:eo.injectedConfig)===null||to===void 0?void 0:to.find(oo=>oo.chain==="btc"))===null||ro===void 0?void 0:ro.walletStandard;return!!(Xr.wallet&&hasSatsConnectFeature(Xr.wallet.features)||!((no=io==null?void 0:io.features)===null||no===void 0)&&no.includes(SATSCONNECT_FEATURE))};class BitcoinSatsConnectLegacyConnector extends BitcoinSatsConnectConnector{constructor(){super(...arguments),this.isLegacy=!0}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;if(!supportsSatsConnect(this))return;const to=findWalletBookWallet(this.walletBook,this.key),ro=(eo=to==null?void 0:to.mobile)===null||eo===void 0?void 0:eo.inAppBrowser;if(isMobile$1()&&!this.isInstalledOnBrowser()&&ro&&this.mobileExperience==="in-app-browser"){const io=template$1(ro)({encodedDappURI:encodeURIComponent(window.location.toString())});window.location.href=io;return}return new Promise((no,io)=>{getAddress({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var oo,ao;return(ao=(oo=this.wallet)===null||oo===void 0?void 0:oo.features[SATSCONNECT_FEATURE])===null||ao===void 0?void 0:ao.provider}),onCancel:()=>{const oo=new Error;oo.code="-32000",io(oo)},onFinish:oo=>__awaiter$i(this,void 0,void 0,function*(){var ao;const{addresses:so}=oo,co=so==null?void 0:so.find(ho=>ho.purpose===AddressPurpose.Ordinals),lo=so==null?void 0:so.find(ho=>ho.purpose===AddressPurpose.Payment),fo=(ao=co==null?void 0:co.address)!==null&&ao!==void 0?ao:lo==null?void 0:lo.address;yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:fo,ordinalsAddress:co,paymentAddress:lo}),no(fo)}),payload:{message:"Address for receiving Ordinals and payments",network:{type:this.currentNetwork},purposes:[AddressPurpose.Ordinals,AddressPurpose.Payment]}})})})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){if(supportsSatsConnect(this))return new Promise((ro,no)=>{signMessage$1({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var io,oo;return(oo=(io=this.wallet)===null||io===void 0?void 0:io.features[SATSCONNECT_FEATURE])===null||oo===void 0?void 0:oo.provider}),onCancel:()=>{const io=new Error;io.code="-32000",no(io)},onFinish:io=>__awaiter$i(this,void 0,void 0,function*(){if(this.isHardwareWalletEnabled)return ro(JSON.stringify({signedTransaction:{data:io}}));ro(io)}),payload:{address:to,message:eo,network:{type:this.currentNetwork}}})})})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){var to;const ro=yield this.getAddress(),no=(to=(yield this.getAdditionalAddresses(ro)).find(io=>io.type==="payment"))===null||to===void 0?void 0:to.address;if(!(!no||!supportsSatsConnect(this)))return new Promise((io,oo)=>{sendBtcTransaction({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var ao,so;return(so=(ao=this.wallet)===null||ao===void 0?void 0:ao.features[SATSCONNECT_FEATURE])===null||so===void 0?void 0:so.provider}),onCancel:()=>{const ao=new Error;ao.code="-32000",oo(ao)},onFinish:ao=>{io(ao)},payload:{network:{type:this.currentNetwork},recipients:[{address:eo.recipientAddress,amountSats:BigInt(eo.amount)}],senderAddress:no}})})})}signTransaction(eo){return __awaiter$i(this,void 0,void 0,function*(){const{message:to,psbtBase64:ro,broadcast:no,inputsToSign:io}=eo;return new Promise((oo,ao)=>{signTransaction$1({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var so,co;return(co=(so=this.wallet)===null||so===void 0?void 0:so.features[SATSCONNECT_FEATURE])===null||co===void 0?void 0:co.provider}),onCancel:()=>{const so=new Error;so.code="-32000",ao(so)},onFinish:so=>{oo(so)},payload:{broadcast:no,inputsToSign:io,message:to||"Sign Transaction",network:{type:this.currentNetwork},psbtBase64:ro}})})})}signTransactions(eo){return __awaiter$i(this,void 0,void 0,function*(){const{message:to,psbts:ro,network:no}=eo;return new Promise((io,oo)=>{signMultipleTransactions({getProvider:()=>__awaiter$i(this,void 0,void 0,function*(){var ao,so;return(so=(ao=this.wallet)===null||ao===void 0?void 0:ao.features[SATSCONNECT_FEATURE])===null||so===void 0?void 0:so.provider}),onCancel:()=>{const ao=new Error;ao.code="-32000",oo(ao)},onFinish:ao=>{io(ao)},payload:{message:to||"Sign Transaction",network:no,psbts:ro}})})})}}const fetchSatsConnectConnectors=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).filter(([to,ro])=>{var no;return(no=ro.injectedConfig)===null||no===void 0?void 0:no.find(io=>{var oo;return io.chain==="btc"&&!!(!((oo=io.walletStandard)===null||oo===void 0)&&oo.features.includes(SATSCONNECT_FEATURE))})}).map(([to,ro])=>{var no;const{shortName:io,injectedConfig:oo}=ro,ao=io||ro.name;return!((no=oo==null?void 0:oo[0].walletStandard)===null||no===void 0)&&no.providerId?class extends BitcoinSatsConnectConnector{constructor(so){super(Object.assign(Object.assign({},so),{overrideKey:to,walletData:ro})),this.name=ao}}:class extends BitcoinSatsConnectLegacyConnector{constructor(so){super(Object.assign(Object.assign({},so),{overrideKey:to,walletData:ro})),this.name=ao}}})},sighashNumberToString=Xr=>{switch(Xr){case src$3.Transaction.SIGHASH_ALL:return"ALL";case src$3.Transaction.SIGHASH_NONE:return"NONE";case src$3.Transaction.SIGHASH_SINGLE:return"SINGLE";case src$3.Transaction.SIGHASH_ALL+src$3.Transaction.SIGHASH_ANYONECANPAY:return"ALL|ANYONECANPAY";case src$3.Transaction.SIGHASH_NONE+src$3.Transaction.SIGHASH_ANYONECANPAY:return"NONE|ANYONECANPAY";case src$3.Transaction.SIGHASH_SINGLE+src$3.Transaction.SIGHASH_ANYONECANPAY:return"SINGLE|ANYONECANPAY";default:return}},decodeBase64=Xr=>Uint8Array.from(Buffer$3.from(Xr,"base64")),encodeBase64=Xr=>Buffer$3.from(Xr).toString("base64");class PhantomConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"phantombtc"})),this.name="Phantom"}connectWithInstalledExtension(){return __awaiter$i(this,void 0,void 0,function*(){var eo,to;let ro,no;if(!((eo=this.walletMethods)===null||eo===void 0)&&eo.connect){const{accounts:oo}=yield this.walletMethods.connect();[ro,no]=oo.map(so=>({address:so.address,publicKey:Buffer$3.from(so.publicKey).toString("hex")})),no||(no=ro)}else{const oo=this.getProvider();if(!oo)return;const ao=yield oo.requestAccounts();no=ao==null?void 0:ao.find(so=>so.purpose==="ordinals"),ro=ao==null?void 0:ao.find(so=>so.purpose==="payment")}const io=(to=no==null?void 0:no.address)!==null&&to!==void 0?to:ro==null?void 0:ro.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:io,ordinalsAddress:no,paymentAddress:ro}),io})}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){if(this.isInstalledOnBrowser())return this.connectWithInstalledExtension();isMobile$1()&&handleMobileWalletRedirect({nativeLink:"phantom://browse",universalLink:"https://phantom.app/ul/browse"})})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){var ro;if(!((ro=this.walletMethods)===null||ro===void 0)&&ro.signMessage){const[no]=yield this.walletMethods.signMessage({account:{address:to},message:new TextEncoder().encode(eo)});return Buffer$3.from(no.signature).toString("base64")}else{const no=this.getProvider();if(!no)return;const io=yield no.signMessage(to,new TextEncoder().encode(eo));return Buffer$3.from(io.signature).toString("base64")}})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){var to,ro,no,io,oo;const[ao]=yield this.getConnectedAccounts();if(!ao)return;const so=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),co=createPsbtOptions(so,eo);if(!((to=this.walletMethods)===null||to===void 0)&&to.signTransaction){const[lo]=yield this.walletMethods.signTransaction({inputsToSign:(no=(ro=co.toSignInputs)===null||ro===void 0?void 0:ro.map(fo=>({account:{address:fo.address},sigHash:fo.sighashTypes&&sighashNumberToString(fo.sighashTypes[0]),signingIndexes:[fo.index]})))!==null&&no!==void 0?no:[],psbt:decodeBase64(eo.unsignedPsbtBase64)});return{signedPsbt:Buffer$3.from(lo.signedPsbt).toString("base64")}}else{const lo=this.getProvider();if(!lo)return;const fo=(oo=(io=eo.signature)===null||io===void 0?void 0:io.map(go=>{var yo;return{address:go.address,sigHash:eo.allowedSighash[0],signingIndexes:(yo=go.signingIndexes)!==null&&yo!==void 0?yo:[]}}))!==null&&oo!==void 0?oo:[],ho=yield lo.signPSBT(decodeBase64(eo.unsignedPsbtBase64),{inputsToSign:fo});return{signedPsbt:encodeBase64(Uint8Array.from(ho))}}})}}class OkxConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"okxwalletbtc"})),this.name="OKX Wallet"}get walletBookWallet(){return this.walletBook.wallets[this.key]}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){if(!this.isInstalledOnBrowser()&&isMobile$1()&&this.walletBookWallet.mobile&&this.walletBookWallet.mobile.inAppBrowser&&this.mobileExperience==="in-app-browser"){const oo=template$1(this.walletBookWallet.mobile.inAppBrowser)({encodedDappURI:encodeURIComponent(window.location.toString())});window.location.assign(oo);return}const eo=this.getProvider();if(!eo)return;const{address:to,publicKey:ro}=yield eo.connect(),no={address:to,publicKey:ro};return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:to,ordinalsAddress:no}),to})}signMessage(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(to)return to.signMessage(eo,"bip322-simple")})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!(!(yield this.getAddress())||!to))return to.sendBitcoin(eo.recipientAddress,eo.amount.toString())})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),no=yield to.signPsbt(ro.toHex(),createPsbtOptions(ro,eo));return{signedPsbt:src$3.Psbt.fromHex(no).toBase64()}})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=[],no=[];for(const oo of eo){const ao=src$3.Psbt.fromBase64(oo.unsignedPsbtBase64);ro.push(ao.toHex()),no.push(createPsbtOptions(ao,oo))}return(yield to.signPsbts(ro,no)).map(oo=>src$3.Psbt.fromHex(oo).toBase64())})}}class OylConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"oylwallet"})),this.name="Oyl Wallet",this.overrideKey="oylwallet"}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){var eo;const to=this.getProvider();if(!to)return;const ro=yield to.getAddresses(),no=ro.taproot,io=ro.nativeSegwit,oo=(eo=no==null?void 0:no.address)!==null&&eo!==void 0?eo:io==null?void 0:io.address;return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:oo,ordinalsAddress:no,paymentAddress:io}),oo})}signMessage(eo,to){return __awaiter$i(this,void 0,void 0,function*(){const ro=this.getProvider();if(!ro)return;const{signature:no}=yield ro.signMessage({address:to,message:eo});return no})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),no=createPsbtOptions(ro,eo),{psbt:io}=yield to.signPsbt({broadcast:!1,finalize:no.autoFinalized,psbt:ro.toHex()});return{signedPsbt:src$3.Psbt.fromHex(io).toBase64()}})}}class UnisatConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"unisat"})),this.name="UniSat",this.overrideKey="unisat"}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){const eo=this.getProvider();if(!eo)return;const[to]=yield eo.requestAccounts(),ro=yield eo.getPublicKey(),no={address:to,publicKey:ro};return yield this.setConnectedAccountWithAddresses({active:!0,mainAddress:to,ordinalsAddress:no}),to})}signMessage(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(to)return to.signMessage(eo,"bip322-simple")})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!(!(yield this.getAddress())||!to))return to.sendBitcoin(eo.recipientAddress,Number(eo.amount))})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=src$3.Psbt.fromBase64(eo.unsignedPsbtBase64),no=yield to.signPsbt(ro.toHex(),createPsbtOptions(ro,eo));return{signedPsbt:src$3.Psbt.fromHex(no).toBase64()}})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){const to=this.getProvider();if(!to)return;const ro=[],no=[];for(const oo of eo){const ao=src$3.Psbt.fromBase64(oo.unsignedPsbtBase64);ro.push(ao.toHex()),no.push(createPsbtOptions(ao,oo))}return(yield to.signPsbts(ro,no)).map(oo=>src$3.Psbt.fromHex(oo).toBase64())})}getConnectedAccounts(){return __awaiter$i(this,void 0,void 0,function*(){const eo=this.getProvider();return eo?eo.getAccounts():[]})}}class UnknownInjectedConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"unknown"})),this.name="Unknown",this.overrideKey="unknown"}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){})}}class FallbackBitcoinConnector extends BitcoinWalletConnector{constructor(eo){super(Object.assign(Object.assign({},eo),{overrideKey:"fallbackconnector"})),this.name="Fallback Connector",this.overrideKey="fallbackconnector",this.isAvailable=!1}getAddress(){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbt(eo){return __awaiter$i(this,void 0,void 0,function*(){})}signPsbts(eo){return __awaiter$i(this,void 0,void 0,function*(){})}sendBitcoin(eo){return __awaiter$i(this,void 0,void 0,function*(){})}}assertPackageVersion("@dynamic-labs/bitcoin",version$j);const BitcoinWalletConnectors=Xr=>[...fetchSatsConnectConnectors(Xr),...fetchBtcKitConnectors(Xr),PhantomConnector,OkxConnector,OylConnector,UnisatConnector,UnknownInjectedConnector,FallbackBitcoinConnector];var version$h="3.4.4";function __awaiter$f(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;class CosmosWallet extends Wallet$1{getProvider(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this._connector.getProvider();if(!eo)throw new Error("unable to retrieve Cosmos provider");try{return cloneObjectWithOverrides(eo,{sendEthereumTx:(to,ro)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.sendEthereumTx(to,ro)}),sendTx:(to,ro,no)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.sendTx(to,ro,no)}),signAmino:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signAmino(to,ro,no,io)}),signArbitrary:(to,ro,no)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signArbitrary(to,ro,no)}),signDirect:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signDirect(to,ro,no,io)}),signDirectAux:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signDirectAux(to,ro,no,io)}),signEthereum:(to,ro,no,io)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signEthereum(to,ro,no,io)}),signICNSAdr36:(to,ro,no,io,oo)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signICNSAdr36(to,ro,no,io,oo)})})}catch(to){return logger$9.warn(`Failed to add logic to auto-sync the wallet. Provider might be out of sync for wallet: ${this._connector.name} (${this.address})`,to),eo}})}getOfflineSigner(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this._connector.getOfflineSigner();if(!eo)throw new Error("unable to retrieve Cosmos offline signer");try{return cloneObjectWithOverrides(eo,{signAmino:(to,ro)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signAmino(to,ro)}),signDirect:(to,ro)=>__awaiter$f(this,void 0,void 0,function*(){return yield this.sync(),eo.signDirect(to,ro)})})}catch(to){return logger$9.warn(`Failed to add logic to auto-sync the wallet. Signer might be out of sync for wallet: ${this._connector.name} (${this.address})`,to),eo}})}}class CosmosWalletConnector extends WalletConnectorBase{constructor(eo){super(eo),this.ChainWallet=CosmosWallet,this.connectedChain="COSMOS",this.supportedChains=["COSMOS"],this.evmNetworks=parseEvmNetworks(eo.cosmosNetworks),this.chainIdMapping=this.evmNetworks.map(to=>({cosmosNetworkId:to.name,dynamicChainId:parseChainId(to.networkId),evmNetwork:to}))}getSelectedNetwork(){const eo=this.chainIdMapping.find(to=>to.cosmosNetworkId===this.getChainId());return eo==null?void 0:eo.evmNetwork}getNetwork(){return __awaiter$f(this,void 0,void 0,function*(){var eo;return(eo=this.getSelectedNetwork())===null||eo===void 0?void 0:eo.chainId})}getLcdUrl(){var eo;return(eo=this.getSelectedNetwork())===null||eo===void 0?void 0:eo.lcdUrl}getDenom(){var eo;return(eo=this.getSelectedNetwork())===null||eo===void 0?void 0:eo.nativeCurrency.denom}getBalance(eo){return __awaiter$f(this,void 0,void 0,function*(){try{return(yield fetch(`${this.getLcdUrl()}/cosmos/bank/v1beta1/balances/${eo}`).then(no=>no.json())).balances.reduce((no,io)=>io.denom===this.getDenom()?Number(io.amount)/1e6:no,0).toString()}catch(to){return logger$9.error(to),"0"}})}getConnectedAccounts(){return __awaiter$f(this,void 0,void 0,function*(){return[yield this.getAddress()]})}endSession(){return __awaiter$f(this,void 0,void 0,function*(){this.setChainId(null)})}}const DYNAMIC_KEPLR_NETWORK_ID="dynamic_keplr_network_id";class KeplrWalletConnector extends CosmosWalletConnector{constructor(eo){super(eo),this.switchNetworkOnlyFromWallet=!0,this.name="Keplr",this.overrideKey="keplr",this._handleAccountChange=this._handleAccountChange.bind(this)}getDefaultChainId(){return this.chainIdMapping.length===0||this.chainIdMapping.find(eo=>eo.cosmosNetworkId==="cosmoshub-4")?"cosmoshub-4":this.chainIdMapping[0].cosmosNetworkId}getChainId(){const eo=this.getDefaultChainId(),to=localStorage.getItem(DYNAMIC_KEPLR_NETWORK_ID);return to??eo}setChainId(eo){eo?localStorage.setItem(DYNAMIC_KEPLR_NETWORK_ID,eo):localStorage.removeItem(DYNAMIC_KEPLR_NETWORK_ID)}getAccount(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this.keplr.getOfflineSigner(this.getChainId()).getAccounts();if(!eo)throw new Error("No accounts found");const[to]=eo;return to})}get keplr(){if(typeof window>"u")throw new Error("Keplr is not available");return window.keplr}connect(){return __awaiter$f(this,void 0,void 0,function*(){yield this.keplr.enable(this.chainIdMapping.map(eo=>eo.cosmosNetworkId))})}getAddress(){return __awaiter$f(this,void 0,void 0,function*(){return yield this.connect(),(yield this.getAccount()).address})}getProvider(){return __awaiter$f(this,void 0,void 0,function*(){return this.keplr})}getOfflineSigner(){return __awaiter$f(this,void 0,void 0,function*(){return this.keplr.getOfflineSigner(this.getChainId())})}isInstalledOnBrowser(){return typeof window.keplr<"u"}_handleAccountChange(){return __awaiter$f(this,void 0,void 0,function*(){const eo=yield this.getAddress();this.emit("accountChange",{accounts:[eo]})})}setupEventListeners(){window.addEventListener("keplr_keystorechange",this._handleAccountChange)}teardownEventListeners(){window.removeEventListener("keplr_keystorechange",this._handleAccountChange),this.setChainId(null)}getSignDoc(eo){return{account_number:"0",chain_id:this.getChainId(),fee:{amount:[],gas:"0"},memo:"",msgs:[{type:"custom/MsgSignText",value:{text:eo}}],sequence:"0"}}signMessage(eo){return __awaiter$f(this,void 0,void 0,function*(){const to=this.getSignDoc(eo),ro=yield this.getAddress(),no=yield this.keplr.signAmino(this.getChainId(),ro,to);if(!no)throw new Error("Could not sign message");return JSON.stringify(no)})}supportsNetworkSwitching(){return!0}switchNetwork(eo){return __awaiter$f(this,arguments,void 0,function*({networkChainId:to}){to&&this.chainIdMapping.forEach(ro=>{ro.dynamicChainId===to&&(this.setChainId(ro.cosmosNetworkId),this.emit("chainChange",{chain:to.toString()}))})})}}assertPackageVersion("@dynamic-labs/cosmos",version$h);const CosmosWalletConnectors=()=>[KeplrWalletConnector];typeof window<"u"&&(window.global=globalThis,Object.assign(window,{Buffer:Buffer$1$1}));var version$g="3.4.4",version$f="3.4.4";function __awaiter$e(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}function __classPrivateFieldGet$3(Xr,eo,to,ro){if(to==="a"&&!ro)throw new TypeError("Private accessor was defined without a getter");if(typeof eo=="function"?Xr!==eo||!ro:!eo.has(Xr))throw new TypeError("Cannot read private member from an object whose class did not declare it");return to==="m"?ro:to==="a"?ro.call(Xr):ro?ro.value:eo.get(Xr)}function __classPrivateFieldSet$3(Xr,eo,to,ro,no){if(typeof eo=="function"?Xr!==eo||!no:!eo.has(Xr))throw new TypeError("Cannot write private member to an object whose class did not declare it");return no?no.value=to:eo.set(Xr,to),to}typeof SuppressedError=="function"&&SuppressedError;const DEFAULT_JWK_MEMBER_BYTE_LENGTH=32;function stringToBase64urlString(Xr){const eo=btoa$1(Xr);return base64StringToBase64UrlEncodedString(eo)}function hexStringToBase64url(Xr,eo){const to=Xr.padStart(Math.ceil(Xr.length/2)*2,"0"),ro=uint8ArrayFromHexString(to,eo);return stringToBase64urlString(ro.reduce((no,io)=>no+String.fromCharCode(io),""))}function base64StringToBase64UrlEncodedString(Xr){return Xr.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uint8ArrayToHexString(Xr){return Xr.reduce((eo,to)=>eo+to.toString(16).padStart(2,"0"),"")}const uint8ArrayFromHexString=(Xr,eo)=>{const to=/^[0-9A-Fa-f]+$/;if(!Xr||Xr.length%2!=0||!to.test(Xr))throw new Error(`cannot create uint8array from invalid hex string: "${Xr}"`);const ro=new Uint8Array(Xr.match(/../g).map(io=>parseInt(io,16)));if(!eo)return ro;if(Xr.length/2>eo)throw new Error("hex value cannot fit in a buffer of "+eo+" byte(s)");let no=new Uint8Array(eo);return no.set(ro,eo-ro.length),no};function btoa$1(Xr){if(arguments.length===0)throw new TypeError("1 argument required, but only 0 present.");let eo;for(Xr=`${Xr}`,eo=0;eo255)throw new Error(`InvalidCharacterError: found code point greater than 255:${Xr.charCodeAt(eo)} at position ${eo}`);let to="";for(eo=0;eo>2,ro[1]=(Xr.charCodeAt(eo)&3)<<4,Xr.length>eo+1&&(ro[1]|=Xr.charCodeAt(eo+1)>>4,ro[2]=(Xr.charCodeAt(eo+1)&15)<<2),Xr.length>eo+2&&(ro[2]|=Xr.charCodeAt(eo+2)>>6,ro[3]=Xr.charCodeAt(eo+2)&63);for(let no=0;no"u"?to+="=":to+=btoaLookup(ro[no])}return to}function btoaLookup(Xr){const eo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";if(Xr>=0&&Xr<64)return eo[Xr]}const stampHeaderName$2="X-Stamp",isCryptoEnabledBrowser=typeof window<"u"&&typeof window.document<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u",isNode=typeof process$1$1<"u"&&process$1$1.versions!=null&&process$1$1.versions.node!=null,signWithApiKey=async Xr=>isCryptoEnabledBrowser?(await __vitePreload(()=>import("./webcrypto-6IU6aAco.js"),__vite__mapDeps([0,1])).then(to=>to.signWithApiKey))(Xr):isNode?(await __vitePreload(()=>import("./nodecrypto-BXD6e4iz.js"),__vite__mapDeps([2,1])).then(to=>to.signWithApiKey))(Xr):(await __vitePreload(()=>import("./purejs-BONB21cl.js"),[]).then(to=>to.signWithApiKey))(Xr);class ApiKeyStamper{constructor(eo){this.apiPublicKey=eo.apiPublicKey,this.apiPrivateKey=eo.apiPrivateKey}async stamp(eo){const to=await signWithApiKey({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:eo}),ro={publicKey:this.apiPublicKey,scheme:"SIGNATURE_SCHEME_TK_API_P256",signature:to};return{stampHeaderName:stampHeaderName$2,stampHeaderValue:stringToBase64urlString(JSON.stringify(ro))}}}const base64UrlEncode=Xr=>Buffer$3.from(Xr).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),generateRandomBuffer=()=>{const Xr=new Uint8Array(32);return crypto.getRandomValues(Xr),Xr.buffer},transportMap={AUTHENTICATOR_TRANSPORT_BLE:AuthenticatorTransportProtocol.Ble,AUTHENTICATOR_TRANSPORT_HYBRID:AuthenticatorTransportProtocol.Hybrid,AUTHENTICATOR_TRANSPORT_INTERNAL:AuthenticatorTransportProtocol.Internal,AUTHENTICATOR_TRANSPORT_NFC:AuthenticatorTransportProtocol.Nfc,AUTHENTICATOR_TRANSPORT_USB:AuthenticatorTransportProtocol.Usb},convertAttestationTransports=Xr=>Xr.map(eo=>transportMap[eo]),TURNKEY_API_BASE_URL="https://api.turnkey.com",TURNKEY_API_KEY_EXPIRY_MESSAGE="Turnkey error 16: expired api key",TURNKEY_API_KEY_NOT_FOUND_MESSAGE="Turnkey error 16: could not find public key",WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE="The operation either timed out or was not allowed",WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE="The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",INVALID_PASSKEY_SELECTED_ERROR_MESSAGE="Turnkey error 5: webauthn authenticator not found in organization or parent organization",USER_CANCELLED_REQUEST_ERROR_MESSAGE="The user cancelled the request",TURNKEY_SDK_SESSION_KEY_RETRYABLE_ERRORS=[TURNKEY_API_KEY_EXPIRY_MESSAGE,TURNKEY_API_KEY_NOT_FOUND_MESSAGE],TURNKEY_SDK_BENIGN_ERRORS=[WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE,WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE,INVALID_PASSKEY_SELECTED_ERROR_MESSAGE,USER_CANCELLED_REQUEST_ERROR_MESSAGE];class DynamicEmbeddedWalletsLogger extends Logger$2{constructor(eo,to){super(eo,to)}error(eo,...to){const[ro]=to;!(ro!=null&&ro.message)||!TURNKEY_SDK_BENIGN_ERRORS.some(no=>ro.message.includes(no))?(Logger$2.events.emit("error",eo),this.log(LogLevel.ERROR,eo,...to)):this.warn(eo,...to)}}const logger$6=new DynamicEmbeddedWalletsLogger("Dynamic embedded wallets",LogLevel.INFO),stampHeaderName$1="X-Stamp";var IframeEventType;(function(Xr){Xr.PublicKeyReady="PUBLIC_KEY_READY",Xr.InjectCredentialBundle="INJECT_CREDENTIAL_BUNDLE",Xr.InjectKeyExportBundle="INJECT_KEY_EXPORT_BUNDLE",Xr.InjectWalletExportBundle="INJECT_WALLET_EXPORT_BUNDLE",Xr.InjectImportBundle="INJECT_IMPORT_BUNDLE",Xr.ExtractWalletEncryptedBundle="EXTRACT_WALLET_ENCRYPTED_BUNDLE",Xr.ExtractKeyEncryptedBundle="EXTRACT_KEY_ENCRYPTED_BUNDLE",Xr.ApplySettings="APPLY_SETTINGS",Xr.BundleInjected="BUNDLE_INJECTED",Xr.EncryptedBundleExtracted="ENCRYPTED_BUNDLE_EXTRACTED",Xr.SettingsApplied="SETTINGS_APPLIED",Xr.StampRequest="STAMP_REQUEST",Xr.Stamp="STAMP",Xr.Error="ERROR"})(IframeEventType||(IframeEventType={}));var KeyFormat;(function(Xr){Xr.Hexadecimal="HEXADECIMAL",Xr.Solana="SOLANA"})(KeyFormat||(KeyFormat={}));class IframeStamper{constructor(eo){if(typeof window>"u")throw new Error("Cannot initialize iframe in non-browser environment");if(!eo.iframeContainer)throw new Error("Iframe container cannot be found");if(this.container=eo.iframeContainer,this.container.querySelector(`#${eo.iframeElementId}`))throw new Error(`Iframe element with ID ${eo.iframeElementId} already exists`);let to=window.document.createElement("iframe");to.setAttribute("sandbox","allow-scripts allow-same-origin"),to.id=eo.iframeElementId,to.src=eo.iframeUrl,this.iframe=to;const ro=new URL(eo.iframeUrl);this.iframeOrigin=ro.origin,this.iframePublicKey=null}async init(){return this.container.appendChild(this.iframe),new Promise((eo,to)=>{window.addEventListener("message",ro=>{var no;ro.origin===this.iframeOrigin&&((no=ro.data)==null?void 0:no.type)===IframeEventType.PublicKeyReady&&(this.iframePublicKey=ro.data.value,eo(ro.data.value))},!1)})}clear(){this.iframe.remove()}publicKey(){return this.iframePublicKey}async injectCredentialBundle(eo){return new Promise((to,ro)=>{var no;(no=this.iframe.contentWindow)==null||no.postMessage({type:IframeEventType.InjectCredentialBundle,value:eo},"*"),window.addEventListener("message",io=>{var oo,ao;io.origin===this.iframeOrigin&&(((oo=io.data)==null?void 0:oo.type)===IframeEventType.BundleInjected&&to(io.data.value),((ao=io.data)==null?void 0:ao.type)===IframeEventType.Error&&ro(io.data.value))},!1)})}async injectKeyExportBundle(eo,to,ro){var no;return(no=this.iframe.contentWindow)==null||no.postMessage({type:IframeEventType.InjectKeyExportBundle,value:eo,keyFormat:ro,organizationId:to},"*"),new Promise((io,oo)=>{window.addEventListener("message",ao=>{var so,co;ao.origin===this.iframeOrigin&&(((so=ao.data)==null?void 0:so.type)===IframeEventType.BundleInjected&&io(ao.data.value),((co=ao.data)==null?void 0:co.type)===IframeEventType.Error&&oo(ao.data.value))},!1)})}async injectWalletExportBundle(eo,to){var ro;return(ro=this.iframe.contentWindow)==null||ro.postMessage({type:IframeEventType.InjectWalletExportBundle,value:eo,organizationId:to},"*"),new Promise((no,io)=>{window.addEventListener("message",oo=>{var ao,so;oo.origin===this.iframeOrigin&&(((ao=oo.data)==null?void 0:ao.type)===IframeEventType.BundleInjected&&no(oo.data.value),((so=oo.data)==null?void 0:so.type)===IframeEventType.Error&&io(oo.data.value))},!1)})}async injectImportBundle(eo,to,ro){var no;return(no=this.iframe.contentWindow)==null||no.postMessage({type:IframeEventType.InjectImportBundle,value:eo,organizationId:to,userId:ro},"*"),new Promise((io,oo)=>{window.addEventListener("message",ao=>{var so,co;ao.origin===this.iframeOrigin&&(((so=ao.data)==null?void 0:so.type)===IframeEventType.BundleInjected&&io(ao.data.value),((co=ao.data)==null?void 0:co.type)===IframeEventType.Error&&oo(ao.data.value))},!1)})}async extractWalletEncryptedBundle(){var eo;return(eo=this.iframe.contentWindow)==null||eo.postMessage({type:IframeEventType.ExtractWalletEncryptedBundle},"*"),new Promise((to,ro)=>{window.addEventListener("message",no=>{var io,oo;no.origin===this.iframeOrigin&&(((io=no.data)==null?void 0:io.type)===IframeEventType.EncryptedBundleExtracted&&to(no.data.value),((oo=no.data)==null?void 0:oo.type)===IframeEventType.Error&&ro(no.data.value))},!1)})}async extractKeyEncryptedBundle(eo){var to;return(to=this.iframe.contentWindow)==null||to.postMessage({type:IframeEventType.ExtractKeyEncryptedBundle,keyFormat:eo},"*"),new Promise((ro,no)=>{window.addEventListener("message",io=>{var oo,ao;io.origin===this.iframeOrigin&&(((oo=io.data)==null?void 0:oo.type)===IframeEventType.EncryptedBundleExtracted&&ro(io.data.value),((ao=io.data)==null?void 0:ao.type)===IframeEventType.Error&&no(io.data.value))},!1)})}async applySettings(eo){var ro;const to=JSON.stringify(eo);return(ro=this.iframe.contentWindow)==null||ro.postMessage({type:IframeEventType.ApplySettings,value:to},"*"),new Promise((no,io)=>{window.addEventListener("message",oo=>{var ao,so;oo.origin===this.iframeOrigin&&(((ao=oo.data)==null?void 0:ao.type)===IframeEventType.SettingsApplied&&no(oo.data.value),((so=oo.data)==null?void 0:so.type)===IframeEventType.Error&&io(oo.data.value))},!1)})}async stamp(eo){var ro;if(this.iframePublicKey===null)throw new Error("null iframe public key. Have you called/awaited .init()?");const to=this.iframeOrigin;return(ro=this.iframe.contentWindow)==null||ro.postMessage({type:IframeEventType.StampRequest,value:eo},"*"),new Promise(function(no,io){window.addEventListener("message",oo=>{var ao,so;oo.origin===to&&(((ao=oo.data)==null?void 0:ao.type)===IframeEventType.Stamp&&no({stampHeaderName:stampHeaderName$1,stampHeaderValue:oo.data.value}),((so=oo.data)==null?void 0:so.type)===IframeEventType.Error&&io(oo.data.value))},!1)})}}var browserPonyfill={exports:{}};(function(Xr,eo){var to=typeof self<"u"?self:commonjsGlobal,ro=function(){function io(){this.fetch=!1,this.DOMException=to.DOMException}return io.prototype=to,new io}();(function(io){(function(oo){var ao={searchParams:"URLSearchParams"in io,iterable:"Symbol"in io&&"iterator"in Symbol,blob:"FileReader"in io&&"Blob"in io&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in io,arrayBuffer:"ArrayBuffer"in io};function so(uo){return uo&&DataView.prototype.isPrototypeOf(uo)}if(ao.arrayBuffer)var co=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],lo=ArrayBuffer.isView||function(uo){return uo&&co.indexOf(Object.prototype.toString.call(uo))>-1};function fo(uo){if(typeof uo!="string"&&(uo=String(uo)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(uo))throw new TypeError("Invalid character in header field name");return uo.toLowerCase()}function ho(uo){return typeof uo!="string"&&(uo=String(uo)),uo}function go(uo){var po={next:function(){var bo=uo.shift();return{done:bo===void 0,value:bo}}};return ao.iterable&&(po[Symbol.iterator]=function(){return po}),po}function yo(uo){this.map={},uo instanceof yo?uo.forEach(function(po,bo){this.append(bo,po)},this):Array.isArray(uo)?uo.forEach(function(po){this.append(po[0],po[1])},this):uo&&Object.getOwnPropertyNames(uo).forEach(function(po){this.append(po,uo[po])},this)}yo.prototype.append=function(uo,po){uo=fo(uo),po=ho(po);var bo=this.map[uo];this.map[uo]=bo?bo+", "+po:po},yo.prototype.delete=function(uo){delete this.map[fo(uo)]},yo.prototype.get=function(uo){return uo=fo(uo),this.has(uo)?this.map[uo]:null},yo.prototype.has=function(uo){return this.map.hasOwnProperty(fo(uo))},yo.prototype.set=function(uo,po){this.map[fo(uo)]=ho(po)},yo.prototype.forEach=function(uo,po){for(var bo in this.map)this.map.hasOwnProperty(bo)&&uo.call(po,this.map[bo],bo,this)},yo.prototype.keys=function(){var uo=[];return this.forEach(function(po,bo){uo.push(bo)}),go(uo)},yo.prototype.values=function(){var uo=[];return this.forEach(function(po){uo.push(po)}),go(uo)},yo.prototype.entries=function(){var uo=[];return this.forEach(function(po,bo){uo.push([bo,po])}),go(uo)},ao.iterable&&(yo.prototype[Symbol.iterator]=yo.prototype.entries);function vo(uo){if(uo.bodyUsed)return Promise.reject(new TypeError("Already read"));uo.bodyUsed=!0}function wo(uo){return new Promise(function(po,bo){uo.onload=function(){po(uo.result)},uo.onerror=function(){bo(uo.error)}})}function Eo(uo){var po=new FileReader,bo=wo(po);return po.readAsArrayBuffer(uo),bo}function ko(uo){var po=new FileReader,bo=wo(po);return po.readAsText(uo),bo}function Ao(uo){for(var po=new Uint8Array(uo),bo=new Array(po.length),_o=0;_o-1?po:uo}function Do(uo,po){po=po||{};var bo=po.body;if(uo instanceof Do){if(uo.bodyUsed)throw new TypeError("Already read");this.url=uo.url,this.credentials=uo.credentials,po.headers||(this.headers=new yo(uo.headers)),this.method=uo.method,this.mode=uo.mode,this.signal=uo.signal,!bo&&uo._bodyInit!=null&&(bo=uo._bodyInit,uo.bodyUsed=!0)}else this.url=String(uo);if(this.credentials=po.credentials||this.credentials||"same-origin",(po.headers||!this.headers)&&(this.headers=new yo(po.headers)),this.method=No(po.method||this.method||"GET"),this.mode=po.mode||this.mode||null,this.signal=po.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&bo)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(bo)}Do.prototype.clone=function(){return new Do(this,{body:this._bodyInit})};function Fo(uo){var po=new FormData;return uo.trim().split("&").forEach(function(bo){if(bo){var _o=bo.split("="),$o=_o.shift().replace(/\+/g," "),Co=_o.join("=").replace(/\+/g," ");po.append(decodeURIComponent($o),decodeURIComponent(Co))}}),po}function Xo(uo){var po=new yo,bo=uo.replace(/\r?\n[\t ]+/g," ");return bo.split(/\r?\n/).forEach(function(_o){var $o=_o.split(":"),Co=$o.shift().trim();if(Co){var Ro=$o.join(":").trim();po.append(Co,Ro)}}),po}jo.call(Do.prototype);function Lo(uo,po){po||(po={}),this.type="default",this.status=po.status===void 0?200:po.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in po?po.statusText:"OK",this.headers=new yo(po.headers),this.url=po.url||"",this._initBody(uo)}jo.call(Lo.prototype),Lo.prototype.clone=function(){return new Lo(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new yo(this.headers),url:this.url})},Lo.error=function(){var uo=new Lo(null,{status:0,statusText:""});return uo.type="error",uo};var Bo=[301,302,303,307,308];Lo.redirect=function(uo,po){if(Bo.indexOf(po)===-1)throw new RangeError("Invalid status code");return new Lo(null,{status:po,headers:{location:uo}})},oo.DOMException=io.DOMException;try{new oo.DOMException}catch{oo.DOMException=function(po,bo){this.message=po,this.name=bo;var _o=Error(po);this.stack=_o.stack},oo.DOMException.prototype=Object.create(Error.prototype),oo.DOMException.prototype.constructor=oo.DOMException}function xo(uo,po){return new Promise(function(bo,_o){var $o=new Do(uo,po);if($o.signal&&$o.signal.aborted)return _o(new oo.DOMException("Aborted","AbortError"));var Co=new XMLHttpRequest;function Ro(){Co.abort()}Co.onload=function(){var So={status:Co.status,statusText:Co.statusText,headers:Xo(Co.getAllResponseHeaders()||"")};So.url="responseURL"in Co?Co.responseURL:So.headers.get("X-Request-URL");var mo="response"in Co?Co.response:Co.responseText;bo(new Lo(mo,So))},Co.onerror=function(){_o(new TypeError("Network request failed"))},Co.ontimeout=function(){_o(new TypeError("Network request failed"))},Co.onabort=function(){_o(new oo.DOMException("Aborted","AbortError"))},Co.open($o.method,$o.url,!0),$o.credentials==="include"?Co.withCredentials=!0:$o.credentials==="omit"&&(Co.withCredentials=!1),"responseType"in Co&&ao.blob&&(Co.responseType="blob"),$o.headers.forEach(function(So,mo){Co.setRequestHeader(mo,So)}),$o.signal&&($o.signal.addEventListener("abort",Ro),Co.onreadystatechange=function(){Co.readyState===4&&$o.signal.removeEventListener("abort",Ro)}),Co.send(typeof $o._bodyInit>"u"?null:$o._bodyInit)})}return xo.polyfill=!0,io.fetch||(io.fetch=xo,io.Headers=yo,io.Request=Do,io.Response=Lo),oo.Headers=yo,oo.Request=Do,oo.Response=Lo,oo.fetch=xo,Object.defineProperty(oo,"__esModule",{value:!0}),oo})({})})(ro),ro.fetch.ponyfill=!0,delete ro.fetch.polyfill;var no=ro;eo=no.fetch,eo.default=no.fetch,eo.fetch=no.fetch,eo.Headers=no.Headers,eo.Request=no.Request,eo.Response=no.Response,Xr.exports=eo})(browserPonyfill,browserPonyfill.exports);var browserPonyfillExports=browserPonyfill.exports;const fetchTransport=getDefaultExportFromCjs$2(browserPonyfillExports),fetch$2=browserPonyfillExports.fetch;class TurnkeyRequestError extends Error{constructor(eo){let to=`Turnkey error ${eo.code}: ${eo.message}`;eo.details!=null&&(to+=` (Details: ${JSON.stringify(eo.details)})`),super(to),this.name="TurnkeyRequestError",this.details=eo.details??null,this.code=eo.code}}const VERSION$3="@turnkey/http@2.12.2";class TurnkeyClient{constructor(eo,to){if(this.getActivity=async ro=>this.request("/public/v1/query/get_activity",ro),this.stampGetActivity=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_activity",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getApiKey=async ro=>this.request("/public/v1/query/get_api_key",ro),this.stampGetApiKey=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_api_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getApiKeys=async ro=>this.request("/public/v1/query/get_api_keys",ro),this.stampGetApiKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_api_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getAttestationDocument=async ro=>this.request("/public/v1/query/get_attestation",ro),this.stampGetAttestationDocument=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_attestation",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getAuthenticator=async ro=>this.request("/public/v1/query/get_authenticator",ro),this.stampGetAuthenticator=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_authenticator",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getAuthenticators=async ro=>this.request("/public/v1/query/get_authenticators",ro),this.stampGetAuthenticators=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_authenticators",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getOauthProviders=async ro=>this.request("/public/v1/query/get_oauth_providers",ro),this.stampGetOauthProviders=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_oauth_providers",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getOrganization=async ro=>this.request("/public/v1/query/get_organization",ro),this.stampGetOrganization=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_organization",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getOrganizationConfigs=async ro=>this.request("/public/v1/query/get_organization_configs",ro),this.stampGetOrganizationConfigs=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_organization_configs",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPolicy=async ro=>this.request("/public/v1/query/get_policy",ro),this.stampGetPolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPrivateKey=async ro=>this.request("/public/v1/query/get_private_key",ro),this.stampGetPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getUser=async ro=>this.request("/public/v1/query/get_user",ro),this.stampGetUser=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_user",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWallet=async ro=>this.request("/public/v1/query/get_wallet",ro),this.stampGetWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/query/get_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getActivities=async ro=>this.request("/public/v1/query/list_activities",ro),this.stampGetActivities=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_activities",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPolicies=async ro=>this.request("/public/v1/query/list_policies",ro),this.stampGetPolicies=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_policies",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.listPrivateKeyTags=async ro=>this.request("/public/v1/query/list_private_key_tags",ro),this.stampListPrivateKeyTags=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_private_key_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getPrivateKeys=async ro=>this.request("/public/v1/query/list_private_keys",ro),this.stampGetPrivateKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_private_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getSubOrgIds=async ro=>this.request("/public/v1/query/list_suborgs",ro),this.stampGetSubOrgIds=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_suborgs",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.listUserTags=async ro=>this.request("/public/v1/query/list_user_tags",ro),this.stampListUserTags=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_user_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getUsers=async ro=>this.request("/public/v1/query/list_users",ro),this.stampGetUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWalletAccounts=async ro=>this.request("/public/v1/query/list_wallet_accounts",ro),this.stampGetWalletAccounts=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_wallet_accounts",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWallets=async ro=>this.request("/public/v1/query/list_wallets",ro),this.stampGetWallets=async ro=>{const no=this.config.baseUrl+"/public/v1/query/list_wallets",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.getWhoami=async ro=>this.request("/public/v1/query/whoami",ro),this.stampGetWhoami=async ro=>{const no=this.config.baseUrl+"/public/v1/query/whoami",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.approveActivity=async ro=>this.request("/public/v1/submit/approve_activity",ro),this.stampApproveActivity=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/approve_activity",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createApiKeys=async ro=>this.request("/public/v1/submit/create_api_keys",ro),this.stampCreateApiKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_api_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createApiOnlyUsers=async ro=>this.request("/public/v1/submit/create_api_only_users",ro),this.stampCreateApiOnlyUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_api_only_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createAuthenticators=async ro=>this.request("/public/v1/submit/create_authenticators",ro),this.stampCreateAuthenticators=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_authenticators",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createInvitations=async ro=>this.request("/public/v1/submit/create_invitations",ro),this.stampCreateInvitations=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_invitations",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createOauthProviders=async ro=>this.request("/public/v1/submit/create_oauth_providers",ro),this.stampCreateOauthProviders=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_oauth_providers",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPolicies=async ro=>this.request("/public/v1/submit/create_policies",ro),this.stampCreatePolicies=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_policies",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPolicy=async ro=>this.request("/public/v1/submit/create_policy",ro),this.stampCreatePolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPrivateKeyTag=async ro=>this.request("/public/v1/submit/create_private_key_tag",ro),this.stampCreatePrivateKeyTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_private_key_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createPrivateKeys=async ro=>this.request("/public/v1/submit/create_private_keys",ro),this.stampCreatePrivateKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_private_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createReadOnlySession=async ro=>this.request("/public/v1/submit/create_read_only_session",ro),this.stampCreateReadOnlySession=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_read_only_session",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createReadWriteSession=async ro=>this.request("/public/v1/submit/create_read_write_session",ro),this.stampCreateReadWriteSession=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_read_write_session",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createSubOrganization=async ro=>this.request("/public/v1/submit/create_sub_organization",ro),this.stampCreateSubOrganization=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_sub_organization",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createUserTag=async ro=>this.request("/public/v1/submit/create_user_tag",ro),this.stampCreateUserTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_user_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createUsers=async ro=>this.request("/public/v1/submit/create_users",ro),this.stampCreateUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createWallet=async ro=>this.request("/public/v1/submit/create_wallet",ro),this.stampCreateWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.createWalletAccounts=async ro=>this.request("/public/v1/submit/create_wallet_accounts",ro),this.stampCreateWalletAccounts=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/create_wallet_accounts",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteApiKeys=async ro=>this.request("/public/v1/submit/delete_api_keys",ro),this.stampDeleteApiKeys=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_api_keys",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteAuthenticators=async ro=>this.request("/public/v1/submit/delete_authenticators",ro),this.stampDeleteAuthenticators=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_authenticators",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteInvitation=async ro=>this.request("/public/v1/submit/delete_invitation",ro),this.stampDeleteInvitation=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_invitation",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteOauthProviders=async ro=>this.request("/public/v1/submit/delete_oauth_providers",ro),this.stampDeleteOauthProviders=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_oauth_providers",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deletePolicy=async ro=>this.request("/public/v1/submit/delete_policy",ro),this.stampDeletePolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deletePrivateKeyTags=async ro=>this.request("/public/v1/submit/delete_private_key_tags",ro),this.stampDeletePrivateKeyTags=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_private_key_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteUserTags=async ro=>this.request("/public/v1/submit/delete_user_tags",ro),this.stampDeleteUserTags=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_user_tags",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.deleteUsers=async ro=>this.request("/public/v1/submit/delete_users",ro),this.stampDeleteUsers=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/delete_users",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.emailAuth=async ro=>this.request("/public/v1/submit/email_auth",ro),this.stampEmailAuth=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/email_auth",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.exportPrivateKey=async ro=>this.request("/public/v1/submit/export_private_key",ro),this.stampExportPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/export_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.exportWallet=async ro=>this.request("/public/v1/submit/export_wallet",ro),this.stampExportWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/export_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.exportWalletAccount=async ro=>this.request("/public/v1/submit/export_wallet_account",ro),this.stampExportWalletAccount=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/export_wallet_account",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.importPrivateKey=async ro=>this.request("/public/v1/submit/import_private_key",ro),this.stampImportPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/import_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.importWallet=async ro=>this.request("/public/v1/submit/import_wallet",ro),this.stampImportWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/import_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.initImportPrivateKey=async ro=>this.request("/public/v1/submit/init_import_private_key",ro),this.stampInitImportPrivateKey=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/init_import_private_key",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.initImportWallet=async ro=>this.request("/public/v1/submit/init_import_wallet",ro),this.stampInitImportWallet=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/init_import_wallet",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.initUserEmailRecovery=async ro=>this.request("/public/v1/submit/init_user_email_recovery",ro),this.stampInitUserEmailRecovery=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/init_user_email_recovery",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.oauth=async ro=>this.request("/public/v1/submit/oauth",ro),this.stampOauth=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/oauth",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.recoverUser=async ro=>this.request("/public/v1/submit/recover_user",ro),this.stampRecoverUser=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/recover_user",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.rejectActivity=async ro=>this.request("/public/v1/submit/reject_activity",ro),this.stampRejectActivity=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/reject_activity",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.removeOrganizationFeature=async ro=>this.request("/public/v1/submit/remove_organization_feature",ro),this.stampRemoveOrganizationFeature=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/remove_organization_feature",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.setOrganizationFeature=async ro=>this.request("/public/v1/submit/set_organization_feature",ro),this.stampSetOrganizationFeature=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/set_organization_feature",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.signRawPayload=async ro=>this.request("/public/v1/submit/sign_raw_payload",ro),this.stampSignRawPayload=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/sign_raw_payload",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.signRawPayloads=async ro=>this.request("/public/v1/submit/sign_raw_payloads",ro),this.stampSignRawPayloads=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/sign_raw_payloads",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.signTransaction=async ro=>this.request("/public/v1/submit/sign_transaction",ro),this.stampSignTransaction=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/sign_transaction",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updatePolicy=async ro=>this.request("/public/v1/submit/update_policy",ro),this.stampUpdatePolicy=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_policy",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updatePrivateKeyTag=async ro=>this.request("/public/v1/submit/update_private_key_tag",ro),this.stampUpdatePrivateKeyTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_private_key_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updateRootQuorum=async ro=>this.request("/public/v1/submit/update_root_quorum",ro),this.stampUpdateRootQuorum=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_root_quorum",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updateUser=async ro=>this.request("/public/v1/submit/update_user",ro),this.stampUpdateUser=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_user",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},this.updateUserTag=async ro=>this.request("/public/v1/submit/update_user_tag",ro),this.stampUpdateUserTag=async ro=>{const no=this.config.baseUrl+"/public/v1/submit/update_user_tag",io=JSON.stringify(ro),oo=await this.stamper.stamp(io);return{body:io,stamp:oo,url:no}},!eo.baseUrl)throw new Error("Missing base URL. Please verify env vars.");this.config=eo,this.stamper=to}async request(eo,to){const ro=this.config.baseUrl+eo,no=JSON.stringify(to),io=await this.stamper.stamp(no),oo=await fetch$2(ro,{method:"POST",headers:{[io.stampHeaderName]:io.stampHeaderValue,"X-Client-Version":VERSION$3},body:no,redirect:"follow"});if(!oo.ok){let so;try{so=await oo.json()}catch{throw new Error(`${oo.status} ${oo.statusText}`)}throw new TurnkeyRequestError(so)}return await oo.json()}}class TurnkeyActivityError extends Error{constructor(eo){const{message:to,cause:ro,activityId:no,activityStatus:io,activityType:oo}=eo;super(to),this.name="TurnkeyActivityError",this.activityId=no??null,this.activityStatus=io??null,this.activityType=oo??null,this.cause=ro??null}}function bufferToBase64url(Xr){const eo=new Uint8Array(Xr);let to="";for(const io of eo)to+=String.fromCharCode(io);return btoa(to).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}const copyValue="copy",convertValue="convert";function convert$1(Xr,eo,to){if(eo===copyValue)return to;if(eo===convertValue)return Xr(to);if(eo instanceof Array)return to.map(ro=>convert$1(Xr,eo[0],ro));if(eo instanceof Object){const ro={};for(const[no,io]of Object.entries(eo)){if(io.derive){const oo=io.derive(to);oo!==void 0&&(to[no]=oo)}if(!(no in to)){if(io.required)throw new Error(`Missing key: ${no}`);continue}if(to[no]==null){ro[no]=null;continue}ro[no]=convert$1(Xr,io.schema,to[no])}return ro}}function derived(Xr,eo){return{required:!0,schema:Xr,derive:eo}}function required(Xr){return{required:!0,schema:Xr}}function optional$3(Xr){return{required:!1,schema:Xr}}const simplifiedClientExtensionResultsSchema={appid:optional$3(copyValue),appidExclude:optional$3(copyValue),credProps:optional$3(copyValue)},publicKeyCredentialWithAssertion={type:required(copyValue),id:required(copyValue),rawId:required(convertValue),authenticatorAttachment:optional$3(copyValue),response:required({clientDataJSON:required(convertValue),authenticatorData:required(convertValue),signature:required(convertValue),userHandle:required(convertValue)}),clientExtensionResults:derived(simplifiedClientExtensionResultsSchema,Xr=>Xr.getClientExtensionResults())};function getResponseToJSON(Xr){return convert$1(bufferToBase64url,publicKeyCredentialWithAssertion,Xr)}async function get$3(Xr){const eo=await navigator.credentials.get(Xr);return eo.toJSON=()=>getResponseToJSON(eo),eo}const K$4=[1116352408,1899447441,-1245643825,-373957723,961987163,1508970993,-1841331548,-1424204075,-670586216,310598401,607225278,1426881987,1925078388,-2132889090,-1680079193,-1046744716,-459576895,-272742522,264347078,604807628,770255983,1249150122,1555081692,1996064986,-1740746414,-1473132947,-1341970488,-1084653625,-958395405,-710438585,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,-2117940946,-1838011259,-1564481375,-1474664885,-1035236496,-949202525,-778901479,-694614492,-200395387,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,-2067236844,-1933114872,-1866530822,-1538233109,-1090935817,-965641998];function createHash(Xr){return new Hash$1}let Hash$1=class{constructor(){this.A=1779033703,this.B=-1150833019,this.C=1013904242,this.D=-1521486534,this.E=1359893119,this.F=-1694144372,this.G=528734635,this.H=1541459225,this._size=0,this._sp=0,(!sharedBuffer||sharedOffset>=8e3)&&(sharedBuffer=new ArrayBuffer(8e3),sharedOffset=0),this._byte=new Uint8Array(sharedBuffer,sharedOffset,80),this._word=new Int32Array(sharedBuffer,sharedOffset,20),sharedOffset+=80}update(eo){if(typeof eo=="string")return this._utf8(eo);if(eo==null)throw new TypeError("Invalid type: "+typeof eo);const to=eo.byteOffset,ro=eo.byteLength;let no=ro/64|0,io=0;if(no&&!(to&3)&&!(this._size%64)){const ao=new Int32Array(eo.buffer,to,no*16);for(;no--;)this._int32(ao,io>>2),io+=64;this._size+=io}if(eo.BYTES_PER_ELEMENT!==1&&eo.buffer){const ao=new Uint8Array(eo.buffer,to+io,ro-io);return this._uint8(ao)}return io===ro?this:this._uint8(eo,io)}_uint8(eo,to){const{_byte:ro,_word:no}=this,io=eo.length;for(to=to|0;to=64&&this._int32(no),this._size+=ao-oo}return this}_utf8(eo){const{_byte:to,_word:ro}=this,no=eo.length;let io=this._sp;for(let oo=0;oo>>6,to[so++]=128|co&63):co<55296||co>57343?(to[so++]=224|co>>>12,to[so++]=128|co>>>6&63,to[so++]=128|co&63):io?(co=((io&1023)<<10)+(co&1023)+65536,to[so++]=240|co>>>18,to[so++]=128|co>>>12&63,to[so++]=128|co>>>6&63,to[so++]=128|co&63,io=0):io=co}so>=64&&(this._int32(ro),ro[0]=ro[16]),this._size+=so-ao}return this._sp=io,this}_int32(eo,to){let{A:ro,B:no,C:io,D:oo,E:ao,F:so,G:co,H:lo}=this,fo=0;for(to=to|0;fo<16;)W$5[fo++]=swap32(eo[to++]);for(fo=16;fo<64;fo++)W$5[fo]=gamma1(W$5[fo-2])+W$5[fo-7]+gamma0(W$5[fo-15])+W$5[fo-16]|0;for(fo=0;fo<64;fo++){const ho=lo+sigma1(ao)+ch(ao,so,co)+K$4[fo]+W$5[fo]|0,go=sigma0(ro)+maj(ro,no,io)|0;lo=co,co=so,so=ao,ao=oo+ho|0,oo=io,io=no,no=ro,ro=ho+go|0}this.A=ro+this.A|0,this.B=no+this.B|0,this.C=io+this.C|0,this.D=oo+this.D|0,this.E=ao+this.E|0,this.F=so+this.F|0,this.G=co+this.G|0,this.H=lo+this.H|0}digest(eo){const{_byte:to,_word:ro}=this;let no=this._size%64|0;for(to[no++]=128;no&3;)to[no++]=0;if(no>>=2,no>14){for(;no<16;)ro[no++]=0;no=0,this._int32(ro)}for(;no<16;)ro[no++]=0;const io=this._size*8,oo=(io&4294967295)>>>0,ao=(io-oo)/4294967296;return ao&&(ro[14]=swap32(ao)),oo&&(ro[15]=swap32(oo)),this._int32(ro),eo==="hex"?this._hex():this._bin()}_hex(){const{A:eo,B:to,C:ro,D:no,E:io,F:oo,G:ao,H:so}=this;return hex32(eo)+hex32(to)+hex32(ro)+hex32(no)+hex32(io)+hex32(oo)+hex32(ao)+hex32(so)}_bin(){const{A:eo,B:to,C:ro,D:no,E:io,F:oo,G:ao,H:so,_byte:co,_word:lo}=this;return lo[0]=swap32(eo),lo[1]=swap32(to),lo[2]=swap32(ro),lo[3]=swap32(no),lo[4]=swap32(io),lo[5]=swap32(oo),lo[6]=swap32(ao),lo[7]=swap32(so),co.slice(0,32)}};const W$5=new Int32Array(64);let sharedBuffer,sharedOffset=0;const hex32=Xr=>(Xr+4294967296).toString(16).substr(-8),swapLE=Xr=>Xr<<24&4278190080|Xr<<8&16711680|Xr>>8&65280|Xr>>24&255,swapBE=Xr=>Xr,swap32=isBE()?swapBE:swapLE,ch=(Xr,eo,to)=>to^Xr&(eo^to),maj=(Xr,eo,to)=>Xr&eo|to&(Xr|eo),sigma0=Xr=>(Xr>>>2|Xr<<30)^(Xr>>>13|Xr<<19)^(Xr>>>22|Xr<<10),sigma1=Xr=>(Xr>>>6|Xr<<26)^(Xr>>>11|Xr<<21)^(Xr>>>25|Xr<<7),gamma0=Xr=>(Xr>>>7|Xr<<25)^(Xr>>>18|Xr<<14)^Xr>>>3,gamma1=Xr=>(Xr>>>17|Xr<<15)^(Xr>>>19|Xr<<13)^Xr>>>10;function isBE(){return new Uint8Array(new Uint16Array([65279]).buffer)[0]===254}const stampHeaderName="X-Stamp-Webauthn",defaultTimeout=5*60*1e3,defaultUserVerification="preferred";class WebauthnStamper{constructor(eo){this.rpId=eo.rpId,this.timeout=eo.timeout||defaultTimeout,this.userVerification=eo.userVerification||defaultUserVerification,this.allowCredentials=eo.allowCredentials||[]}async stamp(eo){const to=getChallengeFromPayload(eo),ro={publicKey:{rpId:this.rpId,challenge:to,allowCredentials:this.allowCredentials,timeout:this.timeout,userVerification:this.userVerification}},io=(await get$3(ro)).toJSON(),oo={authenticatorData:io.response.authenticatorData,clientDataJson:io.response.clientDataJSON,credentialId:io.id,signature:io.response.signature};return{stampHeaderName,stampHeaderValue:JSON.stringify(oo)}}}function getChallengeFromPayload(Xr){const eo=createHash().update(Xr).digest("hex");return new TextEncoder().encode(eo)}var version$e="3.4.4";class WebauthnNotSupportedError extends Error{constructor(){super("Webauthn is not supported on this device")}}function __awaiter$d(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;function utf8StringToBuffer(Xr){return new TextEncoder().encode(Xr)}function bufferToBase64URLString(Xr){const eo=new Uint8Array(Xr);let to="";for(const no of eo)to+=String.fromCharCode(no);return btoa(to).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function base64URLStringToBuffer(Xr){const eo=Xr.replace(/-/g,"+").replace(/_/g,"/"),to=(4-eo.length%4)%4,ro=eo.padEnd(eo.length+to,"="),no=atob(ro),io=new ArrayBuffer(no.length),oo=new Uint8Array(io);for(let ao=0;aooo.type==="public-key").length===0?new WebAuthnError({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:Xr}):new WebAuthnError({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:Xr});if(Xr.name==="SecurityError"){const io=window.location.hostname;if(isValidDomain(io)){if(to.rp.id!==io)return new WebAuthnError({message:`The RP ID "${to.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:Xr})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:Xr})}else if(Xr.name==="TypeError"){if(to.user.id.byteLength<1||to.user.id.byteLength>64)return new WebAuthnError({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:Xr})}else if(Xr.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:Xr})}return Xr}class BaseWebAuthnAbortService{createNewAbortSignal(){if(this.controller){const to=new Error("Cancelling existing WebAuthn API call for new one");to.name="AbortError",this.controller.abort(to)}const eo=new AbortController;return this.controller=eo,eo.signal}cancelCeremony(){if(this.controller){const eo=new Error("Manually cancelling existing WebAuthn API call");eo.name="AbortError",this.controller.abort(eo),this.controller=void 0}}}const WebAuthnAbortService=new BaseWebAuthnAbortService,attachments=["cross-platform","platform"];function toAuthenticatorAttachment(Xr){if(Xr&&!(attachments.indexOf(Xr)<0))return Xr}async function startRegistration(Xr){var ho;if(!browserSupportsWebAuthn())throw new Error("WebAuthn is not supported in this browser");const to={publicKey:{...Xr,challenge:base64URLStringToBuffer(Xr.challenge),user:{...Xr.user,id:utf8StringToBuffer(Xr.user.id)},excludeCredentials:(ho=Xr.excludeCredentials)==null?void 0:ho.map(toPublicKeyCredentialDescriptor)}};to.signal=WebAuthnAbortService.createNewAbortSignal();let ro;try{ro=await navigator.credentials.create(to)}catch(go){throw identifyRegistrationError({error:go,options:to})}if(!ro)throw new Error("Registration was not completed");const{id:no,rawId:io,response:oo,type:ao}=ro;let so;typeof oo.getTransports=="function"&&(so=oo.getTransports());let co;if(typeof oo.getPublicKeyAlgorithm=="function")try{co=oo.getPublicKeyAlgorithm()}catch(go){warnOnBrokenImplementation("getPublicKeyAlgorithm()",go)}let lo;if(typeof oo.getPublicKey=="function")try{const go=oo.getPublicKey();go!==null&&(lo=bufferToBase64URLString(go))}catch(go){warnOnBrokenImplementation("getPublicKey()",go)}let fo;if(typeof oo.getAuthenticatorData=="function")try{fo=bufferToBase64URLString(oo.getAuthenticatorData())}catch(go){warnOnBrokenImplementation("getAuthenticatorData()",go)}return{id:no,rawId:bufferToBase64URLString(io),response:{attestationObject:bufferToBase64URLString(oo.attestationObject),clientDataJSON:bufferToBase64URLString(oo.clientDataJSON),transports:so,publicKeyAlgorithm:co,publicKey:lo,authenticatorData:fo},type:ao,clientExtensionResults:ro.getClientExtensionResults(),authenticatorAttachment:toAuthenticatorAttachment(ro.authenticatorAttachment)}}function warnOnBrokenImplementation(Xr,eo){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${Xr}. You should report this error to them. `,eo)}const logger$5=new Logger$2("Webauthn"),createWebauthnCredential=Xr=>__awaiter$d(void 0,void 0,void 0,function*(){if(!browserSupportsWebAuthn())throw new WebauthnNotSupportedError;let eo;try{eo=yield startRegistration(Xr)}catch(to){throw logger$5.debug("Failed to create webauthn credential",to),to}return eo}),convertTransportEnumToTurnkeyEnum=Xr=>{switch(Xr){case"internal":return"AUTHENTICATOR_TRANSPORT_INTERNAL";case"usb":return"AUTHENTICATOR_TRANSPORT_USB";case"nfc":return"AUTHENTICATOR_TRANSPORT_NFC";case"ble":return"AUTHENTICATOR_TRANSPORT_BLE";case"hybrid":return"AUTHENTICATOR_TRANSPORT_HYBRID";default:throw new Error("unsupported transport format "+Xr)}},getWebAuthnAttestationTurnkeyAdapter=Xr=>__awaiter$d(void 0,void 0,void 0,function*(){var eo,to;if(!Xr.publicKey)throw new Error("Invalid options. Public key attribute must be defined");const ro=Object.assign(Object.assign({},Xr.publicKey),{challenge:bufferSourceToString(Xr.publicKey.challenge),excludeCredentials:(eo=Xr.publicKey.excludeCredentials)===null||eo===void 0?void 0:eo.map(io=>Object.assign(Object.assign({},io),{id:bufferSourceToString(io.id)})),user:Object.assign(Object.assign({},Xr.publicKey.user),{id:bufferSourceToString(Xr.publicKey.user.id)})}),no=yield createWebauthnCredential(ro);return{attestationObject:no.response.attestationObject,clientDataJson:no.response.clientDataJSON,credentialId:no.rawId,transports:((to=no.response.transports)===null||to===void 0?void 0:to.map(convertTransportEnumToTurnkeyEnum))||[]}}),bufferSourceToString=Xr=>{if(Xr instanceof ArrayBuffer)return bufferToBase64URLString(Xr);{const eo=new Uint8Array(Xr.buffer,Xr.byteOffset,Xr.byteLength);return bufferToBase64URLString(eo)}};assertPackageVersion("@dynamic-labs/webauthn",version$e);const createTurnkeyPasskeyService=()=>({createWebauthnStamper:Xr=>new WebauthnStamper(Xr),getWebAuthnAttestation:getWebAuthnAttestationTurnkeyAdapter});var _a,_PasskeyService_implementation;class PasskeyService{static get implementation(){return __classPrivateFieldGet$3(_a,_a,"f",_PasskeyService_implementation)?__classPrivateFieldGet$3(_a,_a,"f",_PasskeyService_implementation):createTurnkeyPasskeyService()}static set implementation(eo){__classPrivateFieldSet$3(_a,_a,eo,"f",_PasskeyService_implementation)}static get getWebAuthnAttestation(){return _a.implementation.getWebAuthnAttestation}static get createWebauthnStamper(){return _a.implementation.createWebauthnStamper}}_a=PasskeyService;_PasskeyService_implementation={value:void 0};const turnkeyBaseUrl$1="https://api.turnkey.com",turnkeyPasskeyRecoveryUrl="https://recovery.turnkey.com",turnkeyEmailRecoveryUrl="https://auth.turnkey.com",TURNKEY_RECOVERY_CREDENTIAL_EXPIRATION_SECONDS=900,TURNKEY_SESSION_EXPIRATION_SECONDS=1800,EMAIL_AUTH_CREDENTIAL_TYPE="CREDENTIAL_TYPE_API_KEY_P256",PASSKEY_RECOVERY_CREDENTIAL_TYPE="CREDENTIAL_TYPE_RECOVER_USER_KEY_P256";class TurnkeyAuthenticatorRecoveryHandler{constructor(){this.isSessionActive=()=>!this.__createdAt||this.__recoveryType!=="email"?!1:this.isExpired(this.__createdAt,this.__sessionExpiration||TURNKEY_SESSION_EXPIRATION_SECONDS)?(this.clear(),!1):!0,this.isValidCode=eo=>__awaiter$e(this,void 0,void 0,function*(){var to,ro,no,io;if(!eo||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");const oo=yield(to=this.__client)===null||to===void 0?void 0:to.getUser({organizationId:eo,userId:this.__turnkeyRecoveryUserId}),ao={email:EMAIL_AUTH_CREDENTIAL_TYPE,passkey:PASSKEY_RECOVERY_CREDENTIAL_TYPE},so=(io=(no=(ro=oo==null?void 0:oo.user)===null||ro===void 0?void 0:ro.apiKeys)===null||no===void 0?void 0:no.filter(lo=>lo.credential.type===ao[this.__recoveryType]))===null||io===void 0?void 0:io.pop();return!so||this.isExpired(parseInt(so.createdAt.seconds,10),TURNKEY_RECOVERY_CREDENTIAL_EXPIRATION_SECONDS)?!1:(this.__createdAt=parseInt(so.createdAt.seconds,10),!0)}),this.isExpired=(eo,to)=>{const ro=eo+to,no=new Date(ro*1e3);return new Date>=no}}get publicKey(){return this.__publicKey}get client(){return this.__client}get recoveryType(){return this.__recoveryType}get recoveryUserId(){return this.__turnkeyRecoveryUserId||""}set recoveryUserId(eo){this.__turnkeyRecoveryUserId=eo}clear(){var eo;(eo=this.__iframeStamper)===null||eo===void 0||eo.clear(),this.__recoveryType=void 0,this.__iframeStamper=void 0,this.__publicKey=void 0,this.__client=void 0,this.__turnkeyRecoveryUserId=void 0,this.__createdAt=void 0}initRecovery(eo,to,ro,no){return __awaiter$e(this,void 0,void 0,function*(){this.__recoveryType&&this.clear(),this.__sessionExpiration=no,this.__recoveryType=eo;const io=eo==="passkey"?turnkeyPasskeyRecoveryUrl:turnkeyEmailRecoveryUrl;return this.__iframeStamper=new IframeStamper({iframeContainer:to,iframeElementId:ro,iframeUrl:io}),yield this.__iframeStamper.init(),this.__publicKey=this.__iframeStamper.publicKey(),this.__publicKey})}verifyRecoveryCode(eo,to){return __awaiter$e(this,void 0,void 0,function*(){if(!this.__iframeStamper)throw new DynamicError("Cannot proceed with your request");try{if(yield this.__iframeStamper.injectCredentialBundle(eo),this.__client=new TurnkeyClient({baseUrl:turnkeyBaseUrl$1},this.__iframeStamper),!to||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");if(!(yield this.isValidCode(to)))throw new DynamicError("The code is invalid or expired.")}catch(ro){throw logger$6.error("Error while verifying recovery code",ro),ro instanceof DynamicError?ro:new DynamicError("The code is invalid or expired.")}})}completeRecovery(eo){return __awaiter$e(this,arguments,void 0,function*({attestation:to,challenge:ro,turnkeySubOrganizationId:no}){if(!this.__client||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");try{return this.__client.recoverUser({organizationId:no,parameters:{authenticator:{attestation:to,authenticatorName:"Passkey",challenge:ro},userId:this.__turnkeyRecoveryUserId},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_RECOVER_USER"})}catch(io){throw logger$6.error("[TK] Error while completing recovery process",io),io}})}addPasskeyAuthenticator(eo){return __awaiter$e(this,arguments,void 0,function*({attestation:to,challenge:ro,turnkeySubOrganizationId:no}){if(!this.__client||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");try{return this.__client.createAuthenticators({organizationId:no,parameters:{authenticators:[{attestation:to,authenticatorName:"Passkey",challenge:ro}],userId:this.__turnkeyRecoveryUserId},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2"})}catch(io){throw logger$6.error("[TK] Error while creating new authenticator",io),io}})}addEmailRecovery(eo){return __awaiter$e(this,arguments,void 0,function*({organizationId:to,email:ro,turnkeyUserId:no}){let io=getTLD();io||(io=PlatformService.getHostname());const oo=PasskeyService.createWebauthnStamper({rpId:io}),ao=new TurnkeyClient({baseUrl:turnkeyBaseUrl$1},oo);try{return{signedRequest:yield ao.stampUpdateUser({organizationId:to,parameters:{userEmail:ro,userId:no,userTagIds:[]},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_UPDATE_USER"}),userId:no}}catch(so){throw logger$6.error("Error while adding email recovery",so),so}})}}const turnkeyAuthenticatorRecoveryHandler=new TurnkeyAuthenticatorRecoveryHandler,turnkeyBaseUrl="https://api.turnkey.com",turnkeyExportUrl="https://export.turnkey.com";class ExportHandler{get publicKey(){return this.__publicKey}clear(){var eo;(eo=this.__iframeStamper)===null||eo===void 0||eo.clear(),this.__iframeStamper=void 0,this.__publicKey=void 0,this.__turnkeyClient=void 0}initExport(eo,to){return __awaiter$e(this,void 0,void 0,function*(){if(this.__iframeStamper=new IframeStamper({iframeContainer:eo,iframeElementId:to,iframeUrl:turnkeyExportUrl}),yield this.__iframeStamper.init(),this.__publicKey=this.__iframeStamper.publicKey(),turnkeyAuthenticatorRecoveryHandler.isSessionActive())this.__turnkeyClient=turnkeyAuthenticatorRecoveryHandler.client;else{let ro=getTLD();ro||(ro=PlatformService.getHostname());const no=PasskeyService.createWebauthnStamper({rpId:ro}),io=ExportHandler==null?void 0:ExportHandler.apiKeyStamper,oo=io??no;this.__turnkeyClient=new TurnkeyClient({baseUrl:turnkeyBaseUrl},oo)}return this.__publicKey})}verifyExportWallet(eo){return __awaiter$e(this,arguments,void 0,function*({exportBundle:to,organizationId:ro}){if(!this.__iframeStamper)throw new DynamicError("Cannot proceed with your request");try{return yield this.__iframeStamper.injectWalletExportBundle(to,ro)}catch(no){throw logger$6.error("Error while verifying export wallet",no),no}})}verifyExportPrivateKey(eo){return __awaiter$e(this,arguments,void 0,function*({exportBundle:to,organizationId:ro,chain:no}){if(!this.__iframeStamper)throw new DynamicError("Cannot proceed with your request");const io=no==="solana"||no==="SOL"?KeyFormat.Solana:KeyFormat.Hexadecimal;try{return yield this.__iframeStamper.injectKeyExportBundle(to,ro,io)}catch(oo){throw logger$6.error("Error while verifying export private key",oo),oo}})}exportPrivateKey(eo){return __awaiter$e(this,arguments,void 0,function*({privateKeyId:to,organizationId:ro}){const no=ExportHandler==null?void 0:ExportHandler.apiKeyStamper;if(no&&(this.__turnkeyClient=new TurnkeyClient({baseUrl:turnkeyBaseUrl},no)),!this.__iframeStamper||!this.__publicKey||!this.__turnkeyClient||!to)throw new DynamicError("Cannot proceed with your request");try{return(yield this.__turnkeyClient.exportPrivateKey({organizationId:ro,parameters:{privateKeyId:to,targetPublicKey:this.__publicKey},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_EXPORT_PRIVATE_KEY"})).activity}catch(io){throw logger$6.error("[TK] Error while completing export private key process",io),io}})}exportWallet(eo){return __awaiter$e(this,arguments,void 0,function*({walletId:to,organizationId:ro,address:no}){const io=ExportHandler==null?void 0:ExportHandler.apiKeyStamper;if(io&&(this.__turnkeyClient=new TurnkeyClient({baseUrl:turnkeyBaseUrl},io)),!this.__iframeStamper||!this.__publicKey||!this.__turnkeyClient||!to)throw new DynamicError("Cannot proceed with your request");try{return no?(yield this.__turnkeyClient.exportWalletAccount({organizationId:ro,parameters:{address:no,targetPublicKey:this.__publicKey},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT"})).activity:(yield this.__turnkeyClient.exportWallet({organizationId:ro,parameters:{targetPublicKey:this.__publicKey,walletId:to},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_EXPORT_WALLET"})).activity}catch(oo){throw logger$6.error("[TK] Error while completing export wallet process",oo),oo}})}}class TurnkeyWalletConnectorBase extends WalletConnectorBase{constructor(eo,to){if(super(to),this.requiresNonDynamicEmailOtp=!1,this.isEmbeddedWallet=!0,this.removeSessionKeys=()=>__awaiter$e(this,void 0,void 0,function*(){TurnkeyWalletConnectorBase.sessionKeys=void 0,TurnkeyWalletConnectorBase.apiKeyStamper=void 0,ExportHandler.apiKeyStamper=void 0,typeof(this===null||this===void 0?void 0:this.removeSessionKeysFunction)=="function"&&this.removeSessionKeysFunction()}),!to.appName)throw new Error("appName not set");this.name=eo.name,this.overrideKey=eo.key,this.appName=to.appName,this.__authenticatorMethodHandler=turnkeyAuthenticatorRecoveryHandler,this.__exportHandler=new ExportHandler}getWebAuthnAttestation(){return __awaiter$e(this,void 0,void 0,function*(){const eo=generateRandomBuffer(),to=generateRandomBuffer(),{email:ro,passkeyIdentifier:no}=this;if(!ro&&!no)throw new Error("Email or passkeyIdentifier must be set to register a webauthn credential.");const io=ro||`${this.appName} - ${no}`,oo={publicKey:{authenticatorSelection:{authenticatorAttachment:void 0,requireResidentKey:!1,residentKey:"preferred",userVerification:"discouraged"},challenge:eo,pubKeyCredParams:[{alg:-7,type:"public-key"}],rp:{id:getTLD(),name:this.appName},user:{displayName:io,id:to,name:ro||`${this.appName} - ${no}`}}};let ao;try{ao=yield PasskeyService.getWebAuthnAttestation(oo)}catch(so){logger$6.warn(`Unable to register webauthn credential on the current page's TLD ${getTLD()}. Falling back to using hostname. ${PlatformService.getHostname()}`,so),oo.publicKey.rp.id=PlatformService.getHostname(),ao=yield PasskeyService.getWebAuthnAttestation(oo)}return{attestation:{attestationObject:ao.attestationObject,clientDataJson:ao.clientDataJson,credentialId:ao.credentialId,transports:convertAttestationTransports(ao.transports)},challenge:base64UrlEncode(eo),displayName:io}})}getAuthenticatorHandler(){return this.__authenticatorMethodHandler}getExportHandler(){return this.__exportHandler}get email(){return this._email}setEmail(eo){this._email=eo}get phone(){return this._phone}setPhone(eo){this._phone=eo}get passkeyIdentifier(){return this._passkeyIdentifier}setPasskeyIdentifier(eo){this._passkeyIdentifier=eo}clearEmail(){this._email=null}getAddress(){return __awaiter$e(this,void 0,void 0,function*(){var eo;return(eo=this.verifiedCredential)===null||eo===void 0?void 0:eo.address})}getConnectedAccounts(){return __awaiter$e(this,void 0,void 0,function*(){return(this.verifiedCredentials||[]).map(ro=>ro==null?void 0:ro.address).filter(ro=>typeof ro=="string")})}get turnkeyAddress(){var eo;const{address:to}=(eo=this.verifiedCredential)!==null&&eo!==void 0?eo:{};return to}get walletProperties(){const{walletProperties:eo}=this.verifiedCredential||{};return eo}set verifiedCredentials(eo){this._verifiedCredentials=eo}get verifiedCredentials(){return this._verifiedCredentials}set verifiedCredential(eo){this._verifiedCredential=eo}get verifiedCredential(){return this._verifiedCredential}setSessionKeyFetcher(eo){this.createOrRestoreSessionFetcherFunction=eo}setSessionKeyRemoveFunction(eo){this.removeSessionKeysFunction=eo}createOrRestoreSession(){return __awaiter$e(this,arguments,void 0,function*({ignoreRestore:eo}={}){if(!this.isSessionKeyCompatible()||TurnkeyWalletConnectorBase.isLoadingSession)return;if(!this.createOrRestoreSessionFetcherFunction)throw new DynamicError("Cannot register session key to init provider");const{sessionKeys:to}=TurnkeyWalletConnectorBase;if(to!=null&&to.publicKey&&!(new Date>=new Date(to.expirationDate)))return to.publicKey;try{TurnkeyWalletConnectorBase.isLoadingSession=!0;const ro=yield this.createOrRestoreSessionFetcherFunction({ignoreRestore:eo});return TurnkeyWalletConnectorBase.sessionKeys=ro,TurnkeyWalletConnectorBase.apiKeyStamper=new ApiKeyStamper({apiPrivateKey:ro.privateKey,apiPublicKey:ro.publicKey}),ExportHandler.apiKeyStamper=TurnkeyWalletConnectorBase.apiKeyStamper,logger$6.setMetaData("sessionApiPublicKey",ro.publicKey),ro.publicKey}catch{throw new DynamicError("Failed to create or restore session")}finally{TurnkeyWalletConnectorBase.isLoadingSession=!1}})}isSessionKeyCompatible(){var eo;const to=(eo=this.verifiedCredential)===null||eo===void 0?void 0:eo.walletProperties;return!!(to==null?void 0:to.isSessionKeyCompatible)}isSessionActive(){return __awaiter$e(this,void 0,void 0,function*(){return!!((yield this.getAddress())&&TurnkeyWalletConnectorBase.sessionKeys&&TurnkeyWalletConnectorBase.apiKeyStamper)})}get sessionKeys(){return TurnkeyWalletConnectorBase.sessionKeys}setLoggerMetadata(){var eo,to,ro;logger$6.setMetaData("turnkeySubOrganizationId",(to=(eo=this._verifiedCredential)===null||eo===void 0?void 0:eo.walletProperties)===null||to===void 0?void 0:to.turnkeySubOrganizationId),logger$6.setMetaData("walletId",(ro=this._verifiedCredential)===null||ro===void 0?void 0:ro.id);let no="Unknown";this.isSessionKeyCompatible()?no="SessionKeys":this.__authenticatorMethodHandler.recoveryType==="passkey"?no="Passkey":this.__authenticatorMethodHandler.recoveryType==="email"&&(no="EmailAuth"),logger$6.setMetaData("authMethod",no)}}TurnkeyWalletConnectorBase.isLoadingSession=!1;const TurnkeyWalletConnectorInfo={Turnkey:{key:"turnkey",name:"Turnkey"},TurnkeyHD:{key:"turnkeyhd",name:"Turnkey HD"}},findTurnkeyVerifiedCredentials=(Xr,eo)=>Xr==null?void 0:Xr.filter(({walletName:to,chain:ro})=>(to==null?void 0:to.startsWith("turnkey"))&&eo===ro),findTurnkeyVerifiedCredentialsWithSmartWalletRef=(Xr,eo)=>Xr==null?void 0:Xr.reduce((to,ro)=>{var no;if(!((no=ro.walletName)===null||no===void 0)&&no.startsWith("turnkey")&&eo===ro.chain){const io=Xr.find(so=>so.signerRefId===ro.id),oo=io==null?void 0:io.id,ao=io==null?void 0:io.address;to.push(Object.assign(Object.assign({},ro),{smartWalletRefAddress:ao,smartWalletRefId:oo}))}return to},[]);assertPackageVersion("@dynamic-labs/embedded-wallet",version$f);function __awaiter$c(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;async function createAccount(Xr){var io;const{client:eo,organizationId:to,signWith:ro}=Xr;let{ethereumAddress:no}=Xr;if(!ro)throw new TurnkeyActivityError({message:"Missing signWith parameter"});if(isAddress(ro))no=ro;else if(!no&&(no=(io=(await eo.getPrivateKey({privateKeyId:ro,organizationId:to})).privateKey.addresses.find(ao=>ao.format==="ADDRESS_FORMAT_ETHEREUM"))==null?void 0:io.address,typeof no!="string"||!no))throw new TurnkeyActivityError({message:`Unable to find Ethereum address for key ${ro} under organization ${to}`});return toAccount({address:no,signMessage:function({message:oo}){return signMessage(eo,oo,to,ro)},signTransaction:function(oo,ao){const so=ao!=null&&ao.serializer?ao.serializer:serializeTransaction$4;return signTransaction(eo,oo,so,to,ro)},signTypedData:function(oo){return signTypedData(eo,oo,to,ro)}})}async function signMessage(Xr,eo,to,ro){const no=hashMessage(eo);return`${await signMessageWithErrorWrapping(Xr,no,to,ro)}`}async function signTransaction(Xr,eo,to,ro,no){const oo=to(eo).replace(/^0x/,"");return await signTransactionWithErrorWrapping(Xr,oo,ro,no)}async function signTypedData(Xr,eo,to,ro){const no=hashTypedData(eo);return await signMessageWithErrorWrapping(Xr,no,to,ro)}async function signTransactionWithErrorWrapping(Xr,eo,to,ro){let no;try{no=await signTransactionImpl(Xr,eo,to,ro)}catch(io){throw io instanceof TurnkeyActivityError?io:new TurnkeyActivityError({message:`Failed to sign transaction: ${io.message}`,cause:io})}return`0x${no}`}async function signTransactionImpl(Xr,eo,to,ro){var no,io;if(Xr instanceof TurnkeyClient){const{activity:oo}=await Xr.signTransaction({type:"ACTIVITY_TYPE_SIGN_TRANSACTION_V2",organizationId:to,parameters:{signWith:ro,type:"TRANSACTION_TYPE_ETHEREUM",unsignedTransaction:eo},timestampMs:String(Date.now())}),{id:ao,status:so,type:co}=oo;if(oo.status!=="ACTIVITY_STATUS_COMPLETED")throw new TurnkeyActivityError({message:`Invalid activity status: ${oo.status}`,activityId:ao,activityStatus:so,activityType:co});return assertNonNull((io=(no=oo==null?void 0:oo.result)==null?void 0:no.signTransactionResult)==null?void 0:io.signedTransaction)}else{const oo=await Xr.signTransaction({signWith:ro,type:"TRANSACTION_TYPE_ETHEREUM",unsignedTransaction:eo});return assertNonNull(oo==null?void 0:oo.signedTransaction)}}async function signMessageWithErrorWrapping(Xr,eo,to,ro){let no;try{no=await signMessageImpl(Xr,eo,to,ro)}catch(io){throw io instanceof TurnkeyActivityError?io:new TurnkeyActivityError({message:`Failed to sign: ${io.message}`,cause:io})}return no}async function signMessageImpl(Xr,eo,to,ro){var oo;let no;if(Xr instanceof TurnkeyClient){const{activity:ao}=await Xr.signRawPayload({type:"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",organizationId:to,parameters:{signWith:ro,payload:eo,encoding:"PAYLOAD_ENCODING_HEXADECIMAL",hashFunction:"HASH_FUNCTION_NO_OP"},timestampMs:String(Date.now())}),{id:so,status:co,type:lo}=ao;if(co!=="ACTIVITY_STATUS_COMPLETED")throw new TurnkeyActivityError({message:`Invalid activity status: ${ao.status}`,activityId:so,activityStatus:co,activityType:lo});no=assertNonNull((oo=ao==null?void 0:ao.result)==null?void 0:oo.signRawPayloadResult)}else no=await Xr.signRawPayload({signWith:ro,payload:eo,encoding:"PAYLOAD_ENCODING_HEXADECIMAL",hashFunction:"HASH_FUNCTION_NO_OP"});let io=serializeSignature({r:`0x${no.r}`,s:`0x${no.s}`,v:no.v==="00"?27n:28n});return assertNonNull(io)}function assertNonNull(Xr){if(Xr==null)throw new Error(`Got unexpected ${JSON.stringify(Xr)}`);return Xr}var version$d="3.4.4";function __awaiter$b(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,eo||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const logger$4=new Logger$2("ethereum-core"),gasPriceOracleAbiAddress="0x420000000000000000000000000000000000000F",gasPriceOracleAbi=[{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],estimateL1Fee$1=(Xr,eo)=>__awaiter$b(void 0,void 0,void 0,function*(){const to=serializeTransaction$4(Object.assign(Object.assign({chainId:Xr.chain.id},eo),{type:eo.type?eo.type:"eip1559"}));return Xr.readContract({abi:gasPriceOracleAbi,address:gasPriceOracleAbiAddress,args:[to],functionName:"getL1Fee"})}),opStackSupportedChains=[optimism.id,optimismGoerli.id,optimismSepolia.id,base$6.id,baseGoerli.id,baseSepolia$1.id],chainsMap=Object.values(viemChains).reduce((Xr,eo)=>Object.assign(Object.assign({},Xr),{[eo.id]:eo}),{}),erc20Abi=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}];class Eip1559FeeFeed{constructor({publicClient:eo,initialGasLimit:to,initialMaxFeePerGas:ro}){this.fee={gas:BigInt(0)},this.publicClient=eo,this.initialGasLimit=to,this.initialMaxFeePerGas=ro}fetchFee(){return __awaiter$b(this,void 0,void 0,function*(){try{const eo=yield this.estimateL1Fee();if(this.initialGasLimit&&this.initialMaxFeePerGas){this.fee.gas=this.initialGasLimit*this.initialMaxFeePerGas+eo;return}const to=yield this.estimateGas();if(this.initialMaxFeePerGas){this.fee.gas=to*this.initialMaxFeePerGas+eo;return}const ro=yield this.publicClient.estimateFeesPerGas();if(!ro||!ro.maxFeePerGas)return;this.fee.gas=to*ro.maxFeePerGas+eo,this.maxFeePerGas=ro.maxFeePerGas,this.maxPriorityFeePerGas=ro.maxPriorityFeePerGas}catch(eo){logger$4.debug(eo);return}})}}const estimateL1Fee=(Xr,eo)=>__awaiter$b(void 0,void 0,void 0,function*(){const{chain:to}=Xr;if(!to)throw new Error("Chain is not defined");const ro=Xr;if(opStackSupportedChains.includes(to.id))return estimateL1Fee$1(ro,eo);throw new Error("Chain is not supported")}),estimateL1FeeSupportedChains=[...opStackSupportedChains],isL1FeeSupportedByChain=Xr=>estimateL1FeeSupportedChains.includes(Xr),validateAddressFormat=Xr=>/^0x[0-9a-fA-F]{40}$/.test(Xr),parseEther=Xr=>parseEther$1(Xr,"wei"),formatEther=(Xr,{precision:eo}={})=>formatNumberText(formatEther$1(Xr),{precision:eo});class ViemUiTransaction extends Eip1559FeeFeed{constructor({transaction:eo,onSubmit:to,publicClient:ro,account:no}){super({initialGasLimit:eo.gas,initialMaxFeePerGas:eo.maxFeePerGas,publicClient:ro}),this.chain="EVM",this.validateAddressFormat=validateAddressFormat,this.parse=parseEther,this.parseNonNativeToken=(io,oo)=>parseUnits(io,oo),this.format=formatEther,this.formatNonNativeToken=(io,oo)=>formatUnits(io,oo),this.transaction=eo,this.onSubmit=to,this.publicClient=ro,this.address=no}get to(){return this.transaction.to||void 0}set to(eo){this.transaction.to=eo}get from(){return this.address}get value(){return this.transaction.value}set value(eo){this.transaction.value=eo}get nonNativeValue(){return this.transaction.nonNativeValue}set nonNativeValue(eo){this.transaction.nonNativeValue=eo}get nonNativeAddress(){return this.transaction.nonNativeAddress}set nonNativeAddress(eo){this.transaction.nonNativeAddress=eo}get nonNativeDecimal(){return this.transaction.nonNativeDecimal}set nonNativeDecimal(eo){this.transaction.nonNativeDecimal=eo}get data(){return this.transaction.data}submit(){return __awaiter$b(this,void 0,void 0,function*(){return this.onSubmit(this.transaction).catch(eo=>{throw eo instanceof UserRejectedTransactionError?new TransactionExecutionError(new BaseError(eo.message),this.transaction):eo})})}getBalance(){return this.publicClient.getBalance({address:this.address})}estimateGas(){return __awaiter$b(this,void 0,void 0,function*(){const eo=yield this.publicClient.transport.request({method:"eth_estimateGas",params:[{data:this.data,to:this.to,value:this.convertBigIntToHex(this.value)}]});return hexToBigInt(eo)})}convertBigIntToHex(eo){return eo?toHex$1(eo):void 0}estimateL1Fee(){return __awaiter$b(this,void 0,void 0,function*(){var eo;return isL1FeeSupportedByChain(((eo=this.publicClient.chain)===null||eo===void 0?void 0:eo.id)||0)?estimateL1Fee(this.publicClient,{data:this.transaction.data,to:this.transaction.to,value:this.transaction.value}):BigInt(0)})}set maxFeePerGas(eo){this.transaction.maxFeePerGas=eo}set maxPriorityFeePerGas(eo){this.transaction.maxPriorityFeePerGas=eo}}const createViemUiTransaction=Xr=>__awaiter$b(void 0,[Xr],void 0,function*({from:eo,publicClient:to,walletClient:ro}){return new ViemUiTransaction({account:eo,onSubmit:no=>__awaiter$b(void 0,void 0,void 0,function*(){return no.nonNativeAddress?ro.writeContract({abi:erc20Abi,account:eo,address:no.nonNativeAddress,args:[no.to,no.nonNativeValue],functionName:"transfer",maxFeePerGas:no.maxFeePerGas,maxPriorityFeePerGas:no.maxPriorityFeePerGas}):ro.sendTransaction({account:eo,maxFeePerGas:no.maxFeePerGas,maxPriorityFeePerGas:no.maxPriorityFeePerGas,to:no.to,value:no.value})}),publicClient:to,transaction:{}})}),getChain=Xr=>{for(const eo of Object.values(viemChains))if("id"in eo&&eo.id===Xr)return eo;throw new Error(`Chain with id ${Xr} not found`)},mapChain=Xr=>{var eo;return{blockExplorers:!((eo=Xr.blockExplorerUrls)===null||eo===void 0)&&eo[0]?{default:{name:Xr.blockExplorerUrls[0],url:Xr.blockExplorerUrls[0]}}:void 0,id:Xr.chainId,name:Xr.vanityName||Xr.name||Xr.chainName,nativeCurrency:Xr.nativeCurrency,rpcUrls:{default:{http:Xr.rpcUrls},public:{http:Xr.rpcUrls}}}},getOrMapViemChain=Xr=>{let eo;try{eo=getChain(Xr.chainId)}catch{logger$4.debug(`Chain with id ${Xr.chainId} not found in viem's chains`)}const to=mapChain(Xr);return eo?Object.assign(Object.assign({},eo),to):to},findEvmNetwork=({chainId:Xr,name:eo,networks:to})=>{if(!(!Xr&&!eo))return Xr&&eo?to.find(ro=>ro.chainId===Xr&&ro.name===eo):Xr?to.find(ro=>ro.chainId===Xr):to.find(ro=>ro.name===eo)};var L2ResolverAbi=[{inputs:[{internalType:"contract ENS",name:"ens_",type:"address"},{internalType:"address",name:"registrarController_",type:"address"},{internalType:"address",name:"reverseRegistrar_",type:"address"},{internalType:"address",name:"owner_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AlreadyInitialized",type:"error"},{inputs:[],name:"CantSetSelfAsDelegate",type:"error"},{inputs:[],name:"CantSetSelfAsOperator",type:"error"},{inputs:[],name:"NewOwnerIsZeroAddress",type:"error"},{inputs:[],name:"NoHandoverRequest",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"uint256",name:"contentType",type:"uint256"}],name:"ABIChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"address",name:"a",type:"address"}],name:"AddrChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"coinType",type:"uint256"},{indexed:!1,internalType:"bytes",name:"newAddress",type:"bytes"}],name:"AddressChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"address",name:"delegate",type:"address"},{indexed:!0,internalType:"bool",name:"approved",type:"bool"}],name:"Approved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"hash",type:"bytes"}],name:"ContenthashChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"name",type:"bytes"},{indexed:!1,internalType:"uint16",name:"resource",type:"uint16"},{indexed:!1,internalType:"bytes",name:"record",type:"bytes"}],name:"DNSRecordChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"name",type:"bytes"},{indexed:!1,internalType:"uint16",name:"resource",type:"uint16"}],name:"DNSRecordDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"lastzonehash",type:"bytes"},{indexed:!1,internalType:"bytes",name:"zonehash",type:"bytes"}],name:"DNSZonehashChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"bytes4",name:"interfaceID",type:"bytes4"},{indexed:!1,internalType:"address",name:"implementer",type:"address"}],name:"InterfaceChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"string",name:"name",type:"string"}],name:"NameChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"pendingOwner",type:"address"}],name:"OwnershipHandoverCanceled",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"pendingOwner",type:"address"}],name:"OwnershipHandoverRequested",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"oldOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"x",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"y",type:"bytes32"}],name:"PubkeyChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newRegistrarController",type:"address"}],name:"RegistrarControllerUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newReverseRegistrar",type:"address"}],name:"ReverseRegistrarUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"string",name:"indexedKey",type:"string"},{indexed:!1,internalType:"string",name:"key",type:"string"},{indexed:!1,internalType:"string",name:"value",type:"string"}],name:"TextChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"uint64",name:"newVersion",type:"uint64"}],name:"VersionChanged",type:"event"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"contentTypes",type:"uint256"}],name:"ABI",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"addr",outputs:[{internalType:"address payable",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"coinType",type:"uint256"}],name:"addr",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"address",name:"delegate",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cancelOwnershipHandover",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"clearRecords",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"pendingOwner",type:"address"}],name:"completeOwnershipHandover",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"contenthash",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes32",name:"name",type:"bytes32"},{internalType:"uint16",name:"resource",type:"uint16"}],name:"dnsRecord",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"ens",outputs:[{internalType:"contract ENS",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes32",name:"name",type:"bytes32"}],name:"hasDNSRecords",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes4",name:"interfaceID",type:"bytes4"}],name:"interfaceImplementer",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"address",name:"delegate",type:"address"}],name:"isApprovedFor",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes[]",name:"data",type:"bytes[]"}],name:"multicall",outputs:[{internalType:"bytes[]",name:"results",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"nodehash",type:"bytes32"},{internalType:"bytes[]",name:"data",type:"bytes[]"}],name:"multicallWithNodeCheck",outputs:[{internalType:"bytes[]",name:"results",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"pendingOwner",type:"address"}],name:"ownershipHandoverExpiresAt",outputs:[{internalType:"uint256",name:"result",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"pubkey",outputs:[{internalType:"bytes32",name:"x",type:"bytes32"},{internalType:"bytes32",name:"y",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"recordVersions",outputs:[{internalType:"uint64",name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"registrarController",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"requestOwnershipHandover",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes",name:"",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"}],name:"resolve",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"reverseRegistrar",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"contentType",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"setABI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"coinType",type:"uint256"},{internalType:"bytes",name:"a",type:"bytes"}],name:"setAddr",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"address",name:"a",type:"address"}],name:"setAddr",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes",name:"hash",type:"bytes"}],name:"setContenthash",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes",name:"data",type:"bytes"}],name:"setDNSRecords",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes4",name:"interfaceID",type:"bytes4"},{internalType:"address",name:"implementer",type:"address"}],name:"setInterface",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"string",name:"newName",type:"string"}],name:"setName",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes32",name:"x",type:"bytes32"},{internalType:"bytes32",name:"y",type:"bytes32"}],name:"setPubkey",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"registrarController_",type:"address"}],name:"setRegistrarController",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"reverseRegistrar_",type:"address"}],name:"setReverseRegistrar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"string",name:"key",type:"string"},{internalType:"string",name:"value",type:"string"}],name:"setText",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes",name:"hash",type:"bytes"}],name:"setZonehash",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceID",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"string",name:"key",type:"string"}],name:"text",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"zonehash",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"}];const getNameservice=Xr=>__awaiter$b(void 0,[Xr],void 0,function*({rpcProvider:eo,address:to}){const ro={avatar:void 0,name:void 0},no=yield eo.getChainId();if(!no)return ro;const io=(ao,so)=>{const co=ao.toLocaleLowerCase(),lo=keccak256(co.substring(2)),fo=oo(so),ho=namehash(`${fo.toLocaleUpperCase()}.reverse`);return keccak256(encodePacked(["bytes32","bytes32"],[ho,lo]))},oo=ao=>((2147483648|ao)>>>0).toString(16).toLocaleUpperCase();if(no===8453){const ao=io(to,8453);try{const so=yield eo.readContract({abi:L2ResolverAbi,address:"0xC6d566A56A1aFf6508b41f6c90ff131615583BCD",args:[ao],functionName:"name"});if(so)return ro.name=so,ro}catch{return ro}}else ro.name=yield eo.getEnsName({address:to}),ro.avatar=ro.name?yield eo.getEnsAvatar({name:ro.name}):void 0;return ro}),isTransactionExecutionError=Xr=>Xr!=null&&typeof Xr=="object"&&"walk"in Xr&&typeof Xr.walk=="function",interceptTransport=({getAccounts:Xr,onPersonalSign:eo,onSendTransaction:to,onSignTypedData:ro,transport:no})=>io=>{const oo=no(io);return custom$1({request:ao=>__awaiter$b(void 0,void 0,void 0,function*(){var so;const{method:co,params:lo}=ao;if(Xr&&co==="eth_accounts")return Xr({provider:oo});if(eo&&co==="personal_sign"){const[fo]=lo;return eo({args:ao,message:fo,provider:oo}).catch(ho=>{throw ho instanceof UserRejectedRequestError?new UserRejectedRequestError$1(ho):ho})}if(to&&co==="eth_sendTransaction"){const[fo]=lo;return to({args:ao,provider:oo,transaction:fo}).catch(ho=>{throw isTransactionExecutionError(ho)&&ho.walk()instanceof UserRejectedTransactionError?new UserRejectedRequestError$1(ho.walk()):ho instanceof UserRejectedRequestError?new UserRejectedRequestError$1(ho):ho})}if(ro&&co==="eth_signTypedData_v4"){const[,fo]=(so=lo)!==null&&so!==void 0?so:[];return ro({args:ao,message:fo,provider:oo}).catch(ho=>{throw ho instanceof UserRejectedRequestError?new UserRejectedRequestError$1(ho):ho})}return oo.request(ao)})})(io)};class EthereumWallet extends Wallet$1{getPublicClient(){return __awaiter$b(this,void 0,void 0,function*(){const eo=yield this._connector.getPublicClient();if(!eo)throw new Error("Unable to retrieve PublicClient");return eo})}getWalletClient(eo){return __awaiter$b(this,void 0,void 0,function*(){const to=this._connector.getWalletClient(eo);if(!to)throw new Error("Unable to retrieve WalletClient");return createWalletClient({account:this.address,chain:to.chain,transport:interceptTransport({onPersonalSign:ro=>__awaiter$b(this,[ro],void 0,function*({provider:no,args:io}){return yield this.sync(),no.request(io)}),onSendTransaction:ro=>__awaiter$b(this,[ro],void 0,function*({provider:no,args:io}){return yield this.sync(),no.request(io)}),onSignTypedData:ro=>__awaiter$b(this,[ro],void 0,function*({provider:no,args:io}){return yield this.sync(),no.request(io)}),transport:custom$1(to.transport)})})})}}class EthWalletConnector extends WalletConnectorBase{getPublicClient(){return __awaiter$b(this,void 0,void 0,function*(){var eo,to;const ro=(eo=yield this.getNetwork())!==null&&eo!==void 0?eo:1;if(this.evmNetworks.length===0)return;const no={cosmos:[],evm:this.evmNetworks,solana:[],starknet:void 0};if(!this.chainRpcProviders)return;const io=this.chainRpcProviders.getProviders(no);return(to=this.chainRpcProviders.getEvmProviderByChainId(io,ro))===null||to===void 0?void 0:to.provider})}constructor(eo){var to;super(eo),this.ChainWallet=EthereumWallet,this.evmNetworkRpcMap=()=>this.evmNetworks.reduce((ro,no)=>{var io;return[ro[no.chainId]]=!((io=no==null?void 0:no.privateCustomerRpcUrls)===null||io===void 0)&&io.length?no.privateCustomerRpcUrls:no.rpcUrls,ro},{}),this.evmNetworks=parseEvmNetworks(eo.evmNetworks),this.chainRpcProviders=eo.chainRpcProviders,(to=this.chainRpcProviders)===null||to===void 0||to.registerEvmProviders()}getNetwork(){return __awaiter$b(this,void 0,void 0,function*(){const eo=this.getWalletClient();if(!this.supportsNetworkSwitching||!eo)return Promise.resolve(void 0);const to=yield retryableFn(eo.getChainId,{fallbackValue:FALLBACK_UNDEFINED,timeoutMs:1e3});return this.setActiveChain(chainsMap[to]),to})}getNameService(eo){return __awaiter$b(this,void 0,void 0,function*(){const to=yield this.getPublicClient();if(to)return getNameservice({address:eo,rpcProvider:to})})}isTestnet(){return __awaiter$b(this,void 0,void 0,function*(){var eo,to,ro;return(ro=(to=(eo=yield this.getPublicClient())===null||eo===void 0?void 0:eo.chain)===null||to===void 0?void 0:to.testnet)!==null&&ro!==void 0?ro:!1})}parseAddress(eo){try{return getAddress$1(eo)}catch(to){logger$9.debug(`Failed to parse EVM address into EIP55 format: error getting checksum, returning default ${eo}`,to)}return eo}getSigner(){return __awaiter$b(this,void 0,void 0,function*(){return this.getWalletClient()})}getBalance(eo){return __awaiter$b(this,void 0,void 0,function*(){const to=yield this.getPublicClient(),ro=yield to==null?void 0:to.getBalance({address:eo});if(!(!ro&&ro!==BigInt(0)))return formatEther$1(ro)})}supportsNetworkSwitching(){return!0}switchNetwork(eo){return __awaiter$b(this,arguments,void 0,function*({networkName:to,networkChainId:ro}){const no=findEvmNetwork({chainId:ro,name:to,networks:this.evmNetworks});if(!no)throw new DynamicError(`Could not find network mapping for chain ${to||ro}`);if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching is not supported");const io=this.getWalletClient();if(!io)throw new DynamicError("Provider not found");return this.providerSwitchNetwork({network:no,provider:io})})}chooseAccountsToConnect(){return __awaiter$b(this,void 0,void 0,function*(){var eo,to,ro;const no=this.getWalletClient();if(!no)return[];try{const io=yield no.requestPermissions({eth_accounts:{}});logger$9.debug("chooseAccountsToConnect - requestPermissions result",io);const oo=(ro=(to=(eo=io==null?void 0:io.find(ao=>ao.parentCapability==="eth_accounts"))===null||eo===void 0?void 0:eo.caveats)===null||to===void 0?void 0:to[0])===null||ro===void 0?void 0:ro.value;return typeof oo=="string"?[oo]:Array.isArray(oo)?oo:[]}catch(io){if(logger$9.debug("chooseAccountsToConnect - error",io),io.code===4001)throw new UserRejectedRequestError}return[]})}getConnectedAccounts(){return __awaiter$b(this,void 0,void 0,function*(){const eo=this.getWalletClient();if(!eo)return[];const to=yield retryableFn(eo.getAddresses,{fallbackValue:[],timeoutMs:500});return to.length&&this.setActiveAccount(to[0]),to})}providerSwitchNetwork(eo){return __awaiter$b(this,arguments,void 0,function*({network:to,provider:ro}){var no,io,oo,ao;const{chainId:so}=to,co=yield this.getNetwork();if(!(co&&co===so))try{if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching is not supported");const lo=getOrMapViemChain(to);if(yield ro.switchChain(lo),this.key==="magiceden"){const fo=yield ro.getChainId();this.emit("chainChange",{chain:fo.toString()})}else this.setActiveChain(lo)}catch(lo){if(lo.code===4902||!((no=lo.message)===null||no===void 0)&&no.includes("Unrecognized chain")||((oo=(io=lo.data)===null||io===void 0?void 0:io.orginalError)===null||oo===void 0?void 0:oo.code)===4902)return this.providerAddNetwork({network:to,provider:ro});throw!((ao=lo.message)===null||ao===void 0)&&ao.includes("rejected")||typeof lo=="string"&&lo.includes("rejected")?new DynamicError("User rejected the wallet's request to switch network"):lo}})}providerAddNetwork(eo){return __awaiter$b(this,arguments,void 0,function*({network:to,provider:ro}){var no;try{return yield ro.addChain({chain:getOrMapViemChain(to)})}catch(io){throw!((no=io.message)===null||no===void 0)&&no.includes("rejected")||typeof io=="string"&&io.includes("rejected")?new DynamicError("User rejected the wallet's request to add network"):io}})}setActiveAccount(eo){this.activeAccount=eo?toAccount(eo):void 0}getActiveAccount(){return this.activeAccount}setActiveChain(eo){this.activeChain=eo}getActiveChain(){return this.activeChain}createUiTransaction(eo){return __awaiter$b(this,void 0,void 0,function*(){yield this.validateActiveWallet(eo);const to=yield this.getWalletClient(),ro=yield this.getPublicClient();if(!ro||!to)throw new DynamicError("No public client available");return createViemUiTransaction({from:eo,publicClient:ro,walletClient:to})})}confirmTransactionStatus(eo){return __awaiter$b(this,void 0,void 0,function*(){const to=yield this.getPublicClient();if(!to)throw new DynamicError("No public client available");return to.waitForTransactionReceipt({confirmations:3,hash:eo})})}}ChainRpcProviders.getEvmProviderByChainId=(Xr,eo)=>{var to;return(to=Xr.evm)===null||to===void 0?void 0:to.find(no=>no.chainId===eo)};ChainRpcProviders.registerEvmProviders=()=>{ChainRpcProviders.registerChainProviders(ProviderChain.EVM,Xr=>{const eo={};return Xr!=null&&Xr.evm&&(eo.evm=parseEvmNetworks(Xr.evm).map(to=>{var ro;const no=((ro=to.privateCustomerRpcUrls)===null||ro===void 0?void 0:ro[0])||to.rpcUrls[0],io=createPublicClient({chain:getOrMapViemChain(to),transport:http(no)});return{chainId:to.chainId,chainName:to.name,provider:io}})),eo.evm})};const unFormatTransaction=Xr=>Object.assign(Object.assign({},Xr),{gas:typeof Xr.gas<"u"?hexToBigInt(Xr.gas):void 0,gasPrice:typeof Xr.gasPrice<"u"?hexToBigInt(Xr.gasPrice):void 0,maxFeePerGas:typeof Xr.maxFeePerGas<"u"?hexToBigInt(Xr.maxFeePerGas):void 0,maxPriorityFeePerGas:typeof Xr.maxPriorityFeePerGas<"u"?hexToBigInt(Xr.maxPriorityFeePerGas):void 0,nonce:typeof Xr.nonce<"u"?hexToBigInt(Xr.nonce):void 0,value:typeof Xr.value<"u"?hexToBigInt(Xr.value):void 0}),createAccountWithUiConfirmation=({address:Xr,account:eo,provider:to,walletConnector:ro,walletUiUtils:no})=>toAccount({address:Xr,signMessage:(...io)=>__awaiter$b(void 0,void 0,void 0,function*(){return no.signMessage({handler:()=>__awaiter$b(void 0,void 0,void 0,function*(){return(yield eo()).signMessage(...io)}),message:(()=>{var oo;const ao=(oo=io[0])===null||oo===void 0?void 0:oo.message;return ao&&!(typeof ao=="string"&&Array.isArray(ao))?JSON.stringify(ao):ao==null?void 0:ao.toString()})(),walletConnector:ro})}),signTransaction:(...io)=>__awaiter$b(void 0,void 0,void 0,function*(){const oo=new ViemUiTransaction({account:Xr,onSubmit:ao=>__awaiter$b(void 0,void 0,void 0,function*(){return(yield eo()).signTransaction(ao)}),publicClient:to,transaction:io[0]});return no.sendTransaction(ro,oo)}),signTypedData:(...io)=>no.signMessage({handler:()=>__awaiter$b(void 0,void 0,void 0,function*(){return(yield eo()).signTypedData(...io)}),message:JSON.stringify(io[0]),walletConnector:ro})}),createWalletClientWithUiConfirmation=({address:Xr,account:eo,chain:to,transport:ro,walletConnector:no,walletUiUtils:io})=>{let oo=null;const ao=createPublicClient({chain:to,transport:ro}),so=createAccountWithUiConfirmation({account:eo,address:Xr,provider:ao,walletConnector:no,walletUiUtils:io}),co=interceptTransport({getAccounts:()=>__awaiter$b(void 0,void 0,void 0,function*(){return[Xr]}),onPersonalSign:lo=>__awaiter$b(void 0,[lo],void 0,function*({message:fo}){if(!oo)throw new Error("Client not initialized");return oo.signMessage({message:{raw:fo}})}),onSendTransaction:lo=>__awaiter$b(void 0,[lo],void 0,function*({transaction:fo}){if(!oo)throw new Error("Client not initialized");const ho=unFormatTransaction(fo);return oo.sendTransaction(ho)}),onSignTypedData:lo=>__awaiter$b(void 0,[lo],void 0,function*({message:fo}){if(!oo)throw new Error("Client not initialized");return oo.signTypedData(JSON.parse(fo))}),transport:ro});return oo=createWalletClient({account:so,chain:to,transport:co}),oo};assertPackageVersion("@dynamic-labs/ethereum-core",version$d);class TurnkeyEVMWalletConnector extends TurnkeyWalletConnectorBase{constructor(eo,to){var ro;super(eo,to),this.walletFallback={brand:{alt:"Turnkey Wallet",spriteId:"turnkey"},name:"Turnkey HD"},this.ChainWallet=EthereumWallet,this.connectedChain="EVM",this.supportedChains=["ETH","EVM"],this.verifiedCredentialChain="eip155",this.stampCreateWalletAccountRequest=no=>__awaiter$c(this,[no],void 0,function*({request:io}){return yield this.createOrRestoreSession(),this.getTurnkeyClient().stampCreateWalletAccounts(io)}),this.evmNetworks=parseEvmNetworks(to.evmNetworks),this.walletUiUtils=to.walletUiUtils,this._turnkeyAccount=void 0,this._selectedChainId=this.getLastUsedChainId(),this.chainRpcProviders=to.chainRpcProviders,(ro=this.chainRpcProviders)===null||ro===void 0||ro.registerEvmProviders(),this.__turnkeyClient=this.getTurnkeyClient()}getLastUsedChainId(){var eo;if(this.lastUsedChainId)return this.lastUsedChainId;if(!((eo=this.evmNetworks)===null||eo===void 0)&&eo.length)return this.evmNetworks[0].chainId}getNetwork(){return __awaiter$c(this,void 0,void 0,function*(){var eo;return(eo=yield this.getSigner())===null||eo===void 0?void 0:eo.getChainId()})}supportsNetworkSwitching(){return!0}switchNetwork(eo){return __awaiter$c(this,arguments,void 0,function*({networkChainId:to}){this.lastUsedChainId=to,this._selectedChainId=to,yield this.refreshTurnkeyAccount(),this.emit("chainChange",{chain:to.toString()})})}setVerifiedCredentials(eo){const to=findTurnkeyVerifiedCredentialsWithSmartWalletRef(eo,"eip155"),[ro]=to;JSON.stringify(this.verifiedCredentials)!==JSON.stringify(to)&&(this.verifiedCredential=ro,this.verifiedCredentials=to,this.refreshTurnkeyAccount())}validateActiveWallet(eo){return __awaiter$c(this,void 0,void 0,function*(){var to,ro;const no=((to=this.verifiedCredential)===null||to===void 0?void 0:to.address)||"";if(!isSameAddress$1(no,eo,this.connectedChain)){const oo=(ro=this.verifiedCredentials)===null||ro===void 0?void 0:ro.find(ao=>(ao==null?void 0:ao.address)===eo);if(!oo)throw new DynamicError("Account not found");this.verifiedCredential=oo,this.refreshTurnkeyAccount()}})}getRpcUrl(){const eo=this._selectedChainId;return getRpcUrlForChain({chainId:eo,networks:this.evmNetworks})}getBalance(eo){return __awaiter$c(this,void 0,void 0,function*(){const to=this.getRpcUrl();if(!to)return;const no=yield createPublicClient({transport:http(to)}).getBalance({address:eo});return formatEther$1(no)})}signMessage(eo){return __awaiter$c(this,void 0,void 0,function*(){const to=yield this.getSigner();if(!to)throw new Error("Signer not found");return to.signMessage({message:eo})})}getPublicClient(){return __awaiter$c(this,void 0,void 0,function*(){var eo,to;if(this.evmNetworks.length===0)return;const ro=(eo=yield this.getNetwork())!==null&&eo!==void 0?eo:1,no={cosmos:[],evm:this.evmNetworks,solana:[],starknet:void 0};if(!this.chainRpcProviders)return;const io=this.chainRpcProviders.getProviders(no);return(to=this.chainRpcProviders.getEvmProviderByChainId(io,ro))===null||to===void 0?void 0:to.provider})}getSigner(){return __awaiter$c(this,void 0,void 0,function*(){return yield this.getTurnkeyAccount(),this.getWalletClient()})}getTurnkeyClient(){var eo;let to=getTLD();to||(to=PlatformService.getHostname());const ro=PasskeyService.createWebauthnStamper({rpId:to}),no=TurnkeyWalletConnectorBase==null?void 0:TurnkeyWalletConnectorBase.apiKeyStamper,io=no??ro;return this.__turnkeyClient=(eo=this.getAuthenticatorHandler().client)!==null&&eo!==void 0?eo:new TurnkeyClient({baseUrl:TURNKEY_API_BASE_URL},io),this.__turnkeyClient}getAccount(){return __awaiter$c(this,void 0,void 0,function*(){var eo,to,ro;return this.isSessionKeyCompatible()&&((eo=this.__turnkeyClient)===null||eo===void 0?void 0:eo.stamper)instanceof ApiKeyStamper?this._turnkeyAccount:((this.getAuthenticatorHandler().recoveryType==="passkey"&&((to=this.__turnkeyClient)===null||to===void 0?void 0:to.stamper)instanceof IframeStamper||this.getAuthenticatorHandler().recoveryType==="email"&&((ro=this.__turnkeyClient)===null||ro===void 0?void 0:ro.stamper)instanceof WebauthnStamper||this.__turnkeyClient!==this.getAuthenticatorHandler().client)&&(yield this.refreshTurnkeyAccount()),this._turnkeyAccount)})}getWalletClient(){const eo=this.networkRpcUrl,to=this._turnkeyAccount,ro=this.currentEvmNetwork;if(!(!to||!eo||!ro))return createWalletClientWithUiConfirmation({account:this.getAccount.bind(this),address:this.turnkeyAddress,chain:getOrMapViemChain(ro),transport:http(eo),walletConnector:this,walletUiUtils:this.walletUiUtils})}get currentChainId(){var eo,to,ro;return(eo=this._selectedChainId)!==null&&eo!==void 0?eo:(ro=(to=this.evmNetworks)===null||to===void 0?void 0:to[0])===null||ro===void 0?void 0:ro.chainId}get lastUsedChainId(){const eo=localStorage.getItem(TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey);if(eo)try{const to=parseInt(eo);if(isNaN(to))return;if(!this.evmNetworks.some(no=>no.chainId===to)){const no=this.evmNetworks[0].chainId;return this.lastUsedChainId=no,this.lastUsedChainId}return to}catch(to){logger$6.error(to);return}}set lastUsedChainId(eo){eo===void 0?localStorage.removeItem(TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey):localStorage.setItem(TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey,eo.toString())}get networkRpcUrl(){const eo=this.currentChainId;return this.evmNetworks.find(no=>no.chainId===eo)?getRpcUrlForChain({chainId:eo,networks:this.evmNetworks}):void 0}get currentEvmNetwork(){const eo=this.currentChainId;return this.evmNetworks.find(to=>to.chainId===eo)}internalSignTransaction(eo){return __awaiter$c(this,arguments,void 0,function*({transaction:to,args:ro,address:no,turnkeySubOrganizationId:io}){return this.doRetryableTurnkeyAction({action:oo=>oo.signTransaction(to,ro),activityType:"SignTransaction",address:no,turnkeySubOrganizationId:io})})}internalSignTypedData(eo){return __awaiter$c(this,arguments,void 0,function*({typedData:to,address:ro,turnkeySubOrganizationId:no}){return this.doRetryableTurnkeyAction({action:io=>io.signTypedData(to),activityType:"SignTypedData",address:ro,turnkeySubOrganizationId:no})})}internalSignMessage(eo){return __awaiter$c(this,arguments,void 0,function*({message:to,address:ro,turnkeySubOrganizationId:no}){return this.doRetryableTurnkeyAction({action:io=>io.signMessage({message:to}),activityType:"SignMessage",address:ro,turnkeySubOrganizationId:no})})}doRetryableTurnkeyAction(eo){return __awaiter$c(this,arguments,void 0,function*({action:to,activityType:ro,address:no,turnkeySubOrganizationId:io}){yield this.createOrRestoreSession();let oo=yield this.createTurnkeyAccount({address:no,turnkeySubOrganizationId:io});try{return yield to(oo)}catch(ao){if(TURNKEY_SDK_SESSION_KEY_RETRYABLE_ERRORS.some(so=>ao.message.includes(so)))return yield this.removeSessionKeys(),yield this.createOrRestoreSession({ignoreRestore:!0}),oo=yield this.createTurnkeyAccount({address:no,turnkeySubOrganizationId:io}),to(oo);throw logger$6.error(`[TK] failed to perform ${ro} activity`,ao),ao}})}createTurnkeyAccount(eo){return __awaiter$c(this,arguments,void 0,function*({address:to,turnkeySubOrganizationId:ro}){return createAccount({client:this.getTurnkeyClient(),ethereumAddress:to,organizationId:ro,signWith:to})})}refreshTurnkeyAccount(){return __awaiter$c(this,void 0,void 0,function*(){return this._turnkeyAccount=void 0,this.getTurnkeyAccount()})}getTurnkeyAccount(){return __awaiter$c(this,void 0,void 0,function*(){var eo,to;if(this._turnkeyAccount)return this._turnkeyAccount;const{turnkeySubOrganizationId:ro}=(eo=this.walletProperties)!==null&&eo!==void 0?eo:{},{address:no}=(to=this.verifiedCredential)!==null&&to!==void 0?to:{};if(!(!ro||!no))return this._turnkeyAccount=toAccount({address:no,signMessage:io=>__awaiter$c(this,[io],void 0,function*({message:oo}){return this.internalSignMessage({address:no,message:oo,turnkeySubOrganizationId:ro})}),signTransaction:(io,oo)=>__awaiter$c(this,void 0,void 0,function*(){return this.internalSignTransaction({address:no,args:oo,transaction:io,turnkeySubOrganizationId:ro})}),signTypedData:io=>__awaiter$c(this,void 0,void 0,function*(){return this.internalSignTypedData({address:no,turnkeySubOrganizationId:ro,typedData:io})})}),this.setLoggerMetadata(),this._turnkeyAccount})}createUiTransaction(eo){return __awaiter$c(this,void 0,void 0,function*(){yield this.validateActiveWallet(eo);const to=this.getWalletClient(),ro=yield this.getPublicClient();if(!ro||!to)throw new DynamicError("No public client available");return createViemUiTransaction({from:eo,publicClient:ro,walletClient:to})})}}TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey="turnkey-last-used-chain-id";const TurnkeyEVMWalletConnectors=Xr=>{var eo;return!((eo=Xr.apiProviders)===null||eo===void 0)&&eo.turnkey?[TurnkeyEVMWalletConnector.bind(null,TurnkeyWalletConnectorInfo.TurnkeyHD),TurnkeyEVMWalletConnector.bind(null,TurnkeyWalletConnectorInfo.Turnkey)]:[]};assertPackageVersion("@dynamic-labs/embedded-wallet-evm",version$g);var version$c="3.4.4";function __rest$6(Xr,eo){var to={};for(var ro in Xr)Object.prototype.hasOwnProperty.call(Xr,ro)&&eo.indexOf(ro)<0&&(to[ro]=Xr[ro]);if(Xr!=null&&typeof Object.getOwnPropertySymbols=="function")for(var no=0,ro=Object.getOwnPropertySymbols(Xr);noto.chain==="evm")}installedProviders(){const eo=this.getInjectedConfig();if(!eo)return[];const to=[];if(eo.windowLocations)for(const ro of eo.windowLocations){const no=getProvidersFromWindow(ro);no&&no.length&&to.push(...no)}return window.ethereum&&(!window.ethereum.providers||!window.ethereum.providers.length?to.push(window.ethereum):window.ethereum.providers.forEach(ro=>to.push(ro))),to}installedProviderLookup(eo){const to=this.installedProviders();return ProviderLookup(to,eo)}eip6963ProviderLookup(eo){var to;const{providers:ro}=Eip6963ProviderSingleton.get();return(to=ro.find(no=>{var io;return((io=no==null?void 0:no.info)===null||io===void 0?void 0:io.rdns)===eo}))===null||to===void 0?void 0:to.provider}isInstalledHelper(){return this.findProvider()!==void 0}findProvider(){return this.connector.findProvider()}findWalletClient(eo){const to=this.findProvider();if(to)return createWalletClient({account:this.connector.getActiveAccount(),chain:eo?chainsMap[eo]:this.connector.getActiveChain(),transport:custom$1(to)})}getAddress(){return __awaiter$a(this,void 0,void 0,function*(){const eo=this.findWalletClient();return eo?this.getAddressWithProvider(eo):Promise.resolve(void 0)})}getAddressWithProvider(eo){return __awaiter$a(this,void 0,void 0,function*(){try{const[to]=yield eo.requestAddresses(),ro=getAddress$1(to);return this.connector.setActiveAccount(ro),ro}catch(to){return logger$9.error(to),Promise.reject(to)}})}signMessage(eo){return __awaiter$a(this,void 0,void 0,function*(){const to=yield this.getAddress();if(!to)return Promise.resolve(void 0);const ro=this.findWalletClient();return ro?yield ro.signMessage({account:to,message:eo}):Promise.resolve(void 0)})}_setupEventListeners(eo){const to=this.findProvider();if(to&&"on"in to){const{handleAccountChange:ro,handleChainChange:no,handleDisconnect:io}=eventListenerHandlers(eo);return to.on("accountsChanged",ro),to.on("chainChanged",no),to.on("disconnect",io),{tearDownEventListeners:()=>{const ao=this.findProvider();ao&&(ro&&ao.removeListener("accountsChanged",ro),no&&ao.removeListener("chainChanged",no),io&&ao.removeListener("disconnect",io))}}}return to?"on"in to||logger$9.warn("Provider does not support event listeners",{connector:eo,provider:to}):logger$9.warn("Provider not found",{connector:eo}),{tearDownEventListeners:()=>{}}}}var chacha20poly1305={},chacha={},binary={},int={};(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0});function eo(ao,so){var co=ao>>>16&65535,lo=ao&65535,fo=so>>>16&65535,ho=so&65535;return lo*ho+(co*ho+lo*fo<<16>>>0)|0}Xr.mul=Math.imul||eo;function to(ao,so){return ao+so|0}Xr.add=to;function ro(ao,so){return ao-so|0}Xr.sub=ro;function no(ao,so){return ao<>>32-so}Xr.rotl=no;function io(ao,so){return ao<<32-so|ao>>>so}Xr.rotr=io;function oo(ao){return typeof ao=="number"&&isFinite(ao)&&Math.floor(ao)===ao}Xr.isInteger=Number.isInteger||oo,Xr.MAX_SAFE_INTEGER=9007199254740991,Xr.isSafeInteger=function(ao){return Xr.isInteger(ao)&&ao>=-Xr.MAX_SAFE_INTEGER&&ao<=Xr.MAX_SAFE_INTEGER}})(int);Object.defineProperty(binary,"__esModule",{value:!0});var int_1=int;function readInt16BE(Xr,eo){return eo===void 0&&(eo=0),(Xr[eo+0]<<8|Xr[eo+1])<<16>>16}binary.readInt16BE=readInt16BE;function readUint16BE(Xr,eo){return eo===void 0&&(eo=0),(Xr[eo+0]<<8|Xr[eo+1])>>>0}binary.readUint16BE=readUint16BE;function readInt16LE(Xr,eo){return eo===void 0&&(eo=0),(Xr[eo+1]<<8|Xr[eo])<<16>>16}binary.readInt16LE=readInt16LE;function readUint16LE(Xr,eo){return eo===void 0&&(eo=0),(Xr[eo+1]<<8|Xr[eo])>>>0}binary.readUint16LE=readUint16LE;function writeUint16BE(Xr,eo,to){return eo===void 0&&(eo=new Uint8Array(2)),to===void 0&&(to=0),eo[to+0]=Xr>>>8,eo[to+1]=Xr>>>0,eo}binary.writeUint16BE=writeUint16BE;binary.writeInt16BE=writeUint16BE;function writeUint16LE(Xr,eo,to){return eo===void 0&&(eo=new Uint8Array(2)),to===void 0&&(to=0),eo[to+0]=Xr>>>0,eo[to+1]=Xr>>>8,eo}binary.writeUint16LE=writeUint16LE;binary.writeInt16LE=writeUint16LE;function readInt32BE(Xr,eo){return eo===void 0&&(eo=0),Xr[eo]<<24|Xr[eo+1]<<16|Xr[eo+2]<<8|Xr[eo+3]}binary.readInt32BE=readInt32BE;function readUint32BE(Xr,eo){return eo===void 0&&(eo=0),(Xr[eo]<<24|Xr[eo+1]<<16|Xr[eo+2]<<8|Xr[eo+3])>>>0}binary.readUint32BE=readUint32BE;function readInt32LE(Xr,eo){return eo===void 0&&(eo=0),Xr[eo+3]<<24|Xr[eo+2]<<16|Xr[eo+1]<<8|Xr[eo]}binary.readInt32LE=readInt32LE;function readUint32LE(Xr,eo){return eo===void 0&&(eo=0),(Xr[eo+3]<<24|Xr[eo+2]<<16|Xr[eo+1]<<8|Xr[eo])>>>0}binary.readUint32LE=readUint32LE;function writeUint32BE(Xr,eo,to){return eo===void 0&&(eo=new Uint8Array(4)),to===void 0&&(to=0),eo[to+0]=Xr>>>24,eo[to+1]=Xr>>>16,eo[to+2]=Xr>>>8,eo[to+3]=Xr>>>0,eo}binary.writeUint32BE=writeUint32BE;binary.writeInt32BE=writeUint32BE;function writeUint32LE(Xr,eo,to){return eo===void 0&&(eo=new Uint8Array(4)),to===void 0&&(to=0),eo[to+0]=Xr>>>0,eo[to+1]=Xr>>>8,eo[to+2]=Xr>>>16,eo[to+3]=Xr>>>24,eo}binary.writeUint32LE=writeUint32LE;binary.writeInt32LE=writeUint32LE;function readInt64BE(Xr,eo){eo===void 0&&(eo=0);var to=readInt32BE(Xr,eo),ro=readInt32BE(Xr,eo+4);return to*4294967296+ro-(ro>>31)*4294967296}binary.readInt64BE=readInt64BE;function readUint64BE(Xr,eo){eo===void 0&&(eo=0);var to=readUint32BE(Xr,eo),ro=readUint32BE(Xr,eo+4);return to*4294967296+ro}binary.readUint64BE=readUint64BE;function readInt64LE(Xr,eo){eo===void 0&&(eo=0);var to=readInt32LE(Xr,eo),ro=readInt32LE(Xr,eo+4);return ro*4294967296+to-(to>>31)*4294967296}binary.readInt64LE=readInt64LE;function readUint64LE(Xr,eo){eo===void 0&&(eo=0);var to=readUint32LE(Xr,eo),ro=readUint32LE(Xr,eo+4);return ro*4294967296+to}binary.readUint64LE=readUint64LE;function writeUint64BE(Xr,eo,to){return eo===void 0&&(eo=new Uint8Array(8)),to===void 0&&(to=0),writeUint32BE(Xr/4294967296>>>0,eo,to),writeUint32BE(Xr>>>0,eo,to+4),eo}binary.writeUint64BE=writeUint64BE;binary.writeInt64BE=writeUint64BE;function writeUint64LE(Xr,eo,to){return eo===void 0&&(eo=new Uint8Array(8)),to===void 0&&(to=0),writeUint32LE(Xr>>>0,eo,to),writeUint32LE(Xr/4294967296>>>0,eo,to+4),eo}binary.writeUint64LE=writeUint64LE;binary.writeInt64LE=writeUint64LE;function readUintBE(Xr,eo,to){if(to===void 0&&(to=0),Xr%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(Xr/8>eo.length-to)throw new Error("readUintBE: array is too short for the given bitLength");for(var ro=0,no=1,io=Xr/8+to-1;io>=to;io--)ro+=eo[io]*no,no*=256;return ro}binary.readUintBE=readUintBE;function readUintLE(Xr,eo,to){if(to===void 0&&(to=0),Xr%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(Xr/8>eo.length-to)throw new Error("readUintLE: array is too short for the given bitLength");for(var ro=0,no=1,io=to;io=ro;io--)to[io]=eo/no&255,no*=256;return to}binary.writeUintBE=writeUintBE;function writeUintLE(Xr,eo,to,ro){if(to===void 0&&(to=new Uint8Array(Xr/8)),ro===void 0&&(ro=0),Xr%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!int_1.isSafeInteger(eo))throw new Error("writeUintLE value must be an integer");for(var no=1,io=ro;io>>16|po<<16,Lo=Lo+po|0,No^=Lo,No=No>>>20|No<<12,Po=Po+Do|0,bo^=Po,bo=bo>>>16|bo<<16,Bo=Bo+bo|0,Do^=Bo,Do=Do>>>20|Do<<12,jo=jo+Fo|0,_o^=jo,_o=_o>>>16|_o<<16,xo=xo+_o|0,Fo^=xo,Fo=Fo>>>20|Fo<<12,Mo=Mo+Xo|0,$o^=Mo,$o=$o>>>16|$o<<16,uo=uo+$o|0,Xo^=uo,Xo=Xo>>>20|Xo<<12,jo=jo+Fo|0,_o^=jo,_o=_o>>>24|_o<<8,xo=xo+_o|0,Fo^=xo,Fo=Fo>>>25|Fo<<7,Mo=Mo+Xo|0,$o^=Mo,$o=$o>>>24|$o<<8,uo=uo+$o|0,Xo^=uo,Xo=Xo>>>25|Xo<<7,Po=Po+Do|0,bo^=Po,bo=bo>>>24|bo<<8,Bo=Bo+bo|0,Do^=Bo,Do=Do>>>25|Do<<7,Ao=Ao+No|0,po^=Ao,po=po>>>24|po<<8,Lo=Lo+po|0,No^=Lo,No=No>>>25|No<<7,Ao=Ao+Do|0,$o^=Ao,$o=$o>>>16|$o<<16,xo=xo+$o|0,Do^=xo,Do=Do>>>20|Do<<12,Po=Po+Fo|0,po^=Po,po=po>>>16|po<<16,uo=uo+po|0,Fo^=uo,Fo=Fo>>>20|Fo<<12,jo=jo+Xo|0,bo^=jo,bo=bo>>>16|bo<<16,Lo=Lo+bo|0,Xo^=Lo,Xo=Xo>>>20|Xo<<12,Mo=Mo+No|0,_o^=Mo,_o=_o>>>16|_o<<16,Bo=Bo+_o|0,No^=Bo,No=No>>>20|No<<12,jo=jo+Xo|0,bo^=jo,bo=bo>>>24|bo<<8,Lo=Lo+bo|0,Xo^=Lo,Xo=Xo>>>25|Xo<<7,Mo=Mo+No|0,_o^=Mo,_o=_o>>>24|_o<<8,Bo=Bo+_o|0,No^=Bo,No=No>>>25|No<<7,Po=Po+Fo|0,po^=Po,po=po>>>24|po<<8,uo=uo+po|0,Fo^=uo,Fo=Fo>>>25|Fo<<7,Ao=Ao+Do|0,$o^=Ao,$o=$o>>>24|$o<<8,xo=xo+$o|0,Do^=xo,Do=Do>>>25|Do<<7;binary_1.writeUint32LE(Ao+ro|0,Xr,0),binary_1.writeUint32LE(Po+no|0,Xr,4),binary_1.writeUint32LE(jo+io|0,Xr,8),binary_1.writeUint32LE(Mo+oo|0,Xr,12),binary_1.writeUint32LE(No+ao|0,Xr,16),binary_1.writeUint32LE(Do+so|0,Xr,20),binary_1.writeUint32LE(Fo+co|0,Xr,24),binary_1.writeUint32LE(Xo+lo|0,Xr,28),binary_1.writeUint32LE(Lo+fo|0,Xr,32),binary_1.writeUint32LE(Bo+ho|0,Xr,36),binary_1.writeUint32LE(xo+go|0,Xr,40),binary_1.writeUint32LE(uo+yo|0,Xr,44),binary_1.writeUint32LE(po+vo|0,Xr,48),binary_1.writeUint32LE(bo+wo|0,Xr,52),binary_1.writeUint32LE(_o+Eo|0,Xr,56),binary_1.writeUint32LE($o+ko|0,Xr,60)}function streamXOR(Xr,eo,to,ro,no){if(no===void 0&&(no=0),Xr.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(ro.length>>=8,eo++;if(ro>0)throw new Error("ChaCha: counter overflow")}var poly1305={},constantTime={};Object.defineProperty(constantTime,"__esModule",{value:!0});function select(Xr,eo,to){return~(Xr-1)&eo|Xr-1&to}constantTime.select=select;function lessOrEqual(Xr,eo){return(Xr|0)-(eo|0)-1>>>31&1}constantTime.lessOrEqual=lessOrEqual;function compare$2(Xr,eo){if(Xr.length!==eo.length)return 0;for(var to=0,ro=0;ro>>8}constantTime.compare=compare$2;function equal(Xr,eo){return Xr.length===0||eo.length===0?!1:compare$2(Xr,eo)!==0}constantTime.equal=equal;(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0});var eo=constantTime,to=wipe$1;Xr.DIGEST_LENGTH=16;var ro=function(){function oo(ao){this.digestLength=Xr.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var so=ao[0]|ao[1]<<8;this._r[0]=so&8191;var co=ao[2]|ao[3]<<8;this._r[1]=(so>>>13|co<<3)&8191;var lo=ao[4]|ao[5]<<8;this._r[2]=(co>>>10|lo<<6)&7939;var fo=ao[6]|ao[7]<<8;this._r[3]=(lo>>>7|fo<<9)&8191;var ho=ao[8]|ao[9]<<8;this._r[4]=(fo>>>4|ho<<12)&255,this._r[5]=ho>>>1&8190;var go=ao[10]|ao[11]<<8;this._r[6]=(ho>>>14|go<<2)&8191;var yo=ao[12]|ao[13]<<8;this._r[7]=(go>>>11|yo<<5)&8065;var vo=ao[14]|ao[15]<<8;this._r[8]=(yo>>>8|vo<<8)&8191,this._r[9]=vo>>>5&127,this._pad[0]=ao[16]|ao[17]<<8,this._pad[1]=ao[18]|ao[19]<<8,this._pad[2]=ao[20]|ao[21]<<8,this._pad[3]=ao[22]|ao[23]<<8,this._pad[4]=ao[24]|ao[25]<<8,this._pad[5]=ao[26]|ao[27]<<8,this._pad[6]=ao[28]|ao[29]<<8,this._pad[7]=ao[30]|ao[31]<<8}return oo.prototype._blocks=function(ao,so,co){for(var lo=this._fin?0:2048,fo=this._h[0],ho=this._h[1],go=this._h[2],yo=this._h[3],vo=this._h[4],wo=this._h[5],Eo=this._h[6],ko=this._h[7],Ao=this._h[8],Po=this._h[9],jo=this._r[0],Mo=this._r[1],No=this._r[2],Do=this._r[3],Fo=this._r[4],Xo=this._r[5],Lo=this._r[6],Bo=this._r[7],xo=this._r[8],uo=this._r[9];co>=16;){var po=ao[so+0]|ao[so+1]<<8;fo+=po&8191;var bo=ao[so+2]|ao[so+3]<<8;ho+=(po>>>13|bo<<3)&8191;var _o=ao[so+4]|ao[so+5]<<8;go+=(bo>>>10|_o<<6)&8191;var $o=ao[so+6]|ao[so+7]<<8;yo+=(_o>>>7|$o<<9)&8191;var Co=ao[so+8]|ao[so+9]<<8;vo+=($o>>>4|Co<<12)&8191,wo+=Co>>>1&8191;var Ro=ao[so+10]|ao[so+11]<<8;Eo+=(Co>>>14|Ro<<2)&8191;var So=ao[so+12]|ao[so+13]<<8;ko+=(Ro>>>11|So<<5)&8191;var mo=ao[so+14]|ao[so+15]<<8;Ao+=(So>>>8|mo<<8)&8191,Po+=mo>>>5|lo;var To=0,Vo=To;Vo+=fo*jo,Vo+=ho*(5*uo),Vo+=go*(5*xo),Vo+=yo*(5*Bo),Vo+=vo*(5*Lo),To=Vo>>>13,Vo&=8191,Vo+=wo*(5*Xo),Vo+=Eo*(5*Fo),Vo+=ko*(5*Do),Vo+=Ao*(5*No),Vo+=Po*(5*Mo),To+=Vo>>>13,Vo&=8191;var Zo=To;Zo+=fo*Mo,Zo+=ho*jo,Zo+=go*(5*uo),Zo+=yo*(5*xo),Zo+=vo*(5*Bo),To=Zo>>>13,Zo&=8191,Zo+=wo*(5*Lo),Zo+=Eo*(5*Xo),Zo+=ko*(5*Fo),Zo+=Ao*(5*Do),Zo+=Po*(5*No),To+=Zo>>>13,Zo&=8191;var Qo=To;Qo+=fo*No,Qo+=ho*Mo,Qo+=go*jo,Qo+=yo*(5*uo),Qo+=vo*(5*xo),To=Qo>>>13,Qo&=8191,Qo+=wo*(5*Bo),Qo+=Eo*(5*Lo),Qo+=ko*(5*Xo),Qo+=Ao*(5*Fo),Qo+=Po*(5*Do),To+=Qo>>>13,Qo&=8191;var qo=To;qo+=fo*Do,qo+=ho*No,qo+=go*Mo,qo+=yo*jo,qo+=vo*(5*uo),To=qo>>>13,qo&=8191,qo+=wo*(5*xo),qo+=Eo*(5*Bo),qo+=ko*(5*Lo),qo+=Ao*(5*Xo),qo+=Po*(5*Fo),To+=qo>>>13,qo&=8191;var Ho=To;Ho+=fo*Fo,Ho+=ho*Do,Ho+=go*No,Ho+=yo*Mo,Ho+=vo*jo,To=Ho>>>13,Ho&=8191,Ho+=wo*(5*uo),Ho+=Eo*(5*xo),Ho+=ko*(5*Bo),Ho+=Ao*(5*Lo),Ho+=Po*(5*Xo),To+=Ho>>>13,Ho&=8191;var $a=To;$a+=fo*Xo,$a+=ho*Fo,$a+=go*Do,$a+=yo*No,$a+=vo*Mo,To=$a>>>13,$a&=8191,$a+=wo*jo,$a+=Eo*(5*uo),$a+=ko*(5*xo),$a+=Ao*(5*Bo),$a+=Po*(5*Lo),To+=$a>>>13,$a&=8191;var zo=To;zo+=fo*Lo,zo+=ho*Xo,zo+=go*Fo,zo+=yo*Do,zo+=vo*No,To=zo>>>13,zo&=8191,zo+=wo*Mo,zo+=Eo*jo,zo+=ko*(5*uo),zo+=Ao*(5*xo),zo+=Po*(5*Bo),To+=zo>>>13,zo&=8191;var Ko=To;Ko+=fo*Bo,Ko+=ho*Lo,Ko+=go*Xo,Ko+=yo*Fo,Ko+=vo*Do,To=Ko>>>13,Ko&=8191,Ko+=wo*No,Ko+=Eo*Mo,Ko+=ko*jo,Ko+=Ao*(5*uo),Ko+=Po*(5*xo),To+=Ko>>>13,Ko&=8191;var _c=To;_c+=fo*xo,_c+=ho*Bo,_c+=go*Lo,_c+=yo*Xo,_c+=vo*Fo,To=_c>>>13,_c&=8191,_c+=wo*Do,_c+=Eo*No,_c+=ko*Mo,_c+=Ao*jo,_c+=Po*(5*uo),To+=_c>>>13,_c&=8191;var Cl=To;Cl+=fo*uo,Cl+=ho*xo,Cl+=go*Bo,Cl+=yo*Lo,Cl+=vo*Xo,To=Cl>>>13,Cl&=8191,Cl+=wo*Fo,Cl+=Eo*Do,Cl+=ko*No,Cl+=Ao*Mo,Cl+=Po*jo,To+=Cl>>>13,Cl&=8191,To=(To<<2)+To|0,To=To+Vo|0,Vo=To&8191,To=To>>>13,Zo+=To,fo=Vo,ho=Zo,go=Qo,yo=qo,vo=Ho,wo=$a,Eo=zo,ko=Ko,Ao=_c,Po=Cl,so+=16,co-=16}this._h[0]=fo,this._h[1]=ho,this._h[2]=go,this._h[3]=yo,this._h[4]=vo,this._h[5]=wo,this._h[6]=Eo,this._h[7]=ko,this._h[8]=Ao,this._h[9]=Po},oo.prototype.finish=function(ao,so){so===void 0&&(so=0);var co=new Uint16Array(10),lo,fo,ho,go;if(this._leftover){for(go=this._leftover,this._buffer[go++]=1;go<16;go++)this._buffer[go]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(lo=this._h[1]>>>13,this._h[1]&=8191,go=2;go<10;go++)this._h[go]+=lo,lo=this._h[go]>>>13,this._h[go]&=8191;for(this._h[0]+=lo*5,lo=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=lo,lo=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=lo,co[0]=this._h[0]+5,lo=co[0]>>>13,co[0]&=8191,go=1;go<10;go++)co[go]=this._h[go]+lo,lo=co[go]>>>13,co[go]&=8191;for(co[9]-=8192,fo=(lo^1)-1,go=0;go<10;go++)co[go]&=fo;for(fo=~fo,go=0;go<10;go++)this._h[go]=this._h[go]&fo|co[go];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,ho=this._h[0]+this._pad[0],this._h[0]=ho&65535,go=1;go<8;go++)ho=(this._h[go]+this._pad[go]|0)+(ho>>>16)|0,this._h[go]=ho&65535;return ao[so+0]=this._h[0]>>>0,ao[so+1]=this._h[0]>>>8,ao[so+2]=this._h[1]>>>0,ao[so+3]=this._h[1]>>>8,ao[so+4]=this._h[2]>>>0,ao[so+5]=this._h[2]>>>8,ao[so+6]=this._h[3]>>>0,ao[so+7]=this._h[3]>>>8,ao[so+8]=this._h[4]>>>0,ao[so+9]=this._h[4]>>>8,ao[so+10]=this._h[5]>>>0,ao[so+11]=this._h[5]>>>8,ao[so+12]=this._h[6]>>>0,ao[so+13]=this._h[6]>>>8,ao[so+14]=this._h[7]>>>0,ao[so+15]=this._h[7]>>>8,this._finished=!0,this},oo.prototype.update=function(ao){var so=0,co=ao.length,lo;if(this._leftover){lo=16-this._leftover,lo>co&&(lo=co);for(var fo=0;fo=16&&(lo=co-co%16,this._blocks(ao,so,lo),so+=lo,co-=lo),co){for(var fo=0;fo16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var go=new Uint8Array(16);go.set(co,go.length-co.length);var yo=new Uint8Array(32);eo.stream(this._key,go,yo,4);var vo=lo.length+this.tagLength,wo;if(ho){if(ho.length!==vo)throw new Error("ChaCha20Poly1305: incorrect destination length");wo=ho}else wo=new Uint8Array(vo);return eo.streamXOR(this._key,go,lo,wo,4),this._authenticate(wo.subarray(wo.length-this.tagLength,wo.length),yo,wo.subarray(0,wo.length-this.tagLength),fo),ro.wipe(go),wo},so.prototype.open=function(co,lo,fo,ho){if(co.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(lo.length0&&go.update(oo.subarray(ho.length%16))),go.update(fo),fo.length%16>0&&go.update(oo.subarray(fo.length%16));var yo=new Uint8Array(8);ho&&no.writeUint64LE(ho.length,yo),go.update(yo),no.writeUint64LE(fo.length,yo),go.update(yo);for(var vo=go.digest(),wo=0;wothis.blockSize?this._inner.update(to).finish(ro).clean():ro.set(to);for(var no=0;no1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},Xr.prototype.expand=function(eo){for(var to=new Uint8Array(eo),ro=0;ro256)throw new Error("randomString charset is too long");let ho="";const go=lo.length,yo=256-256%go;for(;co>0;){const vo=no(Math.ceil(co*256/yo),fo);for(let wo=0;wo0;wo++){const Eo=vo[wo];Eo0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=so[lo++],co--;this._bufferLength===this.blockSize&&(io(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(co>=this.blockSize&&(lo=io(this._temp,this._state,so,lo,co),co%=this.blockSize);co>0;)this._buffer[this._bufferLength++]=so[lo++],co--;return this},ao.prototype.finish=function(so){if(!this._finished){var co=this._bytesHashed,lo=this._bufferLength,fo=co/536870912|0,ho=co<<3,go=co%64<56?64:128;this._buffer[lo]=128;for(var yo=lo+1;yo0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},ao.prototype.restoreState=function(so){return this._state.set(so.state),this._bufferLength=so.bufferLength,so.buffer&&this._buffer.set(so.buffer),this._bytesHashed=so.bytesHashed,this._finished=!1,this},ao.prototype.cleanSavedState=function(so){to.wipe(so.state),so.buffer&&to.wipe(so.buffer),so.bufferLength=0,so.bytesHashed=0},ao}();Xr.SHA256=ro;var no=new Int32Array([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]);function io(ao,so,co,lo,fo){for(;fo>=64;){for(var ho=so[0],go=so[1],yo=so[2],vo=so[3],wo=so[4],Eo=so[5],ko=so[6],Ao=so[7],Po=0;Po<16;Po++){var jo=lo+Po*4;ao[Po]=eo.readUint32BE(co,jo)}for(var Po=16;Po<64;Po++){var Mo=ao[Po-2],No=(Mo>>>17|Mo<<15)^(Mo>>>19|Mo<<13)^Mo>>>10;Mo=ao[Po-15];var Do=(Mo>>>7|Mo<<25)^(Mo>>>18|Mo<<14)^Mo>>>3;ao[Po]=(No+ao[Po-7]|0)+(Do+ao[Po-16]|0)}for(var Po=0;Po<64;Po++){var No=(((wo>>>6|wo<<26)^(wo>>>11|wo<<21)^(wo>>>25|wo<<7))+(wo&Eo^~wo&ko)|0)+(Ao+(no[Po]+ao[Po]|0)|0)|0,Do=((ho>>>2|ho<<30)^(ho>>>13|ho<<19)^(ho>>>22|ho<<10))+(ho&go^ho&yo^go&yo)|0;Ao=ko,ko=Eo,Eo=wo,wo=vo+No|0,vo=yo,yo=go,go=ho,ho=No+Do|0}so[0]+=ho,so[1]+=go,so[2]+=yo,so[3]+=vo,so[4]+=wo,so[5]+=Eo,so[6]+=ko,so[7]+=Ao,lo+=64,fo-=64}return lo}function oo(ao){var so=new ro;so.update(ao);var co=so.digest();return so.clean(),co}Xr.hash=oo})(sha256$1);var x25519={};(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.sharedKey=Xr.generateKeyPair=Xr.generateKeyPairFromSeed=Xr.scalarMultBase=Xr.scalarMult=Xr.SHARED_KEY_LENGTH=Xr.SECRET_KEY_LENGTH=Xr.PUBLIC_KEY_LENGTH=void 0;const eo=random,to=wipe$1;Xr.PUBLIC_KEY_LENGTH=32,Xr.SECRET_KEY_LENGTH=32,Xr.SHARED_KEY_LENGTH=32;function ro(Po){const jo=new Float64Array(16);if(Po)for(let Mo=0;Mo>16&1),Mo[Xo-1]&=65535;Mo[15]=No[15]-32767-(Mo[14]>>16&1);const Fo=Mo[15]>>16&1;Mo[14]&=65535,ao(No,Mo,1-Fo)}for(let Do=0;Do<16;Do++)Po[2*Do]=No[Do]&255,Po[2*Do+1]=No[Do]>>8}function co(Po,jo){for(let Mo=0;Mo<16;Mo++)Po[Mo]=jo[2*Mo]+(jo[2*Mo+1]<<8);Po[15]&=32767}function lo(Po,jo,Mo){for(let No=0;No<16;No++)Po[No]=jo[No]+Mo[No]}function fo(Po,jo,Mo){for(let No=0;No<16;No++)Po[No]=jo[No]-Mo[No]}function ho(Po,jo,Mo){let No,Do,Fo=0,Xo=0,Lo=0,Bo=0,xo=0,uo=0,po=0,bo=0,_o=0,$o=0,Co=0,Ro=0,So=0,mo=0,To=0,Vo=0,Zo=0,Qo=0,qo=0,Ho=0,$a=0,zo=0,Ko=0,_c=0,Cl=0,ga=0,El=0,Al=0,Ol=0,Wl=0,zl=0,Tl=Mo[0],Ml=Mo[1],ou=Mo[2],Vl=Mo[3],Ll=Mo[4],uu=Mo[5],ru=Mo[6],tu=Mo[7],ku=Mo[8],au=Mo[9],wl=Mo[10],Jo=Mo[11],Go=Mo[12],$l=Mo[13],Zl=Mo[14],Ul=Mo[15];No=jo[0],Fo+=No*Tl,Xo+=No*Ml,Lo+=No*ou,Bo+=No*Vl,xo+=No*Ll,uo+=No*uu,po+=No*ru,bo+=No*tu,_o+=No*ku,$o+=No*au,Co+=No*wl,Ro+=No*Jo,So+=No*Go,mo+=No*$l,To+=No*Zl,Vo+=No*Ul,No=jo[1],Xo+=No*Tl,Lo+=No*Ml,Bo+=No*ou,xo+=No*Vl,uo+=No*Ll,po+=No*uu,bo+=No*ru,_o+=No*tu,$o+=No*ku,Co+=No*au,Ro+=No*wl,So+=No*Jo,mo+=No*Go,To+=No*$l,Vo+=No*Zl,Zo+=No*Ul,No=jo[2],Lo+=No*Tl,Bo+=No*Ml,xo+=No*ou,uo+=No*Vl,po+=No*Ll,bo+=No*uu,_o+=No*ru,$o+=No*tu,Co+=No*ku,Ro+=No*au,So+=No*wl,mo+=No*Jo,To+=No*Go,Vo+=No*$l,Zo+=No*Zl,Qo+=No*Ul,No=jo[3],Bo+=No*Tl,xo+=No*Ml,uo+=No*ou,po+=No*Vl,bo+=No*Ll,_o+=No*uu,$o+=No*ru,Co+=No*tu,Ro+=No*ku,So+=No*au,mo+=No*wl,To+=No*Jo,Vo+=No*Go,Zo+=No*$l,Qo+=No*Zl,qo+=No*Ul,No=jo[4],xo+=No*Tl,uo+=No*Ml,po+=No*ou,bo+=No*Vl,_o+=No*Ll,$o+=No*uu,Co+=No*ru,Ro+=No*tu,So+=No*ku,mo+=No*au,To+=No*wl,Vo+=No*Jo,Zo+=No*Go,Qo+=No*$l,qo+=No*Zl,Ho+=No*Ul,No=jo[5],uo+=No*Tl,po+=No*Ml,bo+=No*ou,_o+=No*Vl,$o+=No*Ll,Co+=No*uu,Ro+=No*ru,So+=No*tu,mo+=No*ku,To+=No*au,Vo+=No*wl,Zo+=No*Jo,Qo+=No*Go,qo+=No*$l,Ho+=No*Zl,$a+=No*Ul,No=jo[6],po+=No*Tl,bo+=No*Ml,_o+=No*ou,$o+=No*Vl,Co+=No*Ll,Ro+=No*uu,So+=No*ru,mo+=No*tu,To+=No*ku,Vo+=No*au,Zo+=No*wl,Qo+=No*Jo,qo+=No*Go,Ho+=No*$l,$a+=No*Zl,zo+=No*Ul,No=jo[7],bo+=No*Tl,_o+=No*Ml,$o+=No*ou,Co+=No*Vl,Ro+=No*Ll,So+=No*uu,mo+=No*ru,To+=No*tu,Vo+=No*ku,Zo+=No*au,Qo+=No*wl,qo+=No*Jo,Ho+=No*Go,$a+=No*$l,zo+=No*Zl,Ko+=No*Ul,No=jo[8],_o+=No*Tl,$o+=No*Ml,Co+=No*ou,Ro+=No*Vl,So+=No*Ll,mo+=No*uu,To+=No*ru,Vo+=No*tu,Zo+=No*ku,Qo+=No*au,qo+=No*wl,Ho+=No*Jo,$a+=No*Go,zo+=No*$l,Ko+=No*Zl,_c+=No*Ul,No=jo[9],$o+=No*Tl,Co+=No*Ml,Ro+=No*ou,So+=No*Vl,mo+=No*Ll,To+=No*uu,Vo+=No*ru,Zo+=No*tu,Qo+=No*ku,qo+=No*au,Ho+=No*wl,$a+=No*Jo,zo+=No*Go,Ko+=No*$l,_c+=No*Zl,Cl+=No*Ul,No=jo[10],Co+=No*Tl,Ro+=No*Ml,So+=No*ou,mo+=No*Vl,To+=No*Ll,Vo+=No*uu,Zo+=No*ru,Qo+=No*tu,qo+=No*ku,Ho+=No*au,$a+=No*wl,zo+=No*Jo,Ko+=No*Go,_c+=No*$l,Cl+=No*Zl,ga+=No*Ul,No=jo[11],Ro+=No*Tl,So+=No*Ml,mo+=No*ou,To+=No*Vl,Vo+=No*Ll,Zo+=No*uu,Qo+=No*ru,qo+=No*tu,Ho+=No*ku,$a+=No*au,zo+=No*wl,Ko+=No*Jo,_c+=No*Go,Cl+=No*$l,ga+=No*Zl,El+=No*Ul,No=jo[12],So+=No*Tl,mo+=No*Ml,To+=No*ou,Vo+=No*Vl,Zo+=No*Ll,Qo+=No*uu,qo+=No*ru,Ho+=No*tu,$a+=No*ku,zo+=No*au,Ko+=No*wl,_c+=No*Jo,Cl+=No*Go,ga+=No*$l,El+=No*Zl,Al+=No*Ul,No=jo[13],mo+=No*Tl,To+=No*Ml,Vo+=No*ou,Zo+=No*Vl,Qo+=No*Ll,qo+=No*uu,Ho+=No*ru,$a+=No*tu,zo+=No*ku,Ko+=No*au,_c+=No*wl,Cl+=No*Jo,ga+=No*Go,El+=No*$l,Al+=No*Zl,Ol+=No*Ul,No=jo[14],To+=No*Tl,Vo+=No*Ml,Zo+=No*ou,Qo+=No*Vl,qo+=No*Ll,Ho+=No*uu,$a+=No*ru,zo+=No*tu,Ko+=No*ku,_c+=No*au,Cl+=No*wl,ga+=No*Jo,El+=No*Go,Al+=No*$l,Ol+=No*Zl,Wl+=No*Ul,No=jo[15],Vo+=No*Tl,Zo+=No*Ml,Qo+=No*ou,qo+=No*Vl,Ho+=No*Ll,$a+=No*uu,zo+=No*ru,Ko+=No*tu,_c+=No*ku,Cl+=No*au,ga+=No*wl,El+=No*Jo,Al+=No*Go,Ol+=No*$l,Wl+=No*Zl,zl+=No*Ul,Fo+=38*Zo,Xo+=38*Qo,Lo+=38*qo,Bo+=38*Ho,xo+=38*$a,uo+=38*zo,po+=38*Ko,bo+=38*_c,_o+=38*Cl,$o+=38*ga,Co+=38*El,Ro+=38*Al,So+=38*Ol,mo+=38*Wl,To+=38*zl,Do=1,No=Fo+Do+65535,Do=Math.floor(No/65536),Fo=No-Do*65536,No=Xo+Do+65535,Do=Math.floor(No/65536),Xo=No-Do*65536,No=Lo+Do+65535,Do=Math.floor(No/65536),Lo=No-Do*65536,No=Bo+Do+65535,Do=Math.floor(No/65536),Bo=No-Do*65536,No=xo+Do+65535,Do=Math.floor(No/65536),xo=No-Do*65536,No=uo+Do+65535,Do=Math.floor(No/65536),uo=No-Do*65536,No=po+Do+65535,Do=Math.floor(No/65536),po=No-Do*65536,No=bo+Do+65535,Do=Math.floor(No/65536),bo=No-Do*65536,No=_o+Do+65535,Do=Math.floor(No/65536),_o=No-Do*65536,No=$o+Do+65535,Do=Math.floor(No/65536),$o=No-Do*65536,No=Co+Do+65535,Do=Math.floor(No/65536),Co=No-Do*65536,No=Ro+Do+65535,Do=Math.floor(No/65536),Ro=No-Do*65536,No=So+Do+65535,Do=Math.floor(No/65536),So=No-Do*65536,No=mo+Do+65535,Do=Math.floor(No/65536),mo=No-Do*65536,No=To+Do+65535,Do=Math.floor(No/65536),To=No-Do*65536,No=Vo+Do+65535,Do=Math.floor(No/65536),Vo=No-Do*65536,Fo+=Do-1+37*(Do-1),Do=1,No=Fo+Do+65535,Do=Math.floor(No/65536),Fo=No-Do*65536,No=Xo+Do+65535,Do=Math.floor(No/65536),Xo=No-Do*65536,No=Lo+Do+65535,Do=Math.floor(No/65536),Lo=No-Do*65536,No=Bo+Do+65535,Do=Math.floor(No/65536),Bo=No-Do*65536,No=xo+Do+65535,Do=Math.floor(No/65536),xo=No-Do*65536,No=uo+Do+65535,Do=Math.floor(No/65536),uo=No-Do*65536,No=po+Do+65535,Do=Math.floor(No/65536),po=No-Do*65536,No=bo+Do+65535,Do=Math.floor(No/65536),bo=No-Do*65536,No=_o+Do+65535,Do=Math.floor(No/65536),_o=No-Do*65536,No=$o+Do+65535,Do=Math.floor(No/65536),$o=No-Do*65536,No=Co+Do+65535,Do=Math.floor(No/65536),Co=No-Do*65536,No=Ro+Do+65535,Do=Math.floor(No/65536),Ro=No-Do*65536,No=So+Do+65535,Do=Math.floor(No/65536),So=No-Do*65536,No=mo+Do+65535,Do=Math.floor(No/65536),mo=No-Do*65536,No=To+Do+65535,Do=Math.floor(No/65536),To=No-Do*65536,No=Vo+Do+65535,Do=Math.floor(No/65536),Vo=No-Do*65536,Fo+=Do-1+37*(Do-1),Po[0]=Fo,Po[1]=Xo,Po[2]=Lo,Po[3]=Bo,Po[4]=xo,Po[5]=uo,Po[6]=po,Po[7]=bo,Po[8]=_o,Po[9]=$o,Po[10]=Co,Po[11]=Ro,Po[12]=So,Po[13]=mo,Po[14]=To,Po[15]=Vo}function go(Po,jo){ho(Po,jo,jo)}function yo(Po,jo){const Mo=ro();for(let No=0;No<16;No++)Mo[No]=jo[No];for(let No=253;No>=0;No--)go(Mo,Mo),No!==2&&No!==4&&ho(Mo,Mo,jo);for(let No=0;No<16;No++)Po[No]=Mo[No]}function vo(Po,jo){const Mo=new Uint8Array(32),No=new Float64Array(80),Do=ro(),Fo=ro(),Xo=ro(),Lo=ro(),Bo=ro(),xo=ro();for(let _o=0;_o<31;_o++)Mo[_o]=Po[_o];Mo[31]=Po[31]&127|64,Mo[0]&=248,co(No,jo);for(let _o=0;_o<16;_o++)Fo[_o]=No[_o];Do[0]=Lo[0]=1;for(let _o=254;_o>=0;--_o){const $o=Mo[_o>>>3]>>>(_o&7)&1;ao(Do,Fo,$o),ao(Xo,Lo,$o),lo(Bo,Do,Xo),fo(Do,Do,Xo),lo(Xo,Fo,Lo),fo(Fo,Fo,Lo),go(Lo,Bo),go(xo,Do),ho(Do,Xo,Do),ho(Xo,Fo,Bo),lo(Bo,Do,Xo),fo(Do,Do,Xo),go(Fo,Do),fo(Xo,Lo,xo),ho(Do,Xo,io),lo(Do,Do,Lo),ho(Xo,Xo,Do),ho(Do,Lo,xo),ho(Lo,Fo,No),go(Fo,Bo),ao(Do,Fo,$o),ao(Xo,Lo,$o)}for(let _o=0;_o<16;_o++)No[_o+16]=Do[_o],No[_o+32]=Xo[_o],No[_o+48]=Fo[_o],No[_o+64]=Lo[_o];const uo=No.subarray(32),po=No.subarray(16);yo(uo,uo),ho(po,po,uo);const bo=new Uint8Array(32);return so(bo,po),bo}Xr.scalarMult=vo;function wo(Po){return vo(Po,no)}Xr.scalarMultBase=wo;function Eo(Po){if(Po.length!==Xr.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${Xr.SECRET_KEY_LENGTH} bytes`);const jo=new Uint8Array(Po);return{publicKey:wo(jo),secretKey:jo}}Xr.generateKeyPairFromSeed=Eo;function ko(Po){const jo=(0,eo.randomBytes)(32,Po),Mo=Eo(jo);return(0,to.wipe)(jo),Mo}Xr.generateKeyPair=ko;function Ao(Po,jo,Mo=!1){if(Po.length!==Xr.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(jo.length!==Xr.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");const No=vo(Po,jo);if(Mo){let Do=0;for(let Fo=0;Fono+io.length,0));const to=allocUnsafe(eo);let ro=0;for(const no of Xr)to.set(no,ro),ro+=no.length;return asUint8Array(to)}function base$1(Xr,eo){if(Xr.length>=255)throw new TypeError("Alphabet too long");for(var to=new Uint8Array(256),ro=0;ro>>0,Po=new Uint8Array(Ao);Eo!==ko;){for(var jo=yo[Eo],Mo=0,No=Ao-1;(jo!==0||Mo>>0,Po[No]=jo%ao>>>0,jo=jo/ao>>>0;if(jo!==0)throw new Error("Non-zero carry");wo=Mo,Eo++}for(var Do=Ao-wo;Do!==Ao&&Po[Do]===0;)Do++;for(var Fo=so.repeat(vo);Do>>0,Ao=new Uint8Array(ko);yo[vo];){var Po=to[yo.charCodeAt(vo)];if(Po===255)return;for(var jo=0,Mo=ko-1;(Po!==0||jo>>0,Ao[Mo]=Po%256>>>0,Po=Po/256>>>0;if(Po!==0)throw new Error("Non-zero carry");Eo=jo,vo++}if(yo[vo]!==" "){for(var No=ko-Eo;No!==ko&&Ao[No]===0;)No++;for(var Do=new Uint8Array(wo+(ko-No)),Fo=wo;No!==ko;)Do[Fo++]=Ao[No++];return Do}}}function go(yo){var vo=ho(yo);if(vo)return vo;throw new Error(`Non-${eo} character`)}return{encode:fo,decodeUnsafe:ho,decode:go}}var src$1=base$1,_brrp__multiformats_scope_baseX=src$1;const coerce$3=Xr=>{if(Xr instanceof Uint8Array&&Xr.constructor.name==="Uint8Array")return Xr;if(Xr instanceof ArrayBuffer)return new Uint8Array(Xr);if(ArrayBuffer.isView(Xr))return new Uint8Array(Xr.buffer,Xr.byteOffset,Xr.byteLength);throw new Error("Unknown type, must be binary type")},fromString$1=Xr=>new TextEncoder().encode(Xr),toString$3=Xr=>new TextDecoder().decode(Xr);class Encoder{constructor(eo,to,ro){this.name=eo,this.prefix=to,this.baseEncode=ro}encode(eo){if(eo instanceof Uint8Array)return`${this.prefix}${this.baseEncode(eo)}`;throw Error("Unknown type, must be binary type")}}class Decoder{constructor(eo,to,ro){if(this.name=eo,this.prefix=to,to.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=to.codePointAt(0),this.baseDecode=ro}decode(eo){if(typeof eo=="string"){if(eo.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(eo)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(eo.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(eo){return or$3(this,eo)}}class ComposedDecoder{constructor(eo){this.decoders=eo}or(eo){return or$3(this,eo)}decode(eo){const to=eo[0],ro=this.decoders[to];if(ro)return ro.decode(eo);throw RangeError(`Unable to decode multibase string ${JSON.stringify(eo)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const or$3=(Xr,eo)=>new ComposedDecoder({...Xr.decoders||{[Xr.prefix]:Xr},...eo.decoders||{[eo.prefix]:eo}});class Codec{constructor(eo,to,ro,no){this.name=eo,this.prefix=to,this.baseEncode=ro,this.baseDecode=no,this.encoder=new Encoder(eo,to,ro),this.decoder=new Decoder(eo,to,no)}encode(eo){return this.encoder.encode(eo)}decode(eo){return this.decoder.decode(eo)}}const from=({name:Xr,prefix:eo,encode:to,decode:ro})=>new Codec(Xr,eo,to,ro),baseX=({prefix:Xr,name:eo,alphabet:to})=>{const{encode:ro,decode:no}=_brrp__multiformats_scope_baseX(to,eo);return from({prefix:Xr,name:eo,encode:ro,decode:io=>coerce$3(no(io))})},decode$5=(Xr,eo,to,ro)=>{const no={};for(let lo=0;lo=8&&(ao-=8,oo[co++]=255&so>>ao)}if(ao>=to||255&so<<8-ao)throw new SyntaxError("Unexpected end of data");return oo},encode$2=(Xr,eo,to)=>{const ro=eo[eo.length-1]==="=",no=(1<to;)oo-=to,io+=eo[no&ao>>oo];if(oo&&(io+=eo[no&ao<from({prefix:eo,name:Xr,encode(no){return encode$2(no,ro,to)},decode(no){return decode$5(no,ro,to,Xr)}}),identity$2=from({prefix:"\0",name:"identity",encode:Xr=>toString$3(Xr),decode:Xr=>fromString$1(Xr)}),identityBase=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$2},Symbol.toStringTag,{value:"Module"})),base2=rfc4648({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$1=Object.freeze(Object.defineProperty({__proto__:null,base2},Symbol.toStringTag,{value:"Module"})),base8=rfc4648({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$1=Object.freeze(Object.defineProperty({__proto__:null,base8},Symbol.toStringTag,{value:"Module"})),base10=baseX({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$1=Object.freeze(Object.defineProperty({__proto__:null,base10},Symbol.toStringTag,{value:"Module"})),base16=rfc4648({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper=rfc4648({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$1=Object.freeze(Object.defineProperty({__proto__:null,base16,base16upper},Symbol.toStringTag,{value:"Module"})),base32=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper=rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad=rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper=rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex=rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper=rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad=rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper=rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z=rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$1=Object.freeze(Object.defineProperty({__proto__:null,base32,base32hex,base32hexpad,base32hexpadupper,base32hexupper,base32pad,base32padupper,base32upper,base32z},Symbol.toStringTag,{value:"Module"})),base36=baseX({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper=baseX({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$1=Object.freeze(Object.defineProperty({__proto__:null,base36,base36upper},Symbol.toStringTag,{value:"Module"})),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr=baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58=Object.freeze(Object.defineProperty({__proto__:null,base58btc,base58flickr},Symbol.toStringTag,{value:"Module"})),base64=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad=rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad=rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$1=Object.freeze(Object.defineProperty({__proto__:null,base64,base64pad,base64url,base64urlpad},Symbol.toStringTag,{value:"Module"})),alphabet=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),alphabetBytesToChars=alphabet.reduce((Xr,eo,to)=>(Xr[to]=eo,Xr),[]),alphabetCharsToBytes=alphabet.reduce((Xr,eo,to)=>(Xr[eo.codePointAt(0)]=to,Xr),[]);function encode$1(Xr){return Xr.reduce((eo,to)=>(eo+=alphabetBytesToChars[to],eo),"")}function decode$4(Xr){const eo=[];for(const to of Xr){const ro=alphabetCharsToBytes[to.codePointAt(0)];if(ro===void 0)throw new Error(`Non-base256emoji character: ${to}`);eo.push(ro)}return new Uint8Array(eo)}const base256emoji=from({prefix:"🚀",name:"base256emoji",encode:encode$1,decode:decode$4}),base256emoji$1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases={...identityBase,...base2$1,...base8$1,...base10$1,...base16$1,...base32$1,...base36$1,...base58,...base64$1,...base256emoji$1};function createCodec(Xr,eo,to,ro){return{name:Xr,prefix:eo,encoder:{name:Xr,prefix:eo,encode:to},decoder:{decode:ro}}}const string$3=createCodec("utf8","u",Xr=>"u"+new TextDecoder("utf8").decode(Xr),Xr=>new TextEncoder().encode(Xr.substring(1))),ascii=createCodec("ascii","a",Xr=>{let eo="a";for(let to=0;to{Xr=Xr.substring(1);const eo=allocUnsafe(Xr.length);for(let to=0;to"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new ReactNativeInfo:typeof navigator<"u"?parseUserAgent(navigator.userAgent):getNodeVersion()}function matchUserAgent(Xr){return Xr!==""&&userAgentRules.reduce(function(eo,to){var ro=to[0],no=to[1];if(eo)return eo;var io=no.exec(Xr);return!!io&&[ro,io]},!1)}function parseUserAgent(Xr){var eo=matchUserAgent(Xr);if(!eo)return null;var to=eo[0],ro=eo[1];if(to==="searchbot")return new BotInfo;var no=ro[1]&&ro[1].split(".").join("_").split("_").slice(0,3);no?no.length=Hl)return Io;var du=Uo-j0(yl);if(du<1)return yl;var bu=iu?d0(iu,0,du).join(""):Io.slice(0,du);if(Rl===to)return bu+yl;if(iu&&(du+=bu.length-du),Y1(Rl)){if(Io.slice(du).search(Rl)){var Pu,Ou=bu;for(Rl.global||(Rl=d1(Rl.source,Op(lu.exec(Rl))+"g")),Rl.lastIndex=0;Pu=Rl.exec(Ou);)var Fu=Pu.index;bu=bu.slice(0,Fu===to?du:Fu)}}else if(Io.indexOf(bm(Rl),du)!=du){var _d=bu.lastIndexOf(Rl);_d>-1&&(bu=bu.slice(0,_d))}return bu+yl}function M3(Io){return Io=Op(Io),Io&&Yu.test(Io)?Io.replace(mu,ax):Io}var j3=q0(function(Io,Oo,Uo){return Io+(Uo?" ":"")+Oo.toUpperCase()}),lv=Ew("toUpperCase");function __(Io,Oo,Uo){return Io=Op(Io),Oo=Uo?to:Oo,Oo===to?tx(Io)?lx(Io):V_(Io):Io.match(Oo)||[]}var x_=xp(function(Io,Oo){try{return nm(Io,to,Oo)}catch(Uo){return J1(Uo)?Uo:new hp(Uo)}}),B3=Ym(function(Io,Oo){return Sm(Oo,function(Uo){Uo=zm(Uo),Zm(Io,Uo,G1(Io[Uo],Io))}),Io});function D3(Io){var Oo=Io==null?0:Io.length,Uo=ap();return Io=Oo?Vp(Io,function(yl){if(typeof yl[1]!="function")throw new km(oo);return[Uo(yl[0]),yl[1]]}):[],xp(function(yl){for(var Rl=-1;++Rl$o)return[];var Uo=So,yl=am(Io,So);Oo=ap(Oo),Io-=So;for(var Rl=c1(yl,Oo);++Uo0||Oo<0)?new Sp(Uo):(Io<0?Uo=Uo.takeRight(-Io):Io&&(Uo=Uo.drop(Io)),Oo!==to&&(Oo=vp(Oo),Uo=Oo<0?Uo.dropRight(-Oo):Uo.take(Oo-Io)),Uo)},Sp.prototype.takeRightWhile=function(Io){return this.reverse().takeWhile(Io).reverse()},Sp.prototype.toArray=function(){return this.take(So)},Wm(Sp.prototype,function(Io,Oo){var Uo=/^(?:filter|find|map|reject)|While$/.test(Oo),yl=/^(?:head|last)$/.test(Oo),Rl=Dl[yl?"take"+(Oo=="last"?"Right":""):Oo],Hl=yl||/^find/.test(Oo);Rl&&(Dl.prototype[Oo]=function(){var iu=this.__wrapped__,du=yl?[1]:arguments,bu=iu instanceof Sp,Pu=du[0],Ou=bu||gp(iu),Fu=function($p){var Cp=Rl.apply(Dl,o0([$p],du));return yl&&_d?Cp[0]:Cp};Ou&&Uo&&typeof Pu=="function"&&Pu.length!=1&&(bu=Ou=!1);var _d=this.__chain__,tp=!!this.__actions__.length,sp=Hl&&!_d,_p=bu&&!tp;if(!Hl&&Ou){iu=_p?iu:new Sp(this);var cp=Io.apply(iu,du);return cp.__actions__.push({func:zy,args:[Fu],thisArg:to}),new Cm(cp,_d)}return sp&&_p?Io.apply(this,du):(cp=this.thru(Fu),sp?yl?cp.value()[0]:cp.value():cp)})}),Sm(["pop","push","shift","sort","splice","unshift"],function(Io){var Oo=gy[Io],Uo=/^(?:push|sort|unshift)$/.test(Io)?"tap":"thru",yl=/^(?:pop|shift)$/.test(Io);Dl.prototype[Io]=function(){var Rl=arguments;if(yl&&!this.__chain__){var Hl=this.value();return Oo.apply(gp(Hl)?Hl:[],Rl)}return this[Uo](function(iu){return Oo.apply(gp(iu)?iu:[],Rl)})}}),Wm(Sp.prototype,function(Io,Oo){var Uo=Dl[Oo];if(Uo){var yl=Uo.name+"";Np.call(U0,yl)||(U0[yl]=[]),U0[yl].push({name:Oo,func:Uo})}}),U0[By(to,Eo).name]=[{name:"wrapper",func:to}],Sp.prototype.clone=Px,Sp.prototype.reverse=Ox,Sp.prototype.value=Nx,Dl.prototype.at=l$,Dl.prototype.chain=u$,Dl.prototype.commit=d$,Dl.prototype.next=f$,Dl.prototype.plant=p$,Dl.prototype.reverse=m$,Dl.prototype.toJSON=Dl.prototype.valueOf=Dl.prototype.value=g$,Dl.prototype.first=Dl.prototype.head,Q0&&(Dl.prototype[Q0]=h$),Dl},B0=ux();Jp?((Jp.exports=B0)._=B0,jp._=B0):kp._=B0}).call(ge$2)})(Ui$1,Ui$1.exports);var Gg=Object.defineProperty,zg=Object.defineProperties,Kg=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Yg=Object.prototype.hasOwnProperty,Zg=Object.prototype.propertyIsEnumerable,ya=(Xr,eo,to)=>eo in Xr?Gg(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,cr$2=(Xr,eo)=>{for(var to in eo||(eo={}))Yg.call(eo,to)&&ya(Xr,to,eo[to]);if(Ea)for(var to of Ea(eo))Zg.call(eo,to)&&ya(Xr,to,eo[to]);return Xr},Jg=(Xr,eo)=>zg(Xr,Kg(eo));function ft$2(Xr,eo,to){var ro;const no=ve$2(Xr);return((ro=eo.rpcMap)==null?void 0:ro[no.reference])||`${Bg}?chainId=${no.namespace}:${no.reference}&projectId=${to}`}function Ct$2(Xr){return Xr.includes(":")?Xr.split(":")[1]:Xr}function Sa(Xr){return Xr.map(eo=>`${eo.split(":")[0]}:${eo.split(":")[1]}`)}function Xg(Xr,eo){const to=Object.keys(eo.namespaces).filter(no=>no.includes(Xr));if(!to.length)return[];const ro=[];return to.forEach(no=>{const io=eo.namespaces[no].accounts;ro.push(...io)}),ro}function Oa(Xr={},eo={}){const to=Ra(Xr),ro=Ra(eo);return Ui$1.exports.merge(to,ro)}function Ra(Xr){var eo,to,ro,no;const io={};if(!B$5(Xr))return io;for(const[oo,ao]of Object.entries(Xr)){const so=oe$3(oo)?[oo]:ao.chains,co=ao.methods||[],lo=ao.events||[],fo=ao.rpcMap||{},ho=en$1(oo);io[ho]=Jg(cr$2(cr$2({},io[ho]),ao),{chains:S$7(so,(eo=io[ho])==null?void 0:eo.chains),methods:S$7(co,(to=io[ho])==null?void 0:to.methods),events:S$7(lo,(ro=io[ho])==null?void 0:ro.events),rpcMap:cr$2(cr$2({},fo),(no=io[ho])==null?void 0:no.rpcMap)})}return io}function Qg(Xr){return Xr.includes(":")?Xr.split(":")[2]:Xr}function Vg(Xr){const eo={};for(const[to,ro]of Object.entries(Xr)){const no=ro.methods||[],io=ro.events||[],oo=ro.accounts||[],ao=oe$3(to)?[to]:ro.chains?ro.chains:Sa(ro.accounts);eo[to]={chains:ao,methods:no,events:io,accounts:oo}}return eo}function Wi$1(Xr){return typeof Xr=="number"?Xr:Xr.includes("0x")?parseInt(Xr,16):(Xr=Xr.includes(":")?Xr.split(":")[1]:Xr,isNaN(Number(Xr))?Xr:Number(Xr))}const ba$1={},z$5=Xr=>ba$1[Xr],Fi$1=(Xr,eo)=>{ba$1[Xr]=eo};class kg{constructor(eo){this.name="polkadot",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getAccounts(){const eo=this.namespace.accounts;return eo?eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2])||[]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class jg{constructor(eo){this.name="eip155",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(eo){switch(eo.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(eo);case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(eo.request.method)?await this.client.request(eo):this.getHttpProvider().request(eo.request)}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(parseInt(eo),to),this.chainId=parseInt(eo),this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}createHttpProvider(eo,to){const ro=to||ft$2(`${this.name}:${eo}`,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=parseInt(Ct$2(to));eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}getHttpProvider(){const eo=this.chainId,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}async handleSwitchChain(eo){var to,ro;let no=eo.request.params?(to=eo.request.params[0])==null?void 0:to.chainId:"0x0";no=no.startsWith("0x")?no:`0x${no}`;const io=parseInt(no,16);if(this.isChainApproved(io))this.setDefaultChain(`${io}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:eo.topic,request:{method:eo.request.method,params:[{chainId:no}]},chainId:(ro=this.namespace.chains)==null?void 0:ro[0]}),this.setDefaultChain(`${io}`);else throw new Error(`Failed to switch to chain 'eip155:${io}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(eo){return this.namespace.chains.includes(`${this.name}:${eo}`)}}class nv{constructor(eo){this.name="solana",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class tv{constructor(eo){this.name="cosmos",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class ev{constructor(eo){this.name="cip34",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{const ro=this.getCardanoRPCUrl(to),no=Ct$2(to);eo[no]=this.createHttpProvider(no,ro)}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}getCardanoRPCUrl(eo){const to=this.namespace.rpcMap;if(to)return to[eo]}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||this.getCardanoRPCUrl(eo);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class rv{constructor(eo){this.name="elrond",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class iv{constructor(eo){this.name="multiversx",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class sv{constructor(eo){this.name="near",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){if(this.chainId=eo,!this.httpProviders[eo]){const ro=to||ft$2(`${this.name}:${eo}`,this.namespace);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);this.setHttpProvider(eo,ro)}this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const eo=this.namespace.accounts;return eo?eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2])||[]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;eo[to]=this.createHttpProvider(to,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace);return typeof ro>"u"?void 0:new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}var uv=Object.defineProperty,av=Object.defineProperties,ov=Object.getOwnPropertyDescriptors,Ta=Object.getOwnPropertySymbols,fv=Object.prototype.hasOwnProperty,cv=Object.prototype.propertyIsEnumerable,La=(Xr,eo,to)=>eo in Xr?uv(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,hr$1=(Xr,eo)=>{for(var to in eo||(eo={}))fv.call(eo,to)&&La(Xr,to,eo[to]);if(Ta)for(var to of Ta(eo))cv.call(eo,to)&&La(Xr,to,eo[to]);return Xr},Mi$1=(Xr,eo)=>av(Xr,ov(eo));let lr$2=class I_{constructor(eo){this.events=new EventEmitter$1,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=eo,this.logger=typeof(eo==null?void 0:eo.logger)<"u"&&typeof(eo==null?void 0:eo.logger)!="string"?eo.logger:Hg(k$2({level:(eo==null?void 0:eo.logger)||Ia})),this.disableProviderPing=(eo==null?void 0:eo.disableProviderPing)||!1}static async init(eo){const to=new I_(eo);return await to.initialize(),to}async request(eo,to,ro){const[no,io]=this.validateChain(to);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(no).request({request:hr$1({},eo),chainId:`${no}:${io}`,topic:this.session.topic,expiry:ro})}sendAsync(eo,to,ro,no){const io=new Date().getTime();this.request(eo,ro,no).then(oo=>to(null,formatJsonRpcResult(io,oo))).catch(oo=>to(oo,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var eo;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(eo=this.session)==null?void 0:eo.topic,reason:U$6("USER_DISCONNECTED")}),await this.cleanup()}async connect(eo){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(eo),await this.cleanupPendingPairings(),!eo.skipPairing)return await this.pair(eo.pairingTopic)}on(eo,to){this.events.on(eo,to)}once(eo,to){this.events.once(eo,to)}removeListener(eo,to){this.events.removeListener(eo,to)}off(eo,to){this.events.off(eo,to)}get isWalletConnect(){return!0}async pair(eo){this.shouldAbortPairingAttempt=!1;let to=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(to>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:ro,approval:no}=await this.client.connect({pairingTopic:eo,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});ro&&(this.uri=ro,this.events.emit("display_uri",ro)),await no().then(io=>{this.session=io;const oo=Vg(io.namespaces);this.namespaces=Oa(this.namespaces,oo),this.persist("namespaces",this.namespaces)}).catch(io=>{if(io.message!==ae$2)throw io;to++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(eo,to){try{if(!this.session)return;const[ro,no]=this.validateChain(eo);this.getProvider(ro).setDefaultChain(no,to)}catch(ro){if(!/Please call connect/.test(ro.message))throw ro}}async cleanupPendingPairings(eo={}){this.logger.info("Cleaning up inactive pairings...");const to=this.client.pairing.getAll();if(k$4(to)){for(const ro of to)eo.deletePairings?this.client.core.expirer.set(ro.topic,0):await this.client.core.relayer.subscriber.unsubscribe(ro.topic);this.logger.info(`Inactive pairings cleared: ${to.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const eo=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[eo]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await Q$4.init({logger:this.providerOpts.logger||Ia,relayUrl:this.providerOpts.relayUrl||Fg,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const eo=[...new Set(Object.keys(this.session.namespaces).map(to=>en$1(to)))];Fi$1("client",this.client),Fi$1("events",this.events),Fi$1("disableProviderPing",this.disableProviderPing),eo.forEach(to=>{if(!this.session)return;const ro=Xg(to,this.session),no=Sa(ro),io=Oa(this.namespaces,this.optionalNamespaces),oo=Mi$1(hr$1({},io[to]),{accounts:ro,chains:no});switch(to){case"eip155":this.rpcProviders[to]=new jg({namespace:oo});break;case"solana":this.rpcProviders[to]=new nv({namespace:oo});break;case"cosmos":this.rpcProviders[to]=new tv({namespace:oo});break;case"polkadot":this.rpcProviders[to]=new kg({namespace:oo});break;case"cip34":this.rpcProviders[to]=new ev({namespace:oo});break;case"elrond":this.rpcProviders[to]=new rv({namespace:oo});break;case"multiversx":this.rpcProviders[to]=new iv({namespace:oo});break;case"near":this.rpcProviders[to]=new sv({namespace:oo});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",eo=>{this.events.emit("session_ping",eo)}),this.client.on("session_event",eo=>{const{params:to}=eo,{event:ro}=to;if(ro.name==="accountsChanged"){const no=ro.data;no&&k$4(no)&&this.events.emit("accountsChanged",no.map(Qg))}else if(ro.name==="chainChanged"){const no=to.chainId,io=to.event.data,oo=en$1(no),ao=Wi$1(no)!==Wi$1(io)?`${oo}:${Wi$1(io)}`:no;this.onChainChanged(ao)}else this.events.emit(ro.name,ro.data);this.events.emit("session_event",eo)}),this.client.on("session_update",({topic:eo,params:to})=>{var ro;const{namespaces:no}=to,io=(ro=this.client)==null?void 0:ro.session.get(eo);this.session=Mi$1(hr$1({},io),{namespaces:no}),this.onSessionUpdate(),this.events.emit("session_update",{topic:eo,params:to})}),this.client.on("session_delete",async eo=>{await this.cleanup(),this.events.emit("session_delete",eo),this.events.emit("disconnect",Mi$1(hr$1({},U$6("USER_DISCONNECTED")),{data:eo.topic}))}),this.on(Vn$1.DEFAULT_CHAIN_CHANGED,eo=>{this.onChainChanged(eo,!0)})}getProvider(eo){if(!this.rpcProviders[eo])throw new Error(`Provider not found: ${eo}`);return this.rpcProviders[eo]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(eo=>{var to;this.getProvider(eo).updateNamespace((to=this.session)==null?void 0:to.namespaces[eo])})}setNamespaces(eo){const{namespaces:to,optionalNamespaces:ro,sessionProperties:no}=eo;to&&Object.keys(to).length&&(this.namespaces=to),ro&&Object.keys(ro).length&&(this.optionalNamespaces=ro),this.sessionProperties=no,this.persist("namespaces",to),this.persist("optionalNamespaces",ro)}validateChain(eo){const[to,ro]=(eo==null?void 0:eo.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[to,ro];if(to&&!Object.keys(this.namespaces||{}).map(oo=>en$1(oo)).includes(to))throw new Error(`Namespace '${to}' is not configured. Please call connect() first with namespace config.`);if(to&&ro)return[to,ro];const no=en$1(Object.keys(this.namespaces)[0]),io=this.rpcProviders[no].getDefaultChain();return[no,io]}async requestAccounts(){const[eo]=this.validateChain();return await this.getProvider(eo).requestAccounts()}onChainChanged(eo,to=!1){if(!this.namespaces)return;const[ro,no]=this.validateChain(eo);no&&(to||this.getProvider(ro).setDefaultChain(no),this.namespaces[ro]?this.namespaces[ro].defaultChain=no:this.namespaces[`${ro}:${no}`]?this.namespaces[`${ro}:${no}`].defaultChain=no:this.namespaces[`${ro}:${no}`]={defaultChain:no},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",no))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(eo,to){this.client.core.storage.setItem(`${xa}/${eo}`,to)}async getFromStore(eo){return await this.client.core.storage.getItem(`${xa}/${eo}`)}};const hv=lr$2,P$4="wc",S$4="ethereum_provider",$$3=`${P$4}@2:${S$4}:`,j$6="https://rpc.walletconnect.com/v1/",u$4=["eth_sendTransaction","personal_sign"],E$3=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m$3=["chainChanged","accountsChanged"],_$6=["chainChanged","accountsChanged","message","disconnect","connect"];var N$5=Object.defineProperty,q$5=Object.defineProperties,D$3=Object.getOwnPropertyDescriptors,y$7=Object.getOwnPropertySymbols,U$4=Object.prototype.hasOwnProperty,Q$3=Object.prototype.propertyIsEnumerable,O$6=(Xr,eo,to)=>eo in Xr?N$5(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,p$3=(Xr,eo)=>{for(var to in eo||(eo={}))U$4.call(eo,to)&&O$6(Xr,to,eo[to]);if(y$7)for(var to of y$7(eo))Q$3.call(eo,to)&&O$6(Xr,to,eo[to]);return Xr},M$3=(Xr,eo)=>q$5(Xr,D$3(eo));function g$5(Xr){return Number(Xr[0].split(":")[1])}function f$6(Xr){return`0x${Xr.toString(16)}`}function L$5(Xr){const{chains:eo,optionalChains:to,methods:ro,optionalMethods:no,events:io,optionalEvents:oo,rpcMap:ao}=Xr;if(!k$4(eo))throw new Error("Invalid chains");const so={chains:eo,methods:ro||u$4,events:io||m$3,rpcMap:p$3({},eo.length?{[g$5(eo)]:ao[g$5(eo)]}:{})},co=io==null?void 0:io.filter(go=>!m$3.includes(go)),lo=ro==null?void 0:ro.filter(go=>!u$4.includes(go));if(!to&&!oo&&!no&&!(co!=null&&co.length)&&!(lo!=null&&lo.length))return{required:eo.length?so:void 0};const fo=(co==null?void 0:co.length)&&(lo==null?void 0:lo.length)||!to,ho={chains:[...new Set(fo?so.chains.concat(to||[]):to)],methods:[...new Set(so.methods.concat(no!=null&&no.length?no:E$3))],events:[...new Set(so.events.concat(oo!=null&&oo.length?oo:_$6))],rpcMap:ao};return{required:eo.length?so:void 0,optional:to.length?ho:void 0}}let v$3=class R_{constructor(){this.events=new eventsExports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=$$3,this.on=(eo,to)=>(this.events.on(eo,to),this),this.once=(eo,to)=>(this.events.once(eo,to),this),this.removeListener=(eo,to)=>(this.events.removeListener(eo,to),this),this.off=(eo,to)=>(this.events.off(eo,to),this),this.parseAccount=eo=>this.isCompatibleChainId(eo)?this.parseAccountId(eo).address:eo,this.signer={},this.rpc={}}static async init(eo){const to=new R_;return await to.initialize(eo),to}async request(eo,to){return await this.signer.request(eo,this.formatChainId(this.chainId),to)}sendAsync(eo,to,ro){this.signer.sendAsync(eo,to,this.formatChainId(this.chainId),ro)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(eo){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(eo);const{required:to,optional:ro}=L$5(this.rpc);try{const no=await new Promise(async(oo,ao)=>{var so;this.rpc.showQrModal&&((so=this.modal)==null||so.subscribeModal(co=>{!co.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),ao(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M$3(p$3({namespaces:p$3({},to&&{[this.namespace]:to})},ro&&{optionalNamespaces:{[this.namespace]:ro}}),{pairingTopic:eo==null?void 0:eo.pairingTopic})).then(co=>{oo(co)}).catch(co=>{ao(new Error(co.message))})});if(!no)return;const io=Un$1(no.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:io),this.setAccounts(io),this.events.emit("connect",{chainId:f$6(this.chainId)})}catch(no){throw this.signer.logger.error(no),no}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",eo=>{const{params:to}=eo,{event:ro}=to;ro.name==="accountsChanged"?(this.accounts=this.parseAccounts(ro.data),this.events.emit("accountsChanged",this.accounts)):ro.name==="chainChanged"?this.setChainId(this.formatChainId(ro.data)):this.events.emit(ro.name,ro.data),this.events.emit("session_event",eo)}),this.signer.on("chainChanged",eo=>{const to=parseInt(eo);this.chainId=to,this.events.emit("chainChanged",f$6(this.chainId)),this.persist()}),this.signer.on("session_update",eo=>{this.events.emit("session_update",eo)}),this.signer.on("session_delete",eo=>{this.reset(),this.events.emit("session_delete",eo),this.events.emit("disconnect",M$3(p$3({},U$6("USER_DISCONNECTED")),{data:eo.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",eo=>{var to,ro;this.rpc.showQrModal&&((to=this.modal)==null||to.closeModal(),(ro=this.modal)==null||ro.openModal({uri:eo})),this.events.emit("display_uri",eo)})}switchEthereumChain(eo){this.request({method:"wallet_switchEthereumChain",params:[{chainId:eo.toString(16)}]})}isCompatibleChainId(eo){return typeof eo=="string"?eo.startsWith(`${this.namespace}:`):!1}formatChainId(eo){return`${this.namespace}:${eo}`}parseChainId(eo){return Number(eo.split(":")[1])}setChainIds(eo){const to=eo.filter(ro=>this.isCompatibleChainId(ro)).map(ro=>this.parseChainId(ro));to.length&&(this.chainId=to[0],this.events.emit("chainChanged",f$6(this.chainId)),this.persist())}setChainId(eo){if(this.isCompatibleChainId(eo)){const to=this.parseChainId(eo);this.chainId=to,this.switchEthereumChain(to)}}parseAccountId(eo){const[to,ro,no]=eo.split(":");return{chainId:`${to}:${ro}`,address:no}}setAccounts(eo){this.accounts=eo.filter(to=>this.parseChainId(this.parseAccountId(to).chainId)===this.chainId).map(to=>this.parseAccountId(to).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(eo){var to,ro;const no=(to=eo==null?void 0:eo.chains)!=null?to:[],io=(ro=eo==null?void 0:eo.optionalChains)!=null?ro:[],oo=no.concat(io);if(!oo.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const ao=no.length?(eo==null?void 0:eo.methods)||u$4:[],so=no.length?(eo==null?void 0:eo.events)||m$3:[],co=(eo==null?void 0:eo.optionalMethods)||[],lo=(eo==null?void 0:eo.optionalEvents)||[],fo=(eo==null?void 0:eo.rpcMap)||this.buildRpcMap(oo,eo.projectId),ho=(eo==null?void 0:eo.qrModalOptions)||void 0;return{chains:no==null?void 0:no.map(go=>this.formatChainId(go)),optionalChains:io.map(go=>this.formatChainId(go)),methods:ao,events:so,optionalMethods:co,optionalEvents:lo,rpcMap:fo,showQrModal:!!(eo!=null&&eo.showQrModal),qrModalOptions:ho,projectId:eo.projectId,metadata:eo.metadata}}buildRpcMap(eo,to){const ro={};return eo.forEach(no=>{ro[no]=this.getRpcUrl(no,to)}),ro}async initialize(eo){if(this.rpc=this.getRpcConfig(eo),this.chainId=this.rpc.chains.length?g$5(this.rpc.chains):g$5(this.rpc.optionalChains),this.signer=await hv.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:eo.disableProviderPing,relayUrl:eo.relayUrl,storageOptions:eo.storageOptions}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let to;try{const{WalletConnectModal:ro}=await __vitePreload(()=>import("./index-B0ywuJCf.js").then(no=>no.i),[]);to=ro}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(to)try{this.modal=new to(p$3({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(ro){throw this.signer.logger.error(ro),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(eo){if(!eo)return;const{chains:to,optionalChains:ro,rpcMap:no}=eo;to&&k$4(to)&&(this.rpc.chains=to.map(io=>this.formatChainId(io)),to.forEach(io=>{this.rpc.rpcMap[io]=(no==null?void 0:no[io])||this.getRpcUrl(io)})),ro&&k$4(ro)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=ro==null?void 0:ro.map(io=>this.formatChainId(io)),ro.forEach(io=>{this.rpc.rpcMap[io]=(no==null?void 0:no[io])||this.getRpcUrl(io)}))}getRpcUrl(eo,to){var ro;return((ro=this.rpc.rpcMap)==null?void 0:ro[eo])||`${j$6}?chainId=eip155:${eo}&projectId=${to||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const eo=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),to=this.session.namespaces[`${this.namespace}:${eo}`]?this.session.namespaces[`${this.namespace}:${eo}`]:this.session.namespaces[this.namespace];this.setChainIds(eo?[this.formatChainId(eo)]:to==null?void 0:to.accounts),this.setAccounts(to==null?void 0:to.accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(eo){return typeof eo=="string"||eo instanceof String?[this.parseAccount(eo)]:eo.map(to=>this.parseAccount(to))}};const parseIntSafe=(Xr,eo=10)=>{try{const to=parseInt(String(Xr),eo);if(isNaN(to)){logger$9.error(`Error parsing ${Xr}`);return}return to}catch(to){logger$9.error(`Error parsing ${Xr} to int: ${to}`)}},activeAccountKey=Xr=>`dynamic-wc2-active-account-${Xr}`,sessionTopicKey=Xr=>`dynamic-wc2-session-topic-${Xr}`,swicthedNetworkKey=Xr=>`dynamic-wc2-switched-network-${Xr}`,currentChainKey=Xr=>`dynamic-wc2-current-chain-${Xr}`,ee$2=new EventEmitter$3;class WalletConnect extends EthWalletConnector{constructor(eo){var to;super(eo),this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.isInitialized=!1,this.canConnectViaQrCode=!0,this.isWalletConnect=!0,this.preferredChains=[],this._hasSwitchedNetwork=!1,this.sessionEventHandler=()=>{},this.sessionDeleteHandler=()=>{},this.name=eo.walletName,this.projectId=eo.projectId,this.deepLinkPreference=eo.deepLinkPreference||"native",this.preferredChains=eo.walletConnectPreferredChains||[],this.hasSwitchedNetwork=(to=!!localStorage.getItem(this.swicthedNetworkKey))!==null&&to!==void 0?to:!1;const ro=localStorage.getItem(this.currentChainKey);this.currentChainId=ro?parseIntSafe(ro):void 0}getMappedChains(){return this.evmNetworks.filter(eo=>eo.chainId!==11297108109).map(eo=>`eip155:${eo.chainId}`)}getMappedChainsByPreferredOrder(){const eo=this.getMappedChains(),to=this.preferredChains.filter(no=>eo.includes(no)),ro=eo.filter(no=>!this.preferredChains.includes(no));return[...to,...ro].map(no=>Number(no.split(":")[1]))}initConnection(){return __awaiter$a(this,void 0,void 0,function*(){const{provider:eo}=WalletConnect;if(!eo)throw new DynamicError("No provider found (init connection)");eo!=null&&eo.signer.uri||eo.connect().catch(to=>{logger$9.error(to),ee$2.emit("walletconnect_connection_failed",to)})})}createProvider(){return __awaiter$a(this,void 0,void 0,function*(){return v$3.init({events:["chainChanged","accountsChanged"],methods:[],optionalChains:this.getMappedChainsByPreferredOrder(),optionalMethods:["eth_chainId","eth_signTypedData","eth_signTransaction","eth_sign","personal_sign","eth_sendTransaction","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain"],projectId:this.projectId,rpcMap:this.evmNetworkRpcMap(),showQrModal:!1})})}getWalletClientFromInitializedProvider(){return __awaiter$a(this,void 0,void 0,function*(){const eo=this.createProvider();return createWalletClient({account:this.getActiveAccount(),transport:custom$1(yield eo)})})}createInitProviderPromise(){return __awaiter$a(this,void 0,void 0,function*(){WalletConnect.provider=yield this.createProvider(),this.teardownEventListeners(),this.setupEventListeners()})}initProvider(){return __awaiter$a(this,void 0,void 0,function*(){const{provider:eo}=WalletConnect;eo||(this.initializePromise===void 0&&(this.initializePromise=this.createInitProviderPromise()),yield this.initializePromise)})}refreshSession(){var eo,to,ro,no,io;!((to=(eo=WalletConnect.provider)===null||eo===void 0?void 0:eo.session)===null||to===void 0)&&to.topic&&localStorage.getItem(this.sessionTopicKey)===((no=(ro=WalletConnect.provider)===null||ro===void 0?void 0:ro.session)===null||no===void 0?void 0:no.topic)&&(this.session=WalletConnect.provider.session,this.setActiveAccount((io=localStorage.getItem(this.activeAccountKey))!==null&&io!==void 0?io:void 0))}init(){return __awaiter$a(this,void 0,void 0,function*(){yield this.initProvider(),yield this.initConnection(),this.isInitialized=!0})}get sessionTopicKey(){return sessionTopicKey(this.key)}get activeAccountKey(){return activeAccountKey(this.key)}get swicthedNetworkKey(){return swicthedNetworkKey(this.key)}get currentChainKey(){return currentChainKey(this.key)}set currentChainId(eo){this._currentChainId=eo,eo?localStorage.setItem(this.currentChainKey,eo.toString()):localStorage.removeItem(this.currentChainKey)}get currentChainId(){return this._currentChainId}set hasSwitchedNetwork(eo){this._hasSwitchedNetwork=eo,eo?localStorage.setItem(this.swicthedNetworkKey,eo.toString()):localStorage.removeItem(this.swicthedNetworkKey)}get hasSwitchedNetwork(){return this._hasSwitchedNetwork}supportsNetworkSwitching(){return!0}setupEventListeners(){WalletConnect.provider&&(this.sessionEventHandler=({params:eo})=>{if(logger$9.debug("session_event was called",{params:eo}),!eo||!eo.event){logger$9.debug("session_event was called without params or params.event");return}const{name:to,data:ro}=eo.event;if(to==="chainChanged"){const no=parseIntSafe(ro);if(no===this.currentChainId){logger$9.debug(`ignoring chainChanged event with same chain id as current chain id: ${no}`);return}if(no===void 0){logger$9.debug(`received unexpected data for chainChanged: ${ro} with type ${typeof ro}}`);return}this.currentChainId=no,this.emit("chainChange",{chain:String(no)}),this.hasSwitchedNetwork=!0,this.switchNetwork({networkChainId:no})}else if(to==="accountsChanged"){if(!Array.isArray(ro)){logger$9.debug(`received unexpected data for accountsChanged: ${ro} with type ${typeof ro}}`);return}const no=ro[0].split(":")[2];this.setWCActiveAccount(no)}},WalletConnect.provider.on("session_event",this.sessionEventHandler),this.sessionDeleteHandler=()=>__awaiter$a(this,void 0,void 0,function*(){this.endSession(),this.emit("disconnect")}),WalletConnect.provider.on("session_delete",this.sessionDeleteHandler))}teardownEventListeners(){WalletConnect.provider&&(WalletConnect.provider.off("session_event",this.sessionEventHandler),WalletConnect.provider.off("session_delete",this.sessionDeleteHandler))}getWalletClient(eo){if(WalletConnect.provider)return createWalletClient({account:this.getActiveAccount(),chain:chainsMap[eo??String(this.currentChainId)],transport:custom$1(WalletConnect.provider)})}getAddress(eo){return __awaiter$a(this,void 0,void 0,function*(){var to,ro;const no=this.getActiveAccount();if(no!=null&&no.address)return no.address;if((!WalletConnect.provider||!(!((to=WalletConnect.provider)===null||to===void 0)&&to.signer.uri))&&(logger$9.debug("No WC2 provider found, re-initializing..."),yield this.endSession(),yield this.init(),yield sleep$1(1e3),!WalletConnect.provider||!(!((ro=WalletConnect.provider)===null||ro===void 0)&&ro.signer.uri)))throw logger$9.debug("No WC2 provider found, escaping and throwing error"),new DynamicError("No provider found");const io=getWalletBookWallet(this.walletBook,this.key,this.walletFallback);return performPlatformSpecificConnectionMethod(WalletConnect.provider.signer.uri,io,{onDesktopUri:eo==null?void 0:eo.onDesktopUri,onDisplayUri:eo==null?void 0:eo.onDisplayUri},this.deepLinkPreference),new Promise((oo,ao)=>{if(!WalletConnect.provider){ao(new DynamicError("No provider found"));return}const so=()=>{const fo=new DynamicError("Connection rejected. Please try again.");fo.code="connection_rejected",WalletConnect.provider&&(WalletConnect.provider.signer.uri=void 0,this.init()),ao(fo),lo()},co=()=>{var fo;const ho=(fo=WalletConnect.provider)===null||fo===void 0?void 0:fo.session;if(!ho){ao(new DynamicError("No session found"));return}this.setSession(ho),this.setWCActiveAccount(ho.namespaces.eip155.accounts[0].split(":")[2]),this.getNetwork().then(go=>{var yo;this.currentChainId=go,oo((yo=this.getActiveAccount())===null||yo===void 0?void 0:yo.address)}),lo()},lo=()=>{var fo;ee$2.off("walletconnect_connection_failed",so),(fo=WalletConnect.provider)===null||fo===void 0||fo.off("connect",co)};ee$2.on("walletconnect_connection_failed",so),WalletConnect.provider.on("connect",co)})})}waitForSignMessage(eo,to){return __awaiter$a(this,void 0,void 0,function*(){const no=yield new Promise((io,oo)=>{this.on("chainChange",()=>io({success:!1})),eo(to).then(ao=>io({signedMessage:ao,success:!0})).catch(oo)});return no.success===!1?eo(to):no.signedMessage})}getDeepLink(){var eo;if(!this.session)return;const to=getWalletBookWallet(this.walletBook,this.key),ro=getDeepLink({metadata:to,mode:"regular",preference:this.deepLinkPreference,uri:(eo=WalletConnect.provider)===null||eo===void 0?void 0:eo.signer.uri});if(ro)return`${ro}?sessionTopic=${this.session.topic}`}signMessage(eo){return __awaiter$a(this,void 0,void 0,function*(){if(!this.session)throw new DynamicError("no session");const to=this.getDeepLink();isMobile$1()&&to&&(window.location.href=to);const ro=io=>__awaiter$a(this,void 0,void 0,function*(){const oo=this.getActiveAccount();return oo?(yield this.getWalletClientFromInitializedProvider()).signMessage({account:oo,message:io}):void 0});return yield this.waitForSignMessage(ro,eo)})}clearActiveAccount(){localStorage.removeItem(this.activeAccountKey),this.setActiveAccount(void 0)}clearSession(){localStorage.removeItem(this.sessionTopicKey),this.session=void 0}setWCActiveAccount(eo){localStorage.setItem(this.activeAccountKey,eo),this.setActiveAccount(eo),this.emit("accountChange",{accounts:[eo]})}setSession(eo){localStorage.setItem(this.sessionTopicKey,eo.topic),this.session=eo}endSession(){return __awaiter$a(this,void 0,void 0,function*(){var eo;if(this.clearActiveAccount(),this.clearSession(),this.hasSwitchedNetwork=!1,this.currentChainId=void 0,!!(!((eo=WalletConnect.provider)===null||eo===void 0)&&eo.session))try{yield WalletConnect.provider.disconnect(),WalletConnect.provider=void 0}catch(to){logger$9.debug(to)}})}getNetwork(){const eo=Object.create(null,{getNetwork:{get:()=>super.getNetwork}});return __awaiter$a(this,void 0,void 0,function*(){return this.currentChainId?this.currentChainId:(yield this.initProvider(),eo.getNetwork.call(this))})}providerSwitchNetwork(eo){const to=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$a(this,arguments,void 0,function*({network:ro}){const no=yield this.getSupportedNetworks();if(!(no!=null&&no.includes(ro.chainId.toString()))){const ao=new DynamicError("Network switching is not available at this time. The user should manually switch network in their wallet");throw ao.code="network_switching_only_available_in_wallet",ao}const io=yield this.getNetwork();if(io&&io===ro.chainId)return;if(this.switchNetworkOnlyFromWallet)throw new DynamicError("Network switching is only supported through the wallet");if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching not supported");const oo=yield this.getWalletClientFromInitializedProvider();if(this.isMetaMask()){const ao=this.getDeepLink();ao&&(window.location.href=ao)}yield to.providerSwitchNetwork.call(this,{network:ro,provider:oo}),this.currentChainId=ro.chainId,this.hasSwitchedNetwork=!0,this.emit("chainChange",{chain:String(ro.chainId)})})}getConnectedAccounts(){return __awaiter$a(this,void 0,void 0,function*(){this.isInitialized===!1&&(yield this.initProvider(),this.refreshSession(),this.isInitialized=!0);const eo=this.getActiveAccount();return eo!=null&&eo.address?[eo.address]:[]})}isMetaMask(){var eo,to,ro,no,io;return(io=(no=(ro=(to=(eo=this.session)===null||eo===void 0?void 0:eo.peer)===null||to===void 0?void 0:to.metadata)===null||ro===void 0?void 0:ro.name)===null||no===void 0?void 0:no.toLowerCase().startsWith("metamask"))!==null&&io!==void 0?io:!1}getSupportedNetworks(){return __awaiter$a(this,void 0,void 0,function*(){var eo;if(yield this.initProvider(),this.refreshSession(),this.isMetaMask())return this.hasSwitchedNetwork?[String(this.currentChainId)]:this.evmNetworks.map(ro=>ro.chainId.toString());if(!this.session)return[];const to=[];return Object.keys(this.session.namespaces).forEach(ro=>{ro.startsWith("eip155:")&&to.push(ro.split(":")[1])}),(eo=this.session.namespaces.eip155)===null||eo===void 0||eo.accounts.forEach(ro=>to.push(ro.split(":")[1])),to.length?to:this.evmNetworks.map(ro=>ro.chainId.toString())})}}let InjectedWalletBase$1=class extends EthWalletConnector{constructor(){super(...arguments),this.supportedChains=["ETH","EVM"],this.connectedChain="EVM",this.walletConnectorFallback=!1}getEthProviderHelper(){return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.wallet&&!this.ethProviderHelper&&(this.ethProviderHelper=new EthProviderHelper(this.wallet,this)),this.ethProviderHelper}getMobileOrInstalledWallet(){var eo,to;return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.isInstalledOnBrowser()?this:!((to=(eo=this.wallet)===null||eo===void 0?void 0:eo.mobile)===null||to===void 0)&&to.inAppBrowser&&this.mobileExperience==="in-app-browser"&&isMobile$1()?this:this.walletConnectorFallback?new WalletConnect(Object.assign(Object.assign({},this.constructorProps),{walletName:this.name})):this}findProvider(){const eo=this.getEthProviderHelper();if(eo)return eo.getInstalledProvider()}setupEventListeners(){if(!this.getWalletClient())return;const to=this.getEthProviderHelper();if(!to)return;const{tearDownEventListeners:ro}=to._setupEventListeners(this);this.teardownEventListeners=ro}getWalletClient(eo){var to;return(to=this.getEthProviderHelper())===null||to===void 0?void 0:to.findWalletClient(eo)}isInstalledOnBrowser(){var eo;return((eo=this.getEthProviderHelper())===null||eo===void 0?void 0:eo.findProvider())!==void 0}getAddress(){return __awaiter$a(this,void 0,void 0,function*(){var eo;return(eo=this.getEthProviderHelper())===null||eo===void 0?void 0:eo.getAddress()})}connect(){return __awaiter$a(this,void 0,void 0,function*(){yield this.getAddress()})}signMessage(eo){return __awaiter$a(this,void 0,void 0,function*(){var to;return(to=this.getEthProviderHelper())===null||to===void 0?void 0:to.signMessage(eo)})}proveOwnership(eo,to){return __awaiter$a(this,void 0,void 0,function*(){return yield this.validateActiveWallet(eo),this.signMessage(to)})}endSession(){return __awaiter$a(this,void 0,void 0,function*(){})}providerSwitchNetwork(eo){const to=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$a(this,arguments,void 0,function*({network:ro,provider:no}){return to.providerSwitchNetwork.call(this,{network:ro,provider:no})})}};class PhantomEvm extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="Phantom",this.overrideKey="phantomevm",this.wallet=findWalletBookWallet(this.walletBook,this.key)}getAddress(){const eo=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$a(this,void 0,void 0,function*(){if(this.isInstalledOnBrowser())return eo.getAddress.call(this);isMobile$1()&&handleMobileWalletRedirect({nativeLink:"phantom://browse",universalLink:"https://phantom.app/ul/browse"})})}canGetChainAddress(){var eo,to;return!!(!((to=(eo=this.getEthProviderHelper())===null||eo===void 0?void 0:eo.findProvider())===null||to===void 0)&&to.selectedAddress)}}class ExodusEvm extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="ExodusEvm",this.overrideKey="exodusevm",this.walletConnectorFallback=!0,this.wallet=findWalletBookWallet(this.walletBook,this.key)}}let UnknownInjected$1=class extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="Unknown",this.overrideKey="unknown",this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}};class FallbackEvmConnector extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="Fallback Connector",this.overrideKey="fallbackconnector",this.isAvailable=!1,this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}}const injectedWalletOverrides$1=[PhantomEvm,ExodusEvm],filteredInjectedWalletKeysOverrides$1=["phantomevm","coinbase","exodusevm"],fetchInjectedWalletConnector=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).filter(([to,ro])=>{var no;return((no=ro.injectedConfig)===null||no===void 0?void 0:no.find(io=>io.chain==="evm"))&&!filteredInjectedWalletKeysOverrides$1.includes(to)}).map(([to,ro])=>{const{shortName:no}=ro,io=no||ro.name,oo=!!ro.walletConnect;return class extends InjectedWalletBase$1{constructor(ao){super(Object.assign({},ao)),this.name=io,this.wallet=ro,this.walletConnectorFallback=oo,this.overrideKey=to}getAddress(){const ao=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$a(this,void 0,void 0,function*(){var so;if(this.isInstalledOnBrowser())return ao.getAddress.call(this);const co=(so=this.wallet.mobile)===null||so===void 0?void 0:so.inAppBrowser;if(!co){const lo=new Error(`No inAppBrowserBase found for ${this.name}.`);throw logger$9.error(lo.message),lo}window.location.href=`${co}/${window.location.href}`})}}})},fetchWalletConnectWallets=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).filter(([,to])=>to.walletConnect&&!to.filterFromWalletConnect).map(([to,ro])=>{const{shortName:no}=ro,io=no||ro.name;return class extends WalletConnect{constructor(oo){super(Object.assign(Object.assign({},oo),{walletName:io})),this.overrideKey=to}}})},getWalletConnectConnector=()=>class extends WalletConnect{constructor(Xr){super(Object.assign(Object.assign({},Xr),{walletName:"WalletConnect"}))}};var dist={},CoinbaseWalletSDK$1={},walletLogo$1={};Object.defineProperty(walletLogo$1,"__esModule",{value:!0});walletLogo$1.walletLogo=void 0;const walletLogo=(Xr,eo)=>{let to;switch(Xr){case"standard":return to=eo,`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;case"circle":return to=eo,`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${eo}' height='${to}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;case"text":return to=(.1*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogo":return to=(.25*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;case"textLight":return to=(.1*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogoLight":return to=(.25*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;default:return to=eo,`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `}};walletLogo$1.walletLogo=walletLogo;var CoinbaseWalletProvider$1={};const require$$0$2=getAugmentedNamespace(eventemitter3$1);var error$2={},constants$5={};Object.defineProperty(constants$5,"__esModule",{value:!0});constants$5.errorValues=constants$5.standardErrorCodes=void 0;constants$5.standardErrorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}};constants$5.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}};var errors$1={},utils$2={};(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.serialize=Xr.getErrorCode=Xr.isValidCode=Xr.getMessageFromCode=Xr.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const eo=constants$5,to="Unspecified error message.";Xr.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function ro(ho,go=to){if(ho&&Number.isInteger(ho)){const yo=ho.toString();if(lo(eo.errorValues,yo))return eo.errorValues[yo].message;if(so(ho))return Xr.JSON_RPC_SERVER_ERROR_MESSAGE}return go}Xr.getMessageFromCode=ro;function no(ho){if(!Number.isInteger(ho))return!1;const go=ho.toString();return!!(eo.errorValues[go]||so(ho))}Xr.isValidCode=no;function io(ho){var go;if(typeof ho=="number")return ho;if(oo(ho))return(go=ho.code)!==null&&go!==void 0?go:ho.errorCode}Xr.getErrorCode=io;function oo(ho){return typeof ho=="object"&&ho!==null&&(typeof ho.code=="number"||typeof ho.errorCode=="number")}function ao(ho,{shouldIncludeStack:go=!1}={}){const yo={};if(ho&&typeof ho=="object"&&!Array.isArray(ho)&&lo(ho,"code")&&no(ho.code)){const vo=ho;yo.code=vo.code,vo.message&&typeof vo.message=="string"?(yo.message=vo.message,lo(vo,"data")&&(yo.data=vo.data)):(yo.message=ro(yo.code),yo.data={originalError:co(ho)})}else yo.code=eo.standardErrorCodes.rpc.internal,yo.message=fo(ho,"message")?ho.message:to,yo.data={originalError:co(ho)};return go&&(yo.stack=fo(ho,"stack")?ho.stack:void 0),yo}Xr.serialize=ao;function so(ho){return ho>=-32099&&ho<=-32e3}function co(ho){return ho&&typeof ho=="object"&&!Array.isArray(ho)?Object.assign({},ho):ho}function lo(ho,go){return Object.prototype.hasOwnProperty.call(ho,go)}function fo(ho,go){return typeof ho=="object"&&ho!==null&&go in ho&&typeof ho[go]=="string"}})(utils$2);Object.defineProperty(errors$1,"__esModule",{value:!0});errors$1.standardErrors=void 0;const constants_1$6=constants$5,utils_1$1=utils$2;errors$1.standardErrors={rpc:{parse:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.parse,Xr),invalidRequest:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidRequest,Xr),invalidParams:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidParams,Xr),methodNotFound:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotFound,Xr),internal:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.internal,Xr),server:Xr=>{if(!Xr||typeof Xr!="object"||Array.isArray(Xr))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:eo}=Xr;if(!Number.isInteger(eo)||eo>-32005||eo<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return getEthJsonRpcError(eo,Xr)},invalidInput:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidInput,Xr),resourceNotFound:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceNotFound,Xr),resourceUnavailable:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceUnavailable,Xr),transactionRejected:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.transactionRejected,Xr),methodNotSupported:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotSupported,Xr),limitExceeded:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.limitExceeded,Xr)},provider:{userRejectedRequest:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.userRejectedRequest,Xr),unauthorized:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unauthorized,Xr),unsupportedMethod:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedMethod,Xr),disconnected:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.disconnected,Xr),chainDisconnected:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.chainDisconnected,Xr),unsupportedChain:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedChain,Xr),custom:Xr=>{if(!Xr||typeof Xr!="object"||Array.isArray(Xr))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:eo,message:to,data:ro}=Xr;if(!to||typeof to!="string")throw new Error('"message" must be a nonempty string');return new EthereumProviderError(eo,to,ro)}}};function getEthJsonRpcError(Xr,eo){const[to,ro]=parseOpts(eo);return new EthereumRpcError(Xr,to||(0,utils_1$1.getMessageFromCode)(Xr),ro)}function getEthProviderError(Xr,eo){const[to,ro]=parseOpts(eo);return new EthereumProviderError(Xr,to||(0,utils_1$1.getMessageFromCode)(Xr),ro)}function parseOpts(Xr){if(Xr){if(typeof Xr=="string")return[Xr];if(typeof Xr=="object"&&!Array.isArray(Xr)){const{message:eo,data:to}=Xr;if(eo&&typeof eo!="string")throw new Error("Must specify string message.");return[eo||void 0,to]}}return[]}class EthereumRpcError extends Error{constructor(eo,to,ro){if(!Number.isInteger(eo))throw new Error('"code" must be an integer.');if(!to||typeof to!="string")throw new Error('"message" must be a nonempty string.');super(to),this.code=eo,ro!==void 0&&(this.data=ro)}}class EthereumProviderError extends EthereumRpcError{constructor(eo,to,ro){if(!isValidEthProviderCode(eo))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(eo,to,ro)}}function isValidEthProviderCode(Xr){return Number.isInteger(Xr)&&Xr>=1e3&&Xr<=4999}(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.standardErrors=Xr.standardErrorCodes=void 0;var eo=constants$5;Object.defineProperty(Xr,"standardErrorCodes",{enumerable:!0,get:function(){return eo.standardErrorCodes}});var to=errors$1;Object.defineProperty(Xr,"standardErrors",{enumerable:!0,get:function(){return to.standardErrors}})})(error$2);var serialize$1={},Web3Response={};Object.defineProperty(Web3Response,"__esModule",{value:!0});Web3Response.isErrorResponse=void 0;function isErrorResponse(Xr){return Xr.errorMessage!==void 0}Web3Response.isErrorResponse=isErrorResponse;var version$b={};Object.defineProperty(version$b,"__esModule",{value:!0});version$b.LIB_VERSION=void 0;version$b.LIB_VERSION="4.0.4";Object.defineProperty(serialize$1,"__esModule",{value:!0});serialize$1.serializeError=void 0;const Web3Response_1$2=Web3Response,version_1$3=version$b,constants_1$5=constants$5,utils_1=utils$2;function serializeError(Xr,eo){const to=(0,utils_1.serialize)(getErrorObject(Xr),{shouldIncludeStack:!0}),ro=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");ro.searchParams.set("version",version_1$3.LIB_VERSION),ro.searchParams.set("code",to.code.toString());const no=getMethod(to.data,eo);return no&&ro.searchParams.set("method",no),ro.searchParams.set("message",to.message),Object.assign(Object.assign({},to),{docUrl:ro.href})}serialize$1.serializeError=serializeError;function getErrorObject(Xr){return typeof Xr=="string"?{message:Xr,code:constants_1$5.standardErrorCodes.rpc.internal}:(0,Web3Response_1$2.isErrorResponse)(Xr)?Object.assign(Object.assign({},Xr),{message:Xr.errorMessage,code:Xr.errorCode,data:{method:Xr.method}}):Xr}function getMethod(Xr,eo){const to=Xr==null?void 0:Xr.method;if(to)return to;if(eo!==void 0){if(typeof eo=="string")return eo;if(Array.isArray(eo)){if(eo.length>0)return eo[0].method}else return eo.method}}var type$3={};Object.defineProperty(type$3,"__esModule",{value:!0});type$3.RegExpString=type$3.IntNumber=type$3.BigIntString=type$3.AddressString=type$3.HexString=type$3.OpaqueType=void 0;function OpaqueType(){return Xr=>Xr}type$3.OpaqueType=OpaqueType;type$3.HexString=OpaqueType();type$3.AddressString=OpaqueType();type$3.BigIntString=OpaqueType();function IntNumber(Xr){return Math.floor(Xr)}type$3.IntNumber=IntNumber;type$3.RegExpString=OpaqueType();var util$6={};Object.defineProperty(util$6,"__esModule",{value:!0});util$6.areAddressArraysEqual=util$6.getFavicon=util$6.range=util$6.isBigNumber=util$6.ensureParsedJSONObject=util$6.ensureBigInt=util$6.ensureRegExpString=util$6.ensureIntNumber=util$6.ensureBuffer=util$6.ensureAddressString=util$6.ensureEvenLengthHexString=util$6.ensureHexString=util$6.isHexString=util$6.prepend0x=util$6.strip0x=util$6.has0xPrefix=util$6.hexStringFromIntNumber=util$6.intNumberFromHexString=util$6.bigIntStringFromBigInt=util$6.hexStringFromBuffer=util$6.hexStringToUint8Array=util$6.uint8ArrayToHex=util$6.randomBytesHex=void 0;const error_1$8=error$2,_1=type$3,INT_STRING_REGEX=/^[0-9]*$/,HEXADECIMAL_STRING_REGEX=/^[a-f0-9]*$/;function randomBytesHex(Xr){return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(Xr)))}util$6.randomBytesHex=randomBytesHex;function uint8ArrayToHex(Xr){return[...Xr].map(eo=>eo.toString(16).padStart(2,"0")).join("")}util$6.uint8ArrayToHex=uint8ArrayToHex;function hexStringToUint8Array(Xr){return new Uint8Array(Xr.match(/.{1,2}/g).map(eo=>parseInt(eo,16)))}util$6.hexStringToUint8Array=hexStringToUint8Array;function hexStringFromBuffer(Xr,eo=!1){const to=Xr.toString("hex");return(0,_1.HexString)(eo?`0x${to}`:to)}util$6.hexStringFromBuffer=hexStringFromBuffer;function bigIntStringFromBigInt(Xr){return(0,_1.BigIntString)(Xr.toString(10))}util$6.bigIntStringFromBigInt=bigIntStringFromBigInt;function intNumberFromHexString(Xr){return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(Xr,!0))))}util$6.intNumberFromHexString=intNumberFromHexString;function hexStringFromIntNumber(Xr){return(0,_1.HexString)(`0x${BigInt(Xr).toString(16)}`)}util$6.hexStringFromIntNumber=hexStringFromIntNumber;function has0xPrefix(Xr){return Xr.startsWith("0x")||Xr.startsWith("0X")}util$6.has0xPrefix=has0xPrefix;function strip0x$1(Xr){return has0xPrefix(Xr)?Xr.slice(2):Xr}util$6.strip0x=strip0x$1;function prepend0x(Xr){return has0xPrefix(Xr)?`0x${Xr.slice(2)}`:`0x${Xr}`}util$6.prepend0x=prepend0x;function isHexString$1(Xr){if(typeof Xr!="string")return!1;const eo=strip0x$1(Xr).toLowerCase();return HEXADECIMAL_STRING_REGEX.test(eo)}util$6.isHexString=isHexString$1;function ensureHexString(Xr,eo=!1){if(typeof Xr=="string"){const to=strip0x$1(Xr).toLowerCase();if(HEXADECIMAL_STRING_REGEX.test(to))return(0,_1.HexString)(eo?`0x${to}`:to)}throw error_1$8.standardErrors.rpc.invalidParams(`"${String(Xr)}" is not a hexadecimal string`)}util$6.ensureHexString=ensureHexString;function ensureEvenLengthHexString(Xr,eo=!1){let to=ensureHexString(Xr,!1);return to.length%2===1&&(to=(0,_1.HexString)(`0${to}`)),eo?(0,_1.HexString)(`0x${to}`):to}util$6.ensureEvenLengthHexString=ensureEvenLengthHexString;function ensureAddressString(Xr){if(typeof Xr=="string"){const eo=strip0x$1(Xr).toLowerCase();if(isHexString$1(eo)&&eo.length===40)return(0,_1.AddressString)(prepend0x(eo))}throw error_1$8.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(Xr)}`)}util$6.ensureAddressString=ensureAddressString;function ensureBuffer(Xr){if(Buffer$3.isBuffer(Xr))return Xr;if(typeof Xr=="string"){if(isHexString$1(Xr)){const eo=ensureEvenLengthHexString(Xr,!1);return Buffer$3.from(eo,"hex")}return Buffer$3.from(Xr,"utf8")}throw error_1$8.standardErrors.rpc.invalidParams(`Not binary data: ${String(Xr)}`)}util$6.ensureBuffer=ensureBuffer;function ensureIntNumber(Xr){if(typeof Xr=="number"&&Number.isInteger(Xr))return(0,_1.IntNumber)(Xr);if(typeof Xr=="string"){if(INT_STRING_REGEX.test(Xr))return(0,_1.IntNumber)(Number(Xr));if(isHexString$1(Xr))return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(Xr,!0))))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(Xr)}`)}util$6.ensureIntNumber=ensureIntNumber;function ensureRegExpString(Xr){if(Xr instanceof RegExp)return(0,_1.RegExpString)(Xr.toString());throw error_1$8.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(Xr)}`)}util$6.ensureRegExpString=ensureRegExpString;function ensureBigInt(Xr){if(Xr!==null&&(typeof Xr=="bigint"||isBigNumber(Xr)))return BigInt(Xr.toString(10));if(typeof Xr=="number")return BigInt(ensureIntNumber(Xr));if(typeof Xr=="string"){if(INT_STRING_REGEX.test(Xr))return BigInt(Xr);if(isHexString$1(Xr))return BigInt(ensureEvenLengthHexString(Xr,!0))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(Xr)}`)}util$6.ensureBigInt=ensureBigInt;function ensureParsedJSONObject(Xr){if(typeof Xr=="string")return JSON.parse(Xr);if(typeof Xr=="object")return Xr;throw error_1$8.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(Xr)}`)}util$6.ensureParsedJSONObject=ensureParsedJSONObject;function isBigNumber(Xr){if(Xr==null||typeof Xr.constructor!="function")return!1;const{constructor:eo}=Xr;return typeof eo.config=="function"&&typeof eo.EUCLID=="number"}util$6.isBigNumber=isBigNumber;function range(Xr,eo){return Array.from({length:eo-Xr},(to,ro)=>Xr+ro)}util$6.range=range;function getFavicon(){const Xr=document.querySelector('link[sizes="192x192"]')||document.querySelector('link[sizes="180x180"]')||document.querySelector('link[rel="icon"]')||document.querySelector('link[rel="shortcut icon"]'),{protocol:eo,host:to}=document.location,ro=Xr?Xr.getAttribute("href"):null;return!ro||ro.startsWith("javascript:")||ro.startsWith("vbscript:")?null:ro.startsWith("http://")||ro.startsWith("https://")||ro.startsWith("data:")?ro:ro.startsWith("//")?eo+ro:`${eo}//${to}${ro}`}util$6.getFavicon=getFavicon;function areAddressArraysEqual(Xr,eo){return Xr.length===eo.length&&Xr.every((to,ro)=>to===eo[ro])}util$6.areAddressArraysEqual=areAddressArraysEqual;var util$5={},SCWSigner$1={},SCWKeyManager$1={},cipher={};Object.defineProperty(cipher,"__esModule",{value:!0});cipher.decryptContent=cipher.encryptContent=cipher.importKeyFromHexString=cipher.exportKeyToHexString=cipher.decrypt=cipher.encrypt=cipher.deriveSharedSecret=cipher.generateKeyPair=void 0;const util_1$b=util$6;async function generateKeyPair(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}cipher.generateKeyPair=generateKeyPair;async function deriveSharedSecret(Xr,eo){return crypto.subtle.deriveKey({name:"ECDH",public:eo},Xr,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}cipher.deriveSharedSecret=deriveSharedSecret;async function encrypt(Xr,eo){const to=crypto.getRandomValues(new Uint8Array(12)),ro=await crypto.subtle.encrypt({name:"AES-GCM",iv:to},Xr,new TextEncoder().encode(eo));return{iv:to,cipherText:ro}}cipher.encrypt=encrypt;async function decrypt(Xr,{iv:eo,cipherText:to}){const ro=await crypto.subtle.decrypt({name:"AES-GCM",iv:eo},Xr,to);return new TextDecoder().decode(ro)}cipher.decrypt=decrypt;function getFormat(Xr){switch(Xr){case"public":return"spki";case"private":return"pkcs8"}}async function exportKeyToHexString(Xr,eo){const to=getFormat(Xr),ro=await crypto.subtle.exportKey(to,eo);return(0,util_1$b.uint8ArrayToHex)(new Uint8Array(ro))}cipher.exportKeyToHexString=exportKeyToHexString;async function importKeyFromHexString(Xr,eo){const to=getFormat(Xr),ro=(0,util_1$b.hexStringToUint8Array)(eo).buffer;return await crypto.subtle.importKey(to,ro,{name:"ECDH",namedCurve:"P-256"},!0,Xr==="private"?["deriveKey"]:[])}cipher.importKeyFromHexString=importKeyFromHexString;async function encryptContent(Xr,eo){const to=JSON.stringify(Xr,(ro,no)=>{if(!(no instanceof Error))return no;const io=no;return Object.assign(Object.assign({},io.code?{code:io.code}:{}),{message:io.message})});return encrypt(eo,to)}cipher.encryptContent=encryptContent;async function decryptContent(Xr,eo){return JSON.parse(await decrypt(eo,Xr))}cipher.decryptContent=decryptContent;var ScopedLocalStorage$1={};Object.defineProperty(ScopedLocalStorage$1,"__esModule",{value:!0});ScopedLocalStorage$1.ScopedLocalStorage=void 0;class ScopedLocalStorage{constructor(eo,to){this.scope=eo,this.module=to}setItem(eo,to){localStorage.setItem(this.scopedKey(eo),to)}getItem(eo){return localStorage.getItem(this.scopedKey(eo))}removeItem(eo){localStorage.removeItem(this.scopedKey(eo))}clear(){const eo=this.scopedKey(""),to=[];for(let ro=0;rolocalStorage.removeItem(ro))}scopedKey(eo){return`-${this.scope}${this.module?`:${this.module}`:""}:${eo}`}static clearAll(){new ScopedLocalStorage("CBWSDK").clear(),new ScopedLocalStorage("walletlink").clear()}}ScopedLocalStorage$1.ScopedLocalStorage=ScopedLocalStorage;Object.defineProperty(SCWKeyManager$1,"__esModule",{value:!0});SCWKeyManager$1.SCWKeyManager=void 0;const cipher_1$1=cipher,ScopedLocalStorage_1$6=ScopedLocalStorage$1,OWN_PRIVATE_KEY={storageKey:"ownPrivateKey",keyType:"private"},OWN_PUBLIC_KEY={storageKey:"ownPublicKey",keyType:"public"},PEER_PUBLIC_KEY={storageKey:"peerPublicKey",keyType:"public"};class SCWKeyManager{constructor(){this.storage=new ScopedLocalStorage_1$6.ScopedLocalStorage("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(eo){this.sharedSecret=null,this.peerPublicKey=eo,await this.storeKey(PEER_PUBLIC_KEY,eo),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(OWN_PUBLIC_KEY.storageKey),this.storage.removeItem(OWN_PRIVATE_KEY.storageKey),this.storage.removeItem(PEER_PUBLIC_KEY.storageKey)}async generateKeyPair(){const eo=await(0,cipher_1$1.generateKeyPair)();this.ownPrivateKey=eo.privateKey,this.ownPublicKey=eo.publicKey,await this.storeKey(OWN_PRIVATE_KEY,eo.privateKey),await this.storeKey(OWN_PUBLIC_KEY,eo.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(OWN_PRIVATE_KEY)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(OWN_PUBLIC_KEY)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey(PEER_PUBLIC_KEY)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await(0,cipher_1$1.deriveSharedSecret)(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(eo){const to=this.storage.getItem(eo.storageKey);return to?(0,cipher_1$1.importKeyFromHexString)(eo.keyType,to):null}async storeKey(eo,to){const ro=await(0,cipher_1$1.exportKeyToHexString)(eo.keyType,to);this.storage.setItem(eo.storageKey,ro)}}SCWKeyManager$1.SCWKeyManager=SCWKeyManager;var SCWStateManager$1={};Object.defineProperty(SCWStateManager$1,"__esModule",{value:!0});SCWStateManager$1.SCWStateManager=void 0;const ScopedLocalStorage_1$5=ScopedLocalStorage$1,ACCOUNTS_KEY="accounts",ACTIVE_CHAIN_STORAGE_KEY="activeChain",AVAILABLE_CHAINS_STORAGE_KEY="availableChains",WALLET_CAPABILITIES_STORAGE_KEY="walletCapabilities";class SCWStateManager{get accounts(){return this._accounts}get activeChain(){return this._activeChain}get walletCapabilities(){return this._walletCapabilities}constructor(eo){var to,ro;this.storage=new ScopedLocalStorage_1$5.ScopedLocalStorage("CBWSDK","SCWStateManager"),this.updateListener=eo.updateListener,this.availableChains=this.loadItemFromStorage(AVAILABLE_CHAINS_STORAGE_KEY),this._walletCapabilities=this.loadItemFromStorage(WALLET_CAPABILITIES_STORAGE_KEY);const no=this.loadItemFromStorage(ACCOUNTS_KEY),io=this.loadItemFromStorage(ACTIVE_CHAIN_STORAGE_KEY);no&&this.updateListener.onAccountsUpdate({accounts:no,source:"storage"}),io&&this.updateListener.onChainUpdate({chain:io,source:"storage"}),this._accounts=no||[],this._activeChain=io||{id:(ro=(to=eo.appChainIds)===null||to===void 0?void 0:to[0])!==null&&ro!==void 0?ro:1}}updateAccounts(eo){this._accounts=eo,this.storeItemToStorage(ACCOUNTS_KEY,eo),this.updateListener.onAccountsUpdate({accounts:eo,source:"wallet"})}switchChain(eo){var to;const ro=(to=this.availableChains)===null||to===void 0?void 0:to.find(no=>no.id===eo);return ro?(ro===this._activeChain||(this._activeChain=ro,this.storeItemToStorage(ACTIVE_CHAIN_STORAGE_KEY,ro),this.updateListener.onChainUpdate({chain:ro,source:"wallet"})),!0):!1}updateAvailableChains(eo){if(!eo||Object.keys(eo).length===0)return;const to=Object.entries(eo).map(([ro,no])=>({id:Number(ro),rpcUrl:no}));this.availableChains=to,this.storeItemToStorage(AVAILABLE_CHAINS_STORAGE_KEY,to),this.switchChain(this._activeChain.id)}updateWalletCapabilities(eo){this._walletCapabilities=eo,this.storeItemToStorage(WALLET_CAPABILITIES_STORAGE_KEY,eo)}storeItemToStorage(eo,to){this.storage.setItem(eo,JSON.stringify(to))}loadItemFromStorage(eo){const to=this.storage.getItem(eo);return to?JSON.parse(to):void 0}clear(){this.storage.clear()}}SCWStateManager$1.SCWStateManager=SCWStateManager;Object.defineProperty(SCWSigner$1,"__esModule",{value:!0});SCWSigner$1.SCWSigner=void 0;const SCWKeyManager_1=SCWKeyManager$1,SCWStateManager_1=SCWStateManager$1,error_1$7=error$2,util_1$a=util$6,cipher_1=cipher;class SCWSigner{constructor(eo){this.metadata=eo.metadata,this.communicator=eo.communicator,this.keyManager=new SCWKeyManager_1.SCWKeyManager,this.stateManager=new SCWStateManager_1.SCWStateManager({appChainIds:this.metadata.appChainIds,updateListener:eo.updateListener}),this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(){const eo=await this.createRequestMessage({handshake:{method:"eth_requestAccounts",params:this.metadata}}),to=await this.communicator.postRequestAndWaitForResponse(eo);if("failure"in to.content)throw to.content.failure;const ro=await(0,cipher_1.importKeyFromHexString)("public",to.sender);await this.keyManager.setPeerPublicKey(ro);const no=await this.decryptResponseMessage(to);this.updateInternalState({method:"eth_requestAccounts"},no);const io=no.result;if("error"in io)throw io.error;return this.stateManager.accounts}async request(eo){const to=this.tryLocalHandling(eo);if(to!==void 0){if(to instanceof Error)throw to;return to}await this.communicator.waitForPopupLoaded();const ro=await this.sendEncryptedRequest(eo),no=await this.decryptResponseMessage(ro);this.updateInternalState(eo,no);const io=no.result;if("error"in io)throw io.error;return io.value}async disconnect(){this.stateManager.clear(),await this.keyManager.clear()}tryLocalHandling(eo){var to;switch(eo.method){case"wallet_switchEthereumChain":{const ro=eo.params;if(!ro||!(!((to=ro[0])===null||to===void 0)&&to.chainId))throw error_1$7.standardErrors.rpc.invalidParams();const no=(0,util_1$a.ensureIntNumber)(ro[0].chainId);return this.stateManager.switchChain(no)?null:void 0}case"wallet_getCapabilities":{const ro=this.stateManager.walletCapabilities;if(!ro)throw error_1$7.standardErrors.provider.unauthorized("No wallet capabilities found, please disconnect and reconnect");return ro}default:return}}async sendEncryptedRequest(eo){const to=await this.keyManager.getSharedSecret();if(!to)throw error_1$7.standardErrors.provider.unauthorized("No valid session found, try requestAccounts before other methods");const ro=await(0,cipher_1.encryptContent)({action:eo,chainId:this.stateManager.activeChain.id},to),no=await this.createRequestMessage({encrypted:ro});return this.communicator.postRequestAndWaitForResponse(no)}async createRequestMessage(eo){const to=await(0,cipher_1.exportKeyToHexString)("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:to,content:eo,timestamp:new Date}}async decryptResponseMessage(eo){const to=eo.content;if("failure"in to)throw to.failure;const ro=await this.keyManager.getSharedSecret();if(!ro)throw error_1$7.standardErrors.provider.unauthorized("Invalid session");return(0,cipher_1.decryptContent)(to.encrypted,ro)}updateInternalState(eo,to){var ro,no;const io=(ro=to.data)===null||ro===void 0?void 0:ro.chains;io&&this.stateManager.updateAvailableChains(io);const oo=(no=to.data)===null||no===void 0?void 0:no.capabilities;oo&&this.stateManager.updateWalletCapabilities(oo);const ao=to.result;if(!("error"in ao))switch(eo.method){case"eth_requestAccounts":{const so=ao.value;this.stateManager.updateAccounts(so);break}case"wallet_switchEthereumChain":{if(ao.value!==null)return;const so=eo.params,co=(0,util_1$a.ensureIntNumber)(so[0].chainId);this.stateManager.switchChain(co);break}}}}SCWSigner$1.SCWSigner=SCWSigner;var WalletLinkSigner$1={};const{Transform:Transform$1}=requireReadableBrowser$1();var keccak$3=Xr=>class A_ extends Transform$1{constructor(to,ro,no,io,oo){super(oo),this._rate=to,this._capacity=ro,this._delimitedSuffix=no,this._hashBitLength=io,this._options=oo,this._state=new Xr,this._state.initialize(to,ro),this._finalized=!1}_transform(to,ro,no){let io=null;try{this.update(to,ro)}catch(oo){io=oo}no(io)}_flush(to){let ro=null;try{this.push(this.digest())}catch(no){ro=no}to(ro)}update(to,ro){if(!Buffer$3.isBuffer(to)&&typeof to!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return Buffer$3.isBuffer(to)||(to=Buffer$3.from(to,ro)),this._state.absorb(to),this}digest(to){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let ro=this._state.squeeze(this._hashBitLength/8);return to!==void 0&&(ro=ro.toString(to)),this._resetState(),ro}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const to=new A_(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(to._state),to._finalized=this._finalized,to}};const{Transform}=requireReadableBrowser$1();var shake=Xr=>class P_ extends Transform{constructor(to,ro,no,io){super(io),this._rate=to,this._capacity=ro,this._delimitedSuffix=no,this._options=io,this._state=new Xr,this._state.initialize(to,ro),this._finalized=!1}_transform(to,ro,no){let io=null;try{this.update(to,ro)}catch(oo){io=oo}no(io)}_flush(){}_read(to){this.push(this.squeeze(to))}update(to,ro){if(!Buffer$3.isBuffer(to)&&typeof to!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return Buffer$3.isBuffer(to)||(to=Buffer$3.from(to,ro)),this._state.absorb(to),this}squeeze(to,ro){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let no=this._state.squeeze(to);return ro!==void 0&&(no=no.toString(ro)),no}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const to=new P_(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(to._state),to._finalized=this._finalized,to}};const createKeccak=keccak$3,createShake=shake;var api=function(Xr){const eo=createKeccak(Xr),to=createShake(Xr);return function(ro,no){switch(typeof ro=="string"?ro.toLowerCase():ro){case"keccak224":return new eo(1152,448,null,224,no);case"keccak256":return new eo(1088,512,null,256,no);case"keccak384":return new eo(832,768,null,384,no);case"keccak512":return new eo(576,1024,null,512,no);case"sha3-224":return new eo(1152,448,6,224,no);case"sha3-256":return new eo(1088,512,6,256,no);case"sha3-384":return new eo(832,768,6,384,no);case"sha3-512":return new eo(576,1024,6,512,no);case"shake128":return new to(1344,256,31,no);case"shake256":return new to(1088,512,31,no);default:throw new Error("Invald algorithm: "+ro)}}},keccakStateUnroll={};const P1600_ROUND_CONSTANTS=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];keccakStateUnroll.p1600=function(Xr){for(let eo=0;eo<24;++eo){const to=Xr[0]^Xr[10]^Xr[20]^Xr[30]^Xr[40],ro=Xr[1]^Xr[11]^Xr[21]^Xr[31]^Xr[41],no=Xr[2]^Xr[12]^Xr[22]^Xr[32]^Xr[42],io=Xr[3]^Xr[13]^Xr[23]^Xr[33]^Xr[43],oo=Xr[4]^Xr[14]^Xr[24]^Xr[34]^Xr[44],ao=Xr[5]^Xr[15]^Xr[25]^Xr[35]^Xr[45],so=Xr[6]^Xr[16]^Xr[26]^Xr[36]^Xr[46],co=Xr[7]^Xr[17]^Xr[27]^Xr[37]^Xr[47],lo=Xr[8]^Xr[18]^Xr[28]^Xr[38]^Xr[48],fo=Xr[9]^Xr[19]^Xr[29]^Xr[39]^Xr[49];let ho=lo^(no<<1|io>>>31),go=fo^(io<<1|no>>>31);const yo=Xr[0]^ho,vo=Xr[1]^go,wo=Xr[10]^ho,Eo=Xr[11]^go,ko=Xr[20]^ho,Ao=Xr[21]^go,Po=Xr[30]^ho,jo=Xr[31]^go,Mo=Xr[40]^ho,No=Xr[41]^go;ho=to^(oo<<1|ao>>>31),go=ro^(ao<<1|oo>>>31);const Do=Xr[2]^ho,Fo=Xr[3]^go,Xo=Xr[12]^ho,Lo=Xr[13]^go,Bo=Xr[22]^ho,xo=Xr[23]^go,uo=Xr[32]^ho,po=Xr[33]^go,bo=Xr[42]^ho,_o=Xr[43]^go;ho=no^(so<<1|co>>>31),go=io^(co<<1|so>>>31);const $o=Xr[4]^ho,Co=Xr[5]^go,Ro=Xr[14]^ho,So=Xr[15]^go,mo=Xr[24]^ho,To=Xr[25]^go,Vo=Xr[34]^ho,Zo=Xr[35]^go,Qo=Xr[44]^ho,qo=Xr[45]^go;ho=oo^(lo<<1|fo>>>31),go=ao^(fo<<1|lo>>>31);const Ho=Xr[6]^ho,$a=Xr[7]^go,zo=Xr[16]^ho,Ko=Xr[17]^go,_c=Xr[26]^ho,Cl=Xr[27]^go,ga=Xr[36]^ho,El=Xr[37]^go,Al=Xr[46]^ho,Ol=Xr[47]^go;ho=so^(to<<1|ro>>>31),go=co^(ro<<1|to>>>31);const Wl=Xr[8]^ho,zl=Xr[9]^go,Tl=Xr[18]^ho,Ml=Xr[19]^go,ou=Xr[28]^ho,Vl=Xr[29]^go,Ll=Xr[38]^ho,uu=Xr[39]^go,ru=Xr[48]^ho,tu=Xr[49]^go,ku=yo,au=vo,wl=Eo<<4|wo>>>28,Jo=wo<<4|Eo>>>28,Go=ko<<3|Ao>>>29,$l=Ao<<3|ko>>>29,Zl=jo<<9|Po>>>23,Ul=Po<<9|jo>>>23,Gl=Mo<<18|No>>>14,Nu=No<<18|Mo>>>14,hu=Do<<1|Fo>>>31,cu=Fo<<1|Do>>>31,Wu=Lo<<12|Xo>>>20,mu=Xo<<12|Lo>>>20,yu=Bo<<10|xo>>>22,Yu=xo<<10|Bo>>>22,_u=po<<13|uo>>>19,Il=uo<<13|po>>>19,Nl=bo<<2|_o>>>30,Pl=_o<<2|bo>>>30,Bl=Co<<30|$o>>>2,fu=$o<<30|Co>>>2,eu=Ro<<6|So>>>26,Xl=So<<6|Ro>>>26,$u=To<<11|mo>>>21,Yo=mo<<11|To>>>21,_l=Vo<<15|Zo>>>17,Sl=Zo<<15|Vo>>>17,Wo=qo<<29|Qo>>>3,xl=Qo<<29|qo>>>3,Ql=Ho<<28|$a>>>4,Fl=$a<<28|Ho>>>4,Jl=Ko<<23|zo>>>9,xu=zo<<23|Ko>>>9,lu=_c<<25|Cl>>>7,su=Cl<<25|_c>>>7,Xu=ga<<21|El>>>11,ju=El<<21|ga>>>11,zu=Ol<<24|Al>>>8,Ku=Al<<24|Ol>>>8,Hu=Wl<<27|zl>>>5,Gu=zl<<27|Wl>>>5,Zu=Tl<<20|Ml>>>12,Vu=Ml<<20|Tl>>>12,Ju=Vl<<7|ou>>>25,Uu=ou<<7|Vl>>>25,qu=Ll<<8|uu>>>24,Mu=uu<<8|Ll>>>24,Bu=ru<<14|tu>>>18,Au=tu<<14|ru>>>18;Xr[0]=ku^~Wu&$u,Xr[1]=au^~mu&Yo,Xr[10]=Ql^~Zu&Go,Xr[11]=Fl^~Vu&$l,Xr[20]=hu^~eu&lu,Xr[21]=cu^~Xl&su,Xr[30]=Hu^~wl&yu,Xr[31]=Gu^~Jo&Yu,Xr[40]=Bl^~Jl&Ju,Xr[41]=fu^~xu&Uu,Xr[2]=Wu^~$u&Xu,Xr[3]=mu^~Yo&ju,Xr[12]=Zu^~Go&_u,Xr[13]=Vu^~$l&Il,Xr[22]=eu^~lu&qu,Xr[23]=Xl^~su&Mu,Xr[32]=wl^~yu&_l,Xr[33]=Jo^~Yu&Sl,Xr[42]=Jl^~Ju&Zl,Xr[43]=xu^~Uu&Ul,Xr[4]=$u^~Xu&Bu,Xr[5]=Yo^~ju&Au,Xr[14]=Go^~_u&Wo,Xr[15]=$l^~Il&xl,Xr[24]=lu^~qu&Gl,Xr[25]=su^~Mu&Nu,Xr[34]=yu^~_l&zu,Xr[35]=Yu^~Sl&Ku,Xr[44]=Ju^~Zl&Nl,Xr[45]=Uu^~Ul&Pl,Xr[6]=Xu^~Bu&ku,Xr[7]=ju^~Au&au,Xr[16]=_u^~Wo&Ql,Xr[17]=Il^~xl&Fl,Xr[26]=qu^~Gl&hu,Xr[27]=Mu^~Nu&cu,Xr[36]=_l^~zu&Hu,Xr[37]=Sl^~Ku&Gu,Xr[46]=Zl^~Nl&Bl,Xr[47]=Ul^~Pl&fu,Xr[8]=Bu^~ku&Wu,Xr[9]=Au^~au&mu,Xr[18]=Wo^~Ql&Zu,Xr[19]=xl^~Fl&Vu,Xr[28]=Gl^~hu&eu,Xr[29]=Nu^~cu&Xl,Xr[38]=zu^~Hu&wl,Xr[39]=Ku^~Gu&Jo,Xr[48]=Nl^~Bl&Jl,Xr[49]=Pl^~fu&xu,Xr[0]^=P1600_ROUND_CONSTANTS[eo*2],Xr[1]^=P1600_ROUND_CONSTANTS[eo*2+1]}};const keccakState=keccakStateUnroll;function Keccak$1(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}Keccak$1.prototype.initialize=function(Xr,eo){for(let to=0;to<50;++to)this.state[to]=0;this.blockSize=Xr/8,this.count=0,this.squeezing=!1};Keccak$1.prototype.absorb=function(Xr){for(let eo=0;eo>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(keccakState.p1600(this.state),this.count=0);return eo};Keccak$1.prototype.copy=function(Xr){for(let eo=0;eo<50;++eo)Xr.state[eo]=this.state[eo];Xr.blockSize=this.blockSize,Xr.count=this.count,Xr.squeezing=this.squeezing};var keccak$2=Keccak$1,js$1=api(keccak$2);const createKeccakHash=js$1;function zeros(Xr){return Buffer$3.allocUnsafe(Xr).fill(0)}function bitLengthFromBigInt(Xr){return Xr.toString(2).length}function bufferBEFromBigInt(Xr,eo){let to=Xr.toString(16);to.length%2!==0&&(to="0"+to);const ro=to.match(/.{1,2}/g).map(no=>parseInt(no,16));for(;ro.length"u")throw new Error("Not an array?");if(to=parseTypeArray(Xr),to!=="dynamic"&&to!==0&&eo.length>to)throw new Error("Elements exceed array size: "+to);no=[],Xr=Xr.slice(0,Xr.lastIndexOf("[")),typeof eo=="string"&&(eo=JSON.parse(eo));for(io in eo)no.push(encodeSingle(Xr,eo[io]));if(to==="dynamic"){var oo=encodeSingle("uint256",eo.length);no.unshift(oo)}return Buffer$3.concat(no)}else{if(Xr==="bytes")return eo=new Buffer$3(eo),no=Buffer$3.concat([encodeSingle("uint256",eo.length),eo]),eo.length%32!==0&&(no=Buffer$3.concat([no,util$3.zeros(32-eo.length%32)])),no;if(Xr.startsWith("bytes")){if(to=parseTypeN(Xr),to<1||to>32)throw new Error("Invalid bytes width: "+to);return util$3.setLengthRight(eo,32)}else if(Xr.startsWith("uint")){if(to=parseTypeN(Xr),to%8||to<8||to>256)throw new Error("Invalid uint width: "+to);ro=parseNumber(eo);const ao=util$3.bitLengthFromBigInt(ro);if(ao>to)throw new Error("Supplied uint exceeds width: "+to+" vs "+ao);if(ro<0)throw new Error("Supplied uint is negative");return util$3.bufferBEFromBigInt(ro,32)}else if(Xr.startsWith("int")){if(to=parseTypeN(Xr),to%8||to<8||to>256)throw new Error("Invalid int width: "+to);ro=parseNumber(eo);const ao=util$3.bitLengthFromBigInt(ro);if(ao>to)throw new Error("Supplied int exceeds width: "+to+" vs "+ao);const so=util$3.twosFromBigInt(ro,256);return util$3.bufferBEFromBigInt(so,32)}else if(Xr.startsWith("ufixed")){if(to=parseTypeNxM(Xr),ro=parseNumber(eo),ro<0)throw new Error("Supplied ufixed is negative");return encodeSingle("uint256",ro*BigInt(2)**BigInt(to[1]))}else if(Xr.startsWith("fixed"))return to=parseTypeNxM(Xr),encodeSingle("int256",parseNumber(eo)*BigInt(2)**BigInt(to[1]))}throw new Error("Unsupported or invalid type: "+Xr)}function isDynamic(Xr){return Xr==="string"||Xr==="bytes"||parseTypeArray(Xr)==="dynamic"}function isArray$3(Xr){return Xr.lastIndexOf("]")===Xr.length-1}function rawEncode(Xr,eo){var to=[],ro=[],no=32*Xr.length;for(var io in Xr){var oo=elementaryName(Xr[io]),ao=eo[io],so=encodeSingle(oo,ao);isDynamic(oo)?(to.push(encodeSingle("uint256",no)),ro.push(so),no+=so.length):to.push(so)}return Buffer$3.concat(to.concat(ro))}function solidityPack(Xr,eo){if(Xr.length!==eo.length)throw new Error("Number of types are not matching the values");for(var to,ro,no=[],io=0;io32)throw new Error("Invalid bytes width: "+to);no.push(util$3.setLengthRight(ao,to))}else if(oo.startsWith("uint")){if(to=parseTypeN(oo),to%8||to<8||to>256)throw new Error("Invalid uint width: "+to);ro=parseNumber(ao);const so=util$3.bitLengthFromBigInt(ro);if(so>to)throw new Error("Supplied uint exceeds width: "+to+" vs "+so);no.push(util$3.bufferBEFromBigInt(ro,to/8))}else if(oo.startsWith("int")){if(to=parseTypeN(oo),to%8||to<8||to>256)throw new Error("Invalid int width: "+to);ro=parseNumber(ao);const so=util$3.bitLengthFromBigInt(ro);if(so>to)throw new Error("Supplied int exceeds width: "+to+" vs "+so);const co=util$3.twosFromBigInt(ro,to);no.push(util$3.bufferBEFromBigInt(co,to/8))}else throw new Error("Unsupported or invalid type: "+oo)}return Buffer$3.concat(no)}function soliditySHA3(Xr,eo){return util$3.keccak(solidityPack(Xr,eo))}var abi$1={rawEncode,solidityPack,soliditySHA3};const util$2=util$4,abi=abi$1,TYPED_MESSAGE_SCHEMA={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},TypedDataUtils={encodeData(Xr,eo,to,ro=!0){const no=["bytes32"],io=[this.hashType(Xr,to)];if(ro){const oo=(ao,so,co)=>{if(to[so]!==void 0)return["bytes32",co==null?"0x0000000000000000000000000000000000000000000000000000000000000000":util$2.keccak(this.encodeData(so,co,to,ro))];if(co===void 0)throw new Error(`missing value for field ${ao} of type ${so}`);if(so==="bytes")return["bytes32",util$2.keccak(co)];if(so==="string")return typeof co=="string"&&(co=Buffer$3.from(co,"utf8")),["bytes32",util$2.keccak(co)];if(so.lastIndexOf("]")===so.length-1){const lo=so.slice(0,so.lastIndexOf("[")),fo=co.map(ho=>oo(ao,lo,ho));return["bytes32",util$2.keccak(abi.rawEncode(fo.map(([ho])=>ho),fo.map(([,ho])=>ho)))]}return[so,co]};for(const ao of to[Xr]){const[so,co]=oo(ao.name,ao.type,eo[ao.name]);no.push(so),io.push(co)}}else for(const oo of to[Xr]){let ao=eo[oo.name];if(ao!==void 0)if(oo.type==="bytes")no.push("bytes32"),ao=util$2.keccak(ao),io.push(ao);else if(oo.type==="string")no.push("bytes32"),typeof ao=="string"&&(ao=Buffer$3.from(ao,"utf8")),ao=util$2.keccak(ao),io.push(ao);else if(to[oo.type]!==void 0)no.push("bytes32"),ao=util$2.keccak(this.encodeData(oo.type,ao,to,ro)),io.push(ao);else{if(oo.type.lastIndexOf("]")===oo.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");no.push(oo.type),io.push(ao)}}return abi.rawEncode(no,io)},encodeType(Xr,eo){let to="",ro=this.findTypeDependencies(Xr,eo).filter(no=>no!==Xr);ro=[Xr].concat(ro.sort());for(const no of ro){if(!eo[no])throw new Error("No type definition specified: "+no);to+=no+"("+eo[no].map(({name:oo,type:ao})=>ao+" "+oo).join(",")+")"}return to},findTypeDependencies(Xr,eo,to=[]){if(Xr=Xr.match(/^\w*/)[0],to.includes(Xr)||eo[Xr]===void 0)return to;to.push(Xr);for(const ro of eo[Xr])for(const no of this.findTypeDependencies(ro.type,eo,to))!to.includes(no)&&to.push(no);return to},hashStruct(Xr,eo,to,ro=!0){return util$2.keccak(this.encodeData(Xr,eo,to,ro))},hashType(Xr,eo){return util$2.keccak(this.encodeType(Xr,eo))},sanitizeData(Xr){const eo={};for(const to in TYPED_MESSAGE_SCHEMA.properties)Xr[to]&&(eo[to]=Xr[to]);return eo.types&&(eo.types=Object.assign({EIP712Domain:[]},eo.types)),eo},hash(Xr,eo=!0){const to=this.sanitizeData(Xr),ro=[Buffer$3.from("1901","hex")];return ro.push(this.hashStruct("EIP712Domain",to.domain,to.types,eo)),to.primaryType!=="EIP712Domain"&&ro.push(this.hashStruct(to.primaryType,to.message,to.types,eo)),util$2.keccak(Buffer$3.concat(ro))}};var ethEip712Util={TYPED_MESSAGE_SCHEMA,TypedDataUtils,hashForSignTypedDataLegacy:function(Xr){return typedSignatureHashLegacy(Xr.data)},hashForSignTypedData_v3:function(Xr){return TypedDataUtils.hash(Xr.data,!1)},hashForSignTypedData_v4:function(Xr){return TypedDataUtils.hash(Xr.data)}};function typedSignatureHashLegacy(Xr){const eo=new Error("Expect argument to be non-empty array");if(typeof Xr!="object"||!Xr.length)throw eo;const to=Xr.map(function(io){return io.type==="bytes"?util$2.toBuffer(io.value):io.value}),ro=Xr.map(function(io){return io.type}),no=Xr.map(function(io){if(!io.name)throw eo;return io.type+" "+io.name});return abi.soliditySHA3(["bytes32","bytes32"],[abi.soliditySHA3(new Array(Xr.length).fill("string"),no),abi.soliditySHA3(ro,to)])}var constants$4={};Object.defineProperty(constants$4,"__esModule",{value:!0});constants$4.APP_VERSION_KEY=constants$4.LOCAL_STORAGE_ADDRESSES_KEY=constants$4.WALLET_USER_NAME_KEY=void 0;constants$4.WALLET_USER_NAME_KEY="walletUsername";constants$4.LOCAL_STORAGE_ADDRESSES_KEY="Addresses";constants$4.APP_VERSION_KEY="AppVersion";var RelayEventManager$1={};Object.defineProperty(RelayEventManager$1,"__esModule",{value:!0});RelayEventManager$1.RelayEventManager=void 0;const util_1$9=util$6;class RelayEventManager{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const eo=this._nextRequestId,to=(0,util_1$9.prepend0x)(eo.toString(16));return this.callbacks.get(to)&&this.callbacks.delete(to),eo}}RelayEventManager$1.RelayEventManager=RelayEventManager;var WalletLinkRelay$1={},WalletLinkConnection$1={},WalletLinkCipher$1={};Object.defineProperty(WalletLinkCipher$1,"__esModule",{value:!0});WalletLinkCipher$1.WalletLinkCipher=void 0;const util_1$8=util$6;class WalletLinkCipher{constructor(eo){this.secret=eo}async encrypt(eo){const to=this.secret;if(to.length!==64)throw Error("secret must be 256 bits");const ro=crypto.getRandomValues(new Uint8Array(12)),no=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(to),{name:"aes-gcm"},!1,["encrypt","decrypt"]),io=new TextEncoder,oo=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:ro},no,io.encode(eo)),ao=16,so=oo.slice(oo.byteLength-ao),co=oo.slice(0,oo.byteLength-ao),lo=new Uint8Array(so),fo=new Uint8Array(co),ho=new Uint8Array([...ro,...lo,...fo]);return(0,util_1$8.uint8ArrayToHex)(ho)}async decrypt(eo){const to=this.secret;if(to.length!==64)throw Error("secret must be 256 bits");return new Promise((ro,no)=>{(async function(){const io=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(to),{name:"aes-gcm"},!1,["encrypt","decrypt"]),oo=(0,util_1$8.hexStringToUint8Array)(eo),ao=oo.slice(0,12),so=oo.slice(12,28),co=oo.slice(28),lo=new Uint8Array([...co,...so]),fo={name:"AES-GCM",iv:new Uint8Array(ao)};try{const ho=await window.crypto.subtle.decrypt(fo,io,lo),go=new TextDecoder;ro(go.decode(ho))}catch(ho){no(ho)}})()})}}WalletLinkCipher$1.WalletLinkCipher=WalletLinkCipher;var WalletLinkHTTP$1={};Object.defineProperty(WalletLinkHTTP$1,"__esModule",{value:!0});WalletLinkHTTP$1.WalletLinkHTTP=void 0;class WalletLinkHTTP{constructor(eo,to,ro){this.linkAPIUrl=eo,this.sessionId=to;const no=`${to}:${ro}`;this.auth=`Basic ${btoa(no)}`}async markUnseenEventsAsSeen(eo){return Promise.all(eo.map(to=>fetch(`${this.linkAPIUrl}/events/${to.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(to=>console.error("Unabled to mark event as failed:",to))}async fetchUnseenEvents(){var eo;const to=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(to.ok){const{events:ro,error:no}=await to.json();if(no)throw new Error(`Check unseen events failed: ${no}`);const io=(eo=ro==null?void 0:ro.filter(oo=>oo.event==="Web3Response").map(oo=>({type:"Event",sessionId:this.sessionId,eventId:oo.id,event:oo.event,data:oo.data})))!==null&&eo!==void 0?eo:[];return this.markUnseenEventsAsSeen(io),io}throw new Error(`Check unseen events failed: ${to.status}`)}}WalletLinkHTTP$1.WalletLinkHTTP=WalletLinkHTTP;var WalletLinkWebSocket$1={};Object.defineProperty(WalletLinkWebSocket$1,"__esModule",{value:!0});WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket$1.ConnectionState=void 0;var ConnectionState;(function(Xr){Xr[Xr.DISCONNECTED=0]="DISCONNECTED",Xr[Xr.CONNECTING=1]="CONNECTING",Xr[Xr.CONNECTED=2]="CONNECTED"})(ConnectionState||(WalletLinkWebSocket$1.ConnectionState=ConnectionState={}));class WalletLinkWebSocket{setConnectionStateListener(eo){this.connectionStateListener=eo}setIncomingDataListener(eo){this.incomingDataListener=eo}constructor(eo,to=WebSocket){this.WebSocketClass=to,this.webSocket=null,this.pendingData=[],this.url=eo.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((eo,to)=>{var ro;let no;try{this.webSocket=no=new this.WebSocketClass(this.url)}catch(io){to(io);return}(ro=this.connectionStateListener)===null||ro===void 0||ro.call(this,ConnectionState.CONNECTING),no.onclose=io=>{var oo;this.clearWebSocket(),to(new Error(`websocket error ${io.code}: ${io.reason}`)),(oo=this.connectionStateListener)===null||oo===void 0||oo.call(this,ConnectionState.DISCONNECTED)},no.onopen=io=>{var oo;eo(),(oo=this.connectionStateListener)===null||oo===void 0||oo.call(this,ConnectionState.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(so=>this.sendData(so)),this.pendingData=[])},no.onmessage=io=>{var oo,ao;if(io.data==="h")(oo=this.incomingDataListener)===null||oo===void 0||oo.call(this,{type:"Heartbeat"});else try{const so=JSON.parse(io.data);(ao=this.incomingDataListener)===null||ao===void 0||ao.call(this,so)}catch{}}})}disconnect(){var eo;const{webSocket:to}=this;if(to){this.clearWebSocket(),(eo=this.connectionStateListener)===null||eo===void 0||eo.call(this,ConnectionState.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{to.close()}catch{}}}sendData(eo){const{webSocket:to}=this;if(!to){this.pendingData.push(eo),this.connect();return}to.send(eo)}clearWebSocket(){const{webSocket:eo}=this;eo&&(this.webSocket=null,eo.onclose=null,eo.onerror=null,eo.onmessage=null,eo.onopen=null)}}WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket;Object.defineProperty(WalletLinkConnection$1,"__esModule",{value:!0});WalletLinkConnection$1.WalletLinkConnection=void 0;const constants_1$4=constants$4,WalletLinkCipher_1=WalletLinkCipher$1,WalletLinkHTTP_1=WalletLinkHTTP$1,WalletLinkWebSocket_1=WalletLinkWebSocket$1,type_1$1=type$3,HEARTBEAT_INTERVAL=1e4,REQUEST_TIMEOUT=6e4;class WalletLinkConnection{constructor({session:eo,linkAPIUrl:to,listener:ro,WebSocketClass:no=WebSocket}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=(0,type_1$1.IntNumber)(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=oo=>{if(!oo)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",so=>oo.JsonRpcUrl&&this.handleChainUpdated(so,oo.JsonRpcUrl)]]).forEach((so,co)=>{const lo=oo[co];lo!==void 0&&so(lo)})},this.handleDestroyed=oo=>{var ao;oo==="1"&&((ao=this.listener)===null||ao===void 0||ao.resetAndReload())},this.handleAccountUpdated=async oo=>{var ao;{const so=await this.cipher.decrypt(oo);(ao=this.listener)===null||ao===void 0||ao.accountUpdated(so)}},this.handleMetadataUpdated=async(oo,ao)=>{var so;{const co=await this.cipher.decrypt(ao);(so=this.listener)===null||so===void 0||so.metadataUpdated(oo,co)}},this.handleWalletUsernameUpdated=async oo=>{this.handleMetadataUpdated(constants_1$4.WALLET_USER_NAME_KEY,oo)},this.handleAppVersionUpdated=async oo=>{this.handleMetadataUpdated(constants_1$4.APP_VERSION_KEY,oo)},this.handleChainUpdated=async(oo,ao)=>{var so;{const co=await this.cipher.decrypt(oo),lo=await this.cipher.decrypt(ao);(so=this.listener)===null||so===void 0||so.chainUpdated(co,lo)}},this.session=eo,this.cipher=new WalletLinkCipher_1.WalletLinkCipher(eo.secret),this.listener=ro;const io=new WalletLinkWebSocket_1.WalletLinkWebSocket(`${to}/rpc`,no);io.setConnectionStateListener(async oo=>{let ao=!1;switch(oo){case WalletLinkWebSocket_1.ConnectionState.DISCONNECTED:if(!this.destroyed){const so=async()=>{await new Promise(co=>setTimeout(co,5e3)),this.destroyed||io.connect().catch(()=>{so()})};so()}break;case WalletLinkWebSocket_1.ConnectionState.CONNECTED:try{await this.authenticate(),this.sendIsLinked(),this.sendGetSessionConfig(),ao=!0}catch{}this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},HEARTBEAT_INTERVAL),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case WalletLinkWebSocket_1.ConnectionState.CONNECTING:break}this.connected!==ao&&(this.connected=ao)}),io.setIncomingDataListener(oo=>{var ao;switch(oo.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const so=oo.type==="IsLinkedOK"?oo.linked:void 0;this.linked=so||oo.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(oo.metadata);break}case"Event":{this.handleIncomingEvent(oo);break}}oo.id!==void 0&&((ao=this.requestResolutions.get(oo.id))===null||ao===void 0||ao(oo))}),this.ws=io,this.http=new WalletLinkHTTP_1.WalletLinkHTTP(to,eo.id,eo.key)}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}destroy(){this.destroyed=!0,this.ws.disconnect(),this.listener=void 0}get isDestroyed(){return this.destroyed}get connected(){return this._connected}set connected(eo){var to;this._connected=eo,eo&&((to=this.onceConnected)===null||to===void 0||to.call(this))}setOnceConnected(eo){return new Promise(to=>{this.connected?eo().then(to):this.onceConnected=()=>{eo().then(to),this.onceConnected=void 0}})}get linked(){return this._linked}set linked(eo){var to,ro;this._linked=eo,eo&&((to=this.onceLinked)===null||to===void 0||to.call(this)),(ro=this.listener)===null||ro===void 0||ro.linkedUpdated(eo)}setOnceLinked(eo){return new Promise(to=>{this.linked?eo().then(to):this.onceLinked=()=>{eo().then(to),this.onceLinked=void 0}})}async handleIncomingEvent(eo){var to;if(!(eo.type!=="Event"||eo.event!=="Web3Response")){const ro=await this.cipher.decrypt(eo.data),no=JSON.parse(ro);if(no.type!=="WEB3_RESPONSE")return;(to=this.listener)===null||to===void 0||to.handleWeb3ResponseMessage(no)}}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(eo=>setTimeout(eo,250));try{await this.fetchUnseenEventsAPI()}catch(eo){console.error("Unable to check for unseen events",eo)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(to=>this.handleIncomingEvent(to))}async setSessionMetadata(eo,to){const ro={type:"SetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,metadata:{[eo]:to}};return this.setOnceConnected(async()=>{const no=await this.makeRequest(ro);if(no.type==="Fail")throw new Error(no.error||"failed to set session metadata")})}async publishEvent(eo,to,ro=!1){const no=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},to),{origin:location.origin,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),io={type:"PublishEvent",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,event:eo,data:no,callWebhook:ro};return this.setOnceLinked(async()=>{const oo=await this.makeRequest(io);if(oo.type==="Fail")throw new Error(oo.error||"failed to publish event");return oo.eventId})}sendData(eo){this.ws.sendData(JSON.stringify(eo))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>HEARTBEAT_INTERVAL*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(eo,to=REQUEST_TIMEOUT){const ro=eo.id;this.sendData(eo);let no;return Promise.race([new Promise((io,oo)=>{no=window.setTimeout(()=>{oo(new Error(`request ${ro} timed out`))},to)}),new Promise(io=>{this.requestResolutions.set(ro,oo=>{clearTimeout(no),io(oo),this.requestResolutions.delete(ro)})})])}async authenticate(){const eo={type:"HostSession",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key},to=await this.makeRequest(eo);if(to.type==="Fail")throw new Error(to.error||"failed to authenticate")}sendIsLinked(){const eo={type:"IsLinked",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(eo)}sendGetSessionConfig(){const eo={type:"GetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(eo)}}WalletLinkConnection$1.WalletLinkConnection=WalletLinkConnection;var WalletLinkSession$1={};Object.defineProperty(WalletLinkSession$1,"__esModule",{value:!0});WalletLinkSession$1.WalletLinkSession=void 0;const sha_js_1=requireSha_js(),util_1$7=util$6,STORAGE_KEY_SESSION_ID="session:id",STORAGE_KEY_SESSION_SECRET="session:secret",STORAGE_KEY_SESSION_LINKED="session:linked";class WalletLinkSession{constructor(eo,to,ro,no){this._storage=eo,this._id=to||(0,util_1$7.randomBytesHex)(16),this._secret=ro||(0,util_1$7.randomBytesHex)(32),this._key=new sha_js_1.sha256().update(`${this._id}, ${this._secret} WalletLink`).digest("hex"),this._linked=!!no}static load(eo){const to=eo.getItem(STORAGE_KEY_SESSION_ID),ro=eo.getItem(STORAGE_KEY_SESSION_LINKED),no=eo.getItem(STORAGE_KEY_SESSION_SECRET);return to&&no?new WalletLinkSession(eo,to,no,ro==="1"):null}get id(){return this._id}get secret(){return this._secret}get key(){return this._key}get linked(){return this._linked}set linked(eo){this._linked=eo,this.persistLinked()}save(){return this._storage.setItem(STORAGE_KEY_SESSION_ID,this._id),this._storage.setItem(STORAGE_KEY_SESSION_SECRET,this._secret),this.persistLinked(),this}persistLinked(){this._storage.setItem(STORAGE_KEY_SESSION_LINKED,this._linked?"1":"0")}}WalletLinkSession$1.WalletLinkSession=WalletLinkSession;var util$1={};Object.defineProperty(util$1,"__esModule",{value:!0});util$1.isDarkMode=util$1.isMobileWeb=util$1.getLocation=util$1.createQrUrl=void 0;function createQrUrl(Xr,eo,to,ro,no,io){const oo=ro?"parent-id":"id",ao=new URLSearchParams({[oo]:Xr,secret:eo,server:to,v:no,chainId:io.toString()}).toString();return`${to}/#/link?${ao}`}util$1.createQrUrl=createQrUrl;function isInIFrame(){try{return window.frameElement!==null}catch{return!1}}function getLocation(){try{return isInIFrame()&&window.top?window.top.location:window.location}catch{return window.location}}util$1.getLocation=getLocation;function isMobileWeb(){var Xr;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((Xr=window==null?void 0:window.navigator)===null||Xr===void 0?void 0:Xr.userAgent)}util$1.isMobileWeb=isMobileWeb;function isDarkMode(){var Xr,eo;return(eo=(Xr=window==null?void 0:window.matchMedia)===null||Xr===void 0?void 0:Xr.call(window,"(prefers-color-scheme: dark)").matches)!==null&&eo!==void 0?eo:!1}util$1.isDarkMode=isDarkMode;var WalletLinkRelayUI$1={},cssReset={},cssResetCss={};Object.defineProperty(cssResetCss,"__esModule",{value:!0});cssResetCss.default='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';var __importDefault$4=commonjsGlobal&&commonjsGlobal.__importDefault||function(Xr){return Xr&&Xr.__esModule?Xr:{default:Xr}};Object.defineProperty(cssReset,"__esModule",{value:!0});cssReset.injectCssReset=void 0;const cssReset_css_1=__importDefault$4(cssResetCss);function injectCssReset(){const Xr=document.createElement("style");Xr.type="text/css",Xr.appendChild(document.createTextNode(cssReset_css_1.default)),document.documentElement.appendChild(Xr)}cssReset.injectCssReset=injectCssReset;var Snackbar={};function r$3(Xr){var eo,to,ro="";if(typeof Xr=="string"||typeof Xr=="number")ro+=Xr;else if(typeof Xr=="object")if(Array.isArray(Xr))for(eo=0;eo2&&(oo.children=arguments.length>3?n$1.call(arguments,2):to),typeof Xr=="function"&&Xr.defaultProps!=null)for(io in Xr.defaultProps)oo[io]===void 0&&(oo[io]=Xr.defaultProps[io]);return g$4(Xr,oo,ro,no,null)}function g$4(Xr,eo,to,ro,no){var io={type:Xr,props:eo,key:to,ref:ro,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:no??++u$3,__i:-1,__u:0};return no==null&&l$4.vnode!=null&&l$4.vnode(io),io}function m$2(){return{current:null}}function b$4(Xr){return Xr.children}function k$1(Xr,eo){this.props=Xr,this.context=eo}function x$3(Xr,eo){if(eo==null)return Xr.__?x$3(Xr.__,Xr.__i+1):null;for(var to;eoeo&&i$3.sort(f$5));M$2.__r=0}function P$3(Xr,eo,to,ro,no,io,oo,ao,so,co,lo){var fo,ho,go,yo,vo,wo=ro&&ro.__k||v$2,Eo=eo.length;for(to.__d=so,$$2(to,eo,wo),so=to.__d,fo=0;fo0?g$4(no.type,no.props,no.key,no.ref?no.ref:null,no.__v):no).__=Xr,no.__b=Xr.__b+1,io=null,(ao=no.__i=L$4(no,to,oo,lo))!==-1&&(lo--,(io=to[ao])&&(io.__u|=131072)),io==null||io.__v===null?(ao==-1&&fo--,typeof no.type!="function"&&(no.__u|=65536)):ao!==oo&&(ao==oo-1?fo--:ao==oo+1?fo++:(ao>oo?fo--:fo++,no.__u|=65536))):no=Xr.__k[ro]=null;if(lo)for(ro=0;ro(so!=null&&!(131072&so.__u)?1:0))for(;oo>=0||ao=0){if((so=eo[oo])&&!(131072&so.__u)&&no==so.key&&io===so.type)return oo;oo--}if(ao2&&(ao.children=arguments.length>3?n$1.call(arguments,2):to),g$4(Xr.type,ao,ro||Xr.key,no||Xr.ref,null)}function G$2(Xr,eo){var to={__c:eo="__cC"+a$3++,__:Xr,Consumer:function(ro,no){return ro.children(no)},Provider:function(ro){var no,io;return this.getChildContext||(no=new Set,(io={})[eo]=this,this.getChildContext=function(){return io},this.componentWillUnmount=function(){no=null},this.shouldComponentUpdate=function(oo){this.props.value!==oo.value&&no.forEach(function(ao){ao.__e=!0,S$3(ao)})},this.sub=function(oo){no.add(oo);var ao=oo.componentWillUnmount;oo.componentWillUnmount=function(){no&&no.delete(oo),ao&&ao.call(oo)}}),ro.children}};return to.Provider.__=to.Consumer.contextType=to}n$1=v$2.slice,l$4={__e:function(Xr,eo,to,ro){for(var no,io,oo;eo=eo.__;)if((no=eo.__c)&&!no.__)try{if((io=no.constructor)&&io.getDerivedStateFromError!=null&&(no.setState(io.getDerivedStateFromError(Xr)),oo=no.__d),no.componentDidCatch!=null&&(no.componentDidCatch(Xr,ro||{}),oo=no.__d),oo)return no.__E=no}catch(ao){Xr=ao}throw Xr}},u$3=0,t$3=function(Xr){return Xr!=null&&Xr.constructor==null},k$1.prototype.setState=function(Xr,eo){var to;to=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=d$5({},this.state),typeof Xr=="function"&&(Xr=Xr(d$5({},to),this.props)),Xr&&d$5(to,Xr),Xr!=null&&this.__v&&(eo&&this._sb.push(eo),S$3(this))},k$1.prototype.forceUpdate=function(Xr){this.__v&&(this.__e=!0,Xr&&this.__h.push(Xr),S$3(this))},k$1.prototype.render=b$4,i$3=[],r$2=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,f$5=function(Xr,eo){return Xr.__v.__b-eo.__v.__b},M$2.__r=0,e$2=0,c$2=F$4(!1),s$3=F$4(!0),a$3=0;const preact_module=Object.freeze(Object.defineProperty({__proto__:null,Component:k$1,Fragment:b$4,cloneElement:E$2,createContext:G$2,createElement:_$5,createRef:m$2,h:_$5,hydrate:D$2,get isValidElement(){return t$3},get options(){return l$4},render:B$3,toChildArray:H$2},Symbol.toStringTag,{value:"Module"})),require$$1=getAugmentedNamespace(preact_module);var t$2,r$1,u$2,i$2,o$2=0,f$4=[],c$1=l$4,e$1=c$1.__b,a$2=c$1.__r,v$1=c$1.diffed,l$3=c$1.__c,m$1=c$1.unmount,s$2=c$1.__;function d$4(Xr,eo){c$1.__h&&c$1.__h(r$1,Xr,o$2||eo),o$2=0;var to=r$1.__H||(r$1.__H={__:[],__h:[]});return Xr>=to.__.length&&to.__.push({}),to.__[Xr]}function h$3(Xr){return o$2=1,p$1(D$1,Xr)}function p$1(Xr,eo,to){var ro=d$4(t$2++,2);if(ro.t=Xr,!ro.__c&&(ro.__=[to?to(eo):D$1(void 0,eo),function(ao){var so=ro.__N?ro.__N[0]:ro.__[0],co=ro.t(so,ao);so!==co&&(ro.__N=[co,ro.__[1]],ro.__c.setState({}))}],ro.__c=r$1,!r$1.u)){var no=function(ao,so,co){if(!ro.__c.__H)return!0;var lo=ro.__c.__H.__.filter(function(ho){return!!ho.__c});if(lo.every(function(ho){return!ho.__N}))return!io||io.call(this,ao,so,co);var fo=!1;return lo.forEach(function(ho){if(ho.__N){var go=ho.__[0];ho.__=ho.__N,ho.__N=void 0,go!==ho.__[0]&&(fo=!0)}}),!(!fo&&ro.__c.props===ao)&&(!io||io.call(this,ao,so,co))};r$1.u=!0;var io=r$1.shouldComponentUpdate,oo=r$1.componentWillUpdate;r$1.componentWillUpdate=function(ao,so,co){if(this.__e){var lo=io;io=void 0,no(ao,so,co),io=lo}oo&&oo.call(this,ao,so,co)},r$1.shouldComponentUpdate=no}return ro.__N||ro.__}function y$5(Xr,eo){var to=d$4(t$2++,3);!c$1.__s&&C$4(to.__H,eo)&&(to.__=Xr,to.i=eo,r$1.__H.__h.push(to))}function _$4(Xr,eo){var to=d$4(t$2++,4);!c$1.__s&&C$4(to.__H,eo)&&(to.__=Xr,to.i=eo,r$1.__h.push(to))}function A$4(Xr){return o$2=5,T$5(function(){return{current:Xr}},[])}function F$3(Xr,eo,to){o$2=6,_$4(function(){return typeof Xr=="function"?(Xr(eo()),function(){return Xr(null)}):Xr?(Xr.current=eo(),function(){return Xr.current=null}):void 0},to==null?to:to.concat(Xr))}function T$5(Xr,eo){var to=d$4(t$2++,7);return C$4(to.__H,eo)&&(to.__=Xr(),to.__H=eo,to.__h=Xr),to.__}function q$3(Xr,eo){return o$2=8,T$5(function(){return Xr},eo)}function x$2(Xr){var eo=r$1.context[Xr.__c],to=d$4(t$2++,9);return to.c=Xr,eo?(to.__==null&&(to.__=!0,eo.sub(r$1)),eo.props.value):Xr.__}function P$2(Xr,eo){c$1.useDebugValue&&c$1.useDebugValue(eo?eo(Xr):Xr)}function b$3(Xr){var eo=d$4(t$2++,10),to=h$3();return eo.__=Xr,r$1.componentDidCatch||(r$1.componentDidCatch=function(ro,no){eo.__&&eo.__(ro,no),to[1](ro)}),[to[0],function(){to[1](void 0)}]}function g$3(){var Xr=d$4(t$2++,11);if(!Xr.__){for(var eo=r$1.__v;eo!==null&&!eo.__m&&eo.__!==null;)eo=eo.__;var to=eo.__m||(eo.__m=[0,0]);Xr.__="P"+to[0]+"-"+to[1]++}return Xr.__}function j$4(){for(var Xr;Xr=f$4.shift();)if(Xr.__P&&Xr.__H)try{Xr.__H.__h.forEach(z$3),Xr.__H.__h.forEach(B$2),Xr.__H.__h=[]}catch(eo){Xr.__H.__h=[],c$1.__e(eo,Xr.__v)}}c$1.__b=function(Xr){r$1=null,e$1&&e$1(Xr)},c$1.__=function(Xr,eo){Xr&&eo.__k&&eo.__k.__m&&(Xr.__m=eo.__k.__m),s$2&&s$2(Xr,eo)},c$1.__r=function(Xr){a$2&&a$2(Xr),t$2=0;var eo=(r$1=Xr.__c).__H;eo&&(u$2===r$1?(eo.__h=[],r$1.__h=[],eo.__.forEach(function(to){to.__N&&(to.__=to.__N),to.i=to.__N=void 0})):(eo.__h.forEach(z$3),eo.__h.forEach(B$2),eo.__h=[],t$2=0)),u$2=r$1},c$1.diffed=function(Xr){v$1&&v$1(Xr);var eo=Xr.__c;eo&&eo.__H&&(eo.__H.__h.length&&(f$4.push(eo)!==1&&i$2===c$1.requestAnimationFrame||((i$2=c$1.requestAnimationFrame)||w$2)(j$4)),eo.__H.__.forEach(function(to){to.i&&(to.__H=to.i),to.i=void 0})),u$2=r$1=null},c$1.__c=function(Xr,eo){eo.some(function(to){try{to.__h.forEach(z$3),to.__h=to.__h.filter(function(ro){return!ro.__||B$2(ro)})}catch(ro){eo.some(function(no){no.__h&&(no.__h=[])}),eo=[],c$1.__e(ro,to.__v)}}),l$3&&l$3(Xr,eo)},c$1.unmount=function(Xr){m$1&&m$1(Xr);var eo,to=Xr.__c;to&&to.__H&&(to.__H.__.forEach(function(ro){try{z$3(ro)}catch(no){eo=no}}),to.__H=void 0,eo&&c$1.__e(eo,to.__v))};var k=typeof requestAnimationFrame=="function";function w$2(Xr){var eo,to=function(){clearTimeout(ro),k&&cancelAnimationFrame(eo),setTimeout(Xr)},ro=setTimeout(to,100);k&&(eo=requestAnimationFrame(to))}function z$3(Xr){var eo=r$1,to=Xr.__c;typeof to=="function"&&(Xr.__c=void 0,to()),r$1=eo}function B$2(Xr){var eo=r$1;Xr.__c=Xr.__(),r$1=eo}function C$4(Xr,eo){return!Xr||Xr.length!==eo.length||eo.some(function(to,ro){return to!==Xr[ro]})}function D$1(Xr,eo){return typeof eo=="function"?eo(Xr):eo}const hooks_module=Object.freeze(Object.defineProperty({__proto__:null,useCallback:q$3,useContext:x$2,useDebugValue:P$2,useEffect:y$5,useErrorBoundary:b$3,useId:g$3,useImperativeHandle:F$3,useLayoutEffect:_$4,useMemo:T$5,useReducer:p$1,useRef:A$4,useState:h$3},Symbol.toStringTag,{value:"Module"})),require$$2$1=getAugmentedNamespace(hooks_module);var SnackbarCss={};Object.defineProperty(SnackbarCss,"__esModule",{value:!0});SnackbarCss.default=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}";(function(Xr){var eo=commonjsGlobal&&commonjsGlobal.__importDefault||function(ho){return ho&&ho.__esModule?ho:{default:ho}};Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.SnackbarInstance=Xr.SnackbarContainer=Xr.Snackbar=void 0;const to=eo(require$$0$1),ro=require$$1,no=require$$2$1,io=util$1,oo=eo(SnackbarCss),ao="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",so="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class co{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=(0,io.isDarkMode)()}attach(go){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",go.appendChild(this.root),this.render()}presentItem(go){const yo=this.nextItemKey++;return this.items.set(yo,go),this.render(),()=>{this.items.delete(yo),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,ro.render)((0,ro.h)("div",null,(0,ro.h)(Xr.SnackbarContainer,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([go,yo])=>(0,ro.h)(Xr.SnackbarInstance,Object.assign({},yo,{key:go}))))),this.root)}}Xr.Snackbar=co;const lo=ho=>(0,ro.h)("div",{class:(0,to.default)("-cbwsdk-snackbar-container")},(0,ro.h)("style",null,oo.default),(0,ro.h)("div",{class:"-cbwsdk-snackbar"},ho.children));Xr.SnackbarContainer=lo;const fo=({autoExpand:ho,message:go,menuItems:yo})=>{const[vo,wo]=(0,no.useState)(!0),[Eo,ko]=(0,no.useState)(ho??!1);(0,no.useEffect)(()=>{const Po=[window.setTimeout(()=>{wo(!1)},1),window.setTimeout(()=>{ko(!0)},1e4)];return()=>{Po.forEach(window.clearTimeout)}});const Ao=()=>{ko(!Eo)};return(0,ro.h)("div",{class:(0,to.default)("-cbwsdk-snackbar-instance",vo&&"-cbwsdk-snackbar-instance-hidden",Eo&&"-cbwsdk-snackbar-instance-expanded")},(0,ro.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:Ao},(0,ro.h)("img",{src:ao,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,ro.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},go),(0,ro.h)("div",{class:"-gear-container"},!Eo&&(0,ro.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,ro.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,ro.h)("img",{src:so,class:"-gear-icon",title:"Expand"}))),yo&&yo.length>0&&(0,ro.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},yo.map((Po,jo)=>(0,ro.h)("div",{class:(0,to.default)("-cbwsdk-snackbar-instance-menu-item",Po.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:Po.onClick,key:jo},(0,ro.h)("svg",{width:Po.svgWidth,height:Po.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,ro.h)("path",{"fill-rule":Po.defaultFillRule,"clip-rule":Po.defaultClipRule,d:Po.path,fill:"#AAAAAA"})),(0,ro.h)("span",{class:(0,to.default)("-cbwsdk-snackbar-instance-menu-item-info",Po.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},Po.info)))))};Xr.SnackbarInstance=fo})(Snackbar);Object.defineProperty(WalletLinkRelayUI$1,"__esModule",{value:!0});WalletLinkRelayUI$1.WalletLinkRelayUI=void 0;const cssReset_1$1=cssReset,Snackbar_1$1=Snackbar;class WalletLinkRelayUI{constructor(){this.attached=!1,this.snackbar=new Snackbar_1$1.Snackbar}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const eo=document.documentElement,to=document.createElement("div");to.className="-cbwsdk-css-reset",eo.appendChild(to),this.snackbar.attach(to),this.attached=!0,(0,cssReset_1$1.injectCssReset)()}showConnecting(eo){let to;return eo.isUnlinkedErrorState?to={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:eo.onResetConnection}]}:to={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:eo.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:eo.onResetConnection}]},this.snackbar.presentItem(to)}}WalletLinkRelayUI$1.WalletLinkRelayUI=WalletLinkRelayUI;var WLMobileRelayUI$1={},RedirectDialog$1={},RedirectDialogCss={};Object.defineProperty(RedirectDialogCss,"__esModule",{value:!0});RedirectDialogCss.default=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";var __importDefault$3=commonjsGlobal&&commonjsGlobal.__importDefault||function(Xr){return Xr&&Xr.__esModule?Xr:{default:Xr}};Object.defineProperty(RedirectDialog$1,"__esModule",{value:!0});RedirectDialog$1.RedirectDialog=void 0;const clsx_1=__importDefault$3(require$$0$1),preact_1=require$$1,cssReset_1=cssReset,Snackbar_1=Snackbar,util_1$6=util$1,RedirectDialog_css_1=__importDefault$3(RedirectDialogCss);class RedirectDialog{constructor(){this.root=null,this.darkMode=(0,util_1$6.isDarkMode)()}attach(){const eo=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",eo.appendChild(this.root),(0,cssReset_1.injectCssReset)()}present(eo){this.render(eo)}clear(){this.render(null)}render(eo){this.root&&((0,preact_1.render)(null,this.root),eo&&(0,preact_1.render)((0,preact_1.h)(RedirectDialogContent,Object.assign({},eo,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}RedirectDialog$1.RedirectDialog=RedirectDialog;const RedirectDialogContent=({title:Xr,buttonText:eo,darkMode:to,onButtonClick:ro,onDismiss:no})=>{const io=to?"dark":"light";return(0,preact_1.h)(Snackbar_1.SnackbarContainer,{darkMode:to},(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,preact_1.h)("style",null,RedirectDialog_css_1.default),(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:no}),(0,preact_1.h)("div",{class:(0,clsx_1.default)("-cbwsdk-redirect-dialog-box",io)},(0,preact_1.h)("p",null,Xr),(0,preact_1.h)("button",{onClick:ro},eo))))};var constants$3={};Object.defineProperty(constants$3,"__esModule",{value:!0});constants$3.CBW_MOBILE_DEEPLINK_URL=constants$3.WALLETLINK_URL=constants$3.CB_KEYS_URL=void 0;constants$3.CB_KEYS_URL="https://keys.coinbase.com/connect";constants$3.WALLETLINK_URL="https://www.walletlink.org";constants$3.CBW_MOBILE_DEEPLINK_URL="https://go.cb-w.com/walletlink";Object.defineProperty(WLMobileRelayUI$1,"__esModule",{value:!0});WLMobileRelayUI$1.WLMobileRelayUI=void 0;const RedirectDialog_1=RedirectDialog$1,util_1$5=util$1,constants_1$3=constants$3;class WLMobileRelayUI{constructor(){this.attached=!1,this.redirectDialog=new RedirectDialog_1.RedirectDialog}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(eo){const to=new URL(constants_1$3.CBW_MOBILE_DEEPLINK_URL);to.searchParams.append("redirect_url",(0,util_1$5.getLocation)().href),eo&&to.searchParams.append("wl_url",eo);const ro=document.createElement("a");ro.target="cbw-opener",ro.href=to.href,ro.rel="noreferrer noopener",ro.click()}openCoinbaseWalletDeeplink(eo){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(eo)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(eo)},99)}showConnecting(eo){return()=>{this.redirectDialog.clear()}}}WLMobileRelayUI$1.WLMobileRelayUI=WLMobileRelayUI;Object.defineProperty(WalletLinkRelay$1,"__esModule",{value:!0});WalletLinkRelay$1.WalletLinkRelay=void 0;const WalletLinkConnection_1=WalletLinkConnection$1,constants_1$2=constants$4,RelayEventManager_1$1=RelayEventManager$1,WalletLinkSession_1=WalletLinkSession$1,Web3Response_1$1=Web3Response,util_1$4=util$1,WalletLinkRelayUI_1=WalletLinkRelayUI$1,WLMobileRelayUI_1=WLMobileRelayUI$1,error_1$6=error$2,util_2$1=util$6,ScopedLocalStorage_1$4=ScopedLocalStorage$1;class WalletLinkRelay{constructor(eo){this.accountsCallback=null,this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.chainCallback=null,this.dappDefaultChain=1,this.isMobileWeb=(0,util_1$4.isMobileWeb)(),this.appName="",this.appLogoUrl=null,this.linkedUpdated=io=>{this.isLinked=io;const oo=this.storage.getItem(constants_1$2.LOCAL_STORAGE_ADDRESSES_KEY);if(io&&(this._session.linked=io),this.isUnlinkedErrorState=!1,oo){const ao=oo.split(" "),so=this.storage.getItem("IsStandaloneSigning")==="true";ao[0]!==""&&!io&&this._session.linked&&!so&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(io,oo)=>{this.storage.setItem(io,oo)},this.chainUpdated=(io,oo)=>{this.chainCallbackParams.chainId===io&&this.chainCallbackParams.jsonRpcUrl===oo||(this.chainCallbackParams={chainId:io,jsonRpcUrl:oo},this.chainCallback&&this.chainCallback(io,oo))},this.accountUpdated=io=>{this.accountsCallback&&this.accountsCallback([io]),WalletLinkRelay.accountRequestCallbackIds.size>0&&(Array.from(WalletLinkRelay.accountRequestCallbackIds.values()).forEach(oo=>{const ao={type:"WEB3_RESPONSE",id:oo,response:{method:"requestEthereumAccounts",result:[io]}};this.invokeCallback(Object.assign(Object.assign({},ao),{id:oo}))}),WalletLinkRelay.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=eo.linkAPIUrl,this.storage=eo.storage;const{session:to,ui:ro,connection:no}=this.subscribe();this._session=to,this.connection=no,this.relayEventManager=new RelayEventManager_1$1.RelayEventManager,this.ui=ro}subscribe(){const eo=WalletLinkSession_1.WalletLinkSession.load(this.storage)||new WalletLinkSession_1.WalletLinkSession(this.storage).save(),{linkAPIUrl:to}=this,ro=new WalletLinkConnection_1.WalletLinkConnection({session:eo,linkAPIUrl:to,listener:this}),no=this.isMobileWeb?new WLMobileRelayUI_1.WLMobileRelayUI:new WalletLinkRelayUI_1.WalletLinkRelayUI;return ro.connect(),{session:eo,ui:no,connection:ro}}attachUI(){this.ui.attach()}resetAndReload(){Promise.race([this.connection.setSessionMetadata("__destroyed","1"),new Promise(eo=>setTimeout(()=>eo(null),1e3))]).then(()=>{this.connection.destroy();const eo=WalletLinkSession_1.WalletLinkSession.load(this.storage);(eo==null?void 0:eo.id)===this._session.id&&ScopedLocalStorage_1$4.ScopedLocalStorage.clearAll(),document.location.reload()}).catch(eo=>{})}setAppInfo(eo,to){this.appName=eo,this.appLogoUrl=to}getStorageItem(eo){return this.storage.getItem(eo)}setStorageItem(eo,to){this.storage.setItem(eo,to)}signEthereumMessage(eo,to,ro,no){return this.sendRequest({method:"signEthereumMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(eo,!0),address:to,addPrefix:ro,typedDataJson:no||null}})}ethereumAddressFromSignedMessage(eo,to,ro){return this.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(eo,!0),signature:(0,util_2$1.hexStringFromBuffer)(to,!0),addPrefix:ro}})}signEthereumTransaction(eo){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:eo.fromAddress,toAddress:eo.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(eo.weiValue),data:(0,util_2$1.hexStringFromBuffer)(eo.data,!0),nonce:eo.nonce,gasPriceInWei:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,maxFeePerGas:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,maxPriorityFeePerGas:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,gasLimit:eo.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(eo.gasLimit):null,chainId:eo.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(eo){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:eo.fromAddress,toAddress:eo.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(eo.weiValue),data:(0,util_2$1.hexStringFromBuffer)(eo.data,!0),nonce:eo.nonce,gasPriceInWei:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,maxFeePerGas:eo.maxFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(eo.maxFeePerGas):null,maxPriorityFeePerGas:eo.maxPriorityFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(eo.maxPriorityFeePerGas):null,gasLimit:eo.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(eo.gasLimit):null,chainId:eo.chainId,shouldSubmit:!0}})}submitEthereumTransaction(eo,to){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:(0,util_2$1.hexStringFromBuffer)(eo,!0),chainId:to}})}scanQRCode(eo){return this.sendRequest({method:"scanQRCode",params:{regExp:eo}})}getWalletLinkSession(){return this._session}genericRequest(eo,to){return this.sendRequest({method:"generic",params:{action:to,data:eo}})}sendGenericMessage(eo){return this.sendRequest(eo)}sendRequest(eo){let to=null;const ro=(0,util_2$1.randomBytesHex)(8),no=io=>{this.publishWeb3RequestCanceledEvent(ro),this.handleErrorResponse(ro,eo.method,io),to==null||to()};return new Promise((io,oo)=>{to=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:no,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(ro,ao=>{if(to==null||to(),(0,Web3Response_1$1.isErrorResponse)(ao))return oo(new Error(ao.errorMessage));io(ao)}),this.publishWeb3RequestEvent(ro,eo)})}setAccountsCallback(eo){this.accountsCallback=eo}setChainCallback(eo){this.chainCallback=eo}setDappDefaultChainCallback(eo){this.dappDefaultChain=eo}publishWeb3RequestEvent(eo,to){const ro={type:"WEB3_REQUEST",id:eo,request:to};this.publishEvent("Web3Request",ro,!0).then(no=>{}).catch(no=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:ro.id,response:{method:to.method,errorMessage:no.message}})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(to.method)}openCoinbaseWalletDeeplink(eo){if(this.ui instanceof WLMobileRelayUI_1.WLMobileRelayUI)switch(eo){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(eo){const to={type:"WEB3_REQUEST_CANCELED",id:eo};this.publishEvent("Web3RequestCanceled",to,!1).then()}publishEvent(eo,to,ro){return this.connection.publishEvent(eo,to,ro)}handleWeb3ResponseMessage(eo){const{response:to}=eo;if(to.method==="requestEthereumAccounts"){WalletLinkRelay.accountRequestCallbackIds.forEach(ro=>this.invokeCallback(Object.assign(Object.assign({},eo),{id:ro}))),WalletLinkRelay.accountRequestCallbackIds.clear();return}this.invokeCallback(eo)}handleErrorResponse(eo,to,ro){var no;const io=(no=ro==null?void 0:ro.message)!==null&&no!==void 0?no:"Unspecified error message.";this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:eo,response:{method:to,errorMessage:io}})}invokeCallback(eo){const to=this.relayEventManager.callbacks.get(eo.id);to&&(to(eo.response),this.relayEventManager.callbacks.delete(eo.id))}requestEthereumAccounts(){const eo={method:"requestEthereumAccounts",params:{appName:this.appName,appLogoUrl:this.appLogoUrl||null}},to=(0,util_2$1.randomBytesHex)(8);return new Promise((ro,no)=>{this.relayEventManager.callbacks.set(to,io=>{if((0,Web3Response_1$1.isErrorResponse)(io))return no(new Error(io.errorMessage));ro(io)}),WalletLinkRelay.accountRequestCallbackIds.add(to),this.publishWeb3RequestEvent(to,eo)})}watchAsset(eo,to,ro,no,io,oo){const ao={method:"watchAsset",params:{type:eo,options:{address:to,symbol:ro,decimals:no,image:io},chainId:oo}};let so=null;const co=(0,util_2$1.randomBytesHex)(8),lo=fo=>{this.publishWeb3RequestCanceledEvent(co),this.handleErrorResponse(co,ao.method,fo),so==null||so()};return so=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:lo,onResetConnection:this.resetAndReload}),new Promise((fo,ho)=>{this.relayEventManager.callbacks.set(co,go=>{if(so==null||so(),(0,Web3Response_1$1.isErrorResponse)(go))return ho(new Error(go.errorMessage));fo(go)}),this.publishWeb3RequestEvent(co,ao)})}addEthereumChain(eo,to,ro,no,io,oo){const ao={method:"addEthereumChain",params:{chainId:eo,rpcUrls:to,blockExplorerUrls:no,chainName:io,iconUrls:ro,nativeCurrency:oo}};let so=null;const co=(0,util_2$1.randomBytesHex)(8),lo=fo=>{this.publishWeb3RequestCanceledEvent(co),this.handleErrorResponse(co,ao.method,fo),so==null||so()};return so=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:lo,onResetConnection:this.resetAndReload}),new Promise((fo,ho)=>{this.relayEventManager.callbacks.set(co,go=>{if(so==null||so(),(0,Web3Response_1$1.isErrorResponse)(go))return ho(new Error(go.errorMessage));fo(go)}),this.publishWeb3RequestEvent(co,ao)})}switchEthereumChain(eo,to){const ro={method:"switchEthereumChain",params:Object.assign({chainId:eo},{address:to})},no=(0,util_2$1.randomBytesHex)(8);return new Promise((io,oo)=>{this.relayEventManager.callbacks.set(no,ao=>{if((0,Web3Response_1$1.isErrorResponse)(ao)&&ao.errorCode)return oo(error_1$6.standardErrors.provider.custom({code:ao.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if((0,Web3Response_1$1.isErrorResponse)(ao))return oo(new Error(ao.errorMessage));io(ao)}),this.publishWeb3RequestEvent(no,ro)})}}WalletLinkRelay$1.WalletLinkRelay=WalletLinkRelay;WalletLinkRelay.accountRequestCallbackIds=new Set;var __importDefault$2=commonjsGlobal&&commonjsGlobal.__importDefault||function(Xr){return Xr&&Xr.__esModule?Xr:{default:Xr}};Object.defineProperty(WalletLinkSigner$1,"__esModule",{value:!0});WalletLinkSigner$1.WalletLinkSigner=void 0;const eth_eip712_util_1=__importDefault$2(ethEip712Util),constants_1$1=constants$4,RelayEventManager_1=RelayEventManager$1,Web3Response_1=Web3Response,WalletLinkRelay_1=WalletLinkRelay$1,constants_2=constants$3,error_1$5=error$2,util_1$3=util$6,ScopedLocalStorage_1$3=ScopedLocalStorage$1,DEFAULT_CHAIN_ID_KEY="DefaultChainId",DEFAULT_JSON_RPC_URL="DefaultJsonRpcUrl";class WalletLinkSigner{constructor(eo){var to,ro;this._relay=null,this._addresses=[],this.hasMadeFirstChainChangedEmission=!1;const{appName:no,appLogoUrl:io}=eo.metadata;this._appName=no,this._appLogoUrl=io,this._storage=new ScopedLocalStorage_1$3.ScopedLocalStorage("walletlink",constants_2.WALLETLINK_URL),this.updateListener=eo.updateListener,this._relayEventManager=new RelayEventManager_1.RelayEventManager,this._jsonRpcUrlFromOpts="";const oo=this._storage.getItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY);if(oo){const so=oo.split(" ");so[0]!==""&&(this._addresses=so.map(co=>(0,util_1$3.ensureAddressString)(co)),(to=this.updateListener)===null||to===void 0||to.onAccountsUpdate({accounts:this._addresses,source:"storage"}))}this._storage.getItem(DEFAULT_CHAIN_ID_KEY)&&((ro=this.updateListener)===null||ro===void 0||ro.onChainUpdate({chain:{id:this.getChainId(),rpcUrl:this.jsonRpcUrl},source:"storage"}),this.hasMadeFirstChainChangedEmission=!0),this.initializeRelay()}getSession(){const eo=this.initializeRelay(),{id:to,secret:ro}=eo.getWalletLinkSession();return{id:to,secret:ro}}async handshake(){return await this.request({method:"eth_requestAccounts"})}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var eo;return(eo=this._storage.getItem(DEFAULT_JSON_RPC_URL))!==null&&eo!==void 0?eo:this._jsonRpcUrlFromOpts}set jsonRpcUrl(eo){this._storage.setItem(DEFAULT_JSON_RPC_URL,eo)}updateProviderInfo(eo,to){var ro;this.jsonRpcUrl=eo;const no=this.getChainId();this._storage.setItem(DEFAULT_CHAIN_ID_KEY,to.toString(10)),((0,util_1$3.ensureIntNumber)(to)!==no||!this.hasMadeFirstChainChangedEmission)&&((ro=this.updateListener)===null||ro===void 0||ro.onChainUpdate({chain:{id:to,rpcUrl:eo},source:"wallet"}),this.hasMadeFirstChainChangedEmission=!0)}async watchAsset(eo,to,ro,no,io,oo){const so=await this.initializeRelay().watchAsset(eo,to,ro,no,io,oo==null?void 0:oo.toString());return(0,Web3Response_1.isErrorResponse)(so)?!1:!!so.result}async addEthereumChain(eo,to,ro,no,io,oo){var ao,so;if((0,util_1$3.ensureIntNumber)(eo)===this.getChainId())return!1;const co=this.initializeRelay();this._isAuthorized()||await co.requestEthereumAccounts();const lo=await co.addEthereumChain(eo.toString(),to,io,ro,no,oo);return(0,Web3Response_1.isErrorResponse)(lo)?!1:(((ao=lo.result)===null||ao===void 0?void 0:ao.isApproved)===!0&&this.updateProviderInfo(to[0],eo),((so=lo.result)===null||so===void 0?void 0:so.isApproved)===!0)}async switchEthereumChain(eo){const ro=await this.initializeRelay().switchEthereumChain(eo.toString(10),this.selectedAddress||void 0);if((0,Web3Response_1.isErrorResponse)(ro)){if(!ro.errorCode)return;throw ro.errorCode===error_1$5.standardErrorCodes.provider.unsupportedChain?error_1$5.standardErrors.provider.unsupportedChain():error_1$5.standardErrors.provider.custom({message:ro.errorMessage,code:ro.errorCode})}const no=ro.result;no.isApproved&&no.rpcUrl.length>0&&this.updateProviderInfo(no.rpcUrl,eo)}async disconnect(){this._relay&&this._relay.resetAndReload(),this._storage.clear()}async request(eo){try{return this._request(eo).catch(to=>{throw to})}catch(to){return Promise.reject(to)}}async _request(eo){if(!eo||typeof eo!="object"||Array.isArray(eo))throw error_1$5.standardErrors.rpc.invalidRequest({message:"Expected a single, non-array, object argument.",data:eo});const{method:to,params:ro}=eo;if(typeof to!="string"||to.length===0)throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.method' must be a non-empty string.",data:eo});if(ro!==void 0&&!Array.isArray(ro)&&(typeof ro!="object"||ro===null))throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.params' must be an object or array if provided.",data:eo});const no=ro===void 0?[]:ro,io=this._relayEventManager.makeRequestId();return(await this._sendRequestAsync({method:to,params:no,jsonrpc:"2.0",id:io})).result}_setAddresses(eo,to){var ro;if(!Array.isArray(eo))throw new Error("addresses is not an array");const no=eo.map(io=>(0,util_1$3.ensureAddressString)(io));JSON.stringify(no)!==JSON.stringify(this._addresses)&&(this._addresses=no,(ro=this.updateListener)===null||ro===void 0||ro.onAccountsUpdate({accounts:no,source:"wallet"}),this._storage.setItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY,no.join(" ")))}_sendRequestAsync(eo){return new Promise((to,ro)=>{try{const no=this._handleSynchronousMethods(eo);if(no!==void 0)return to({jsonrpc:"2.0",id:eo.id,result:no})}catch(no){return ro(no)}this._handleAsynchronousMethods(eo).then(no=>no&&to(Object.assign(Object.assign({},no),{id:eo.id}))).catch(no=>ro(no))})}_handleSynchronousMethods(eo){const{method:to}=eo;switch(to){case"eth_accounts":return this._eth_accounts();case"eth_coinbase":return this._eth_coinbase();case"net_version":return this._net_version();case"eth_chainId":return this._eth_chainId();default:return}}async _handleAsynchronousMethods(eo){const{method:to}=eo,ro=eo.params||[];switch(to){case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_sign":return this._eth_sign(ro);case"eth_ecRecover":return this._eth_ecRecover(ro);case"personal_sign":return this._personal_sign(ro);case"personal_ecRecover":return this._personal_ecRecover(ro);case"eth_signTransaction":return this._eth_signTransaction(ro);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(ro);case"eth_sendTransaction":return this._eth_sendTransaction(ro);case"eth_signTypedData_v1":return this._eth_signTypedData_v1(ro);case"eth_signTypedData_v2":return this._throwUnsupportedMethodError();case"eth_signTypedData_v3":return this._eth_signTypedData_v3(ro);case"eth_signTypedData_v4":case"eth_signTypedData":return this._eth_signTypedData_v4(ro);case"wallet_addEthereumChain":return this._wallet_addEthereumChain(ro);case"wallet_switchEthereumChain":return this._wallet_switchEthereumChain(ro);case"wallet_watchAsset":return this._wallet_watchAsset(ro);default:return this._throwUnsupportedMethodError()}}_isKnownAddress(eo){try{const to=(0,util_1$3.ensureAddressString)(eo);return this._addresses.map(no=>(0,util_1$3.ensureAddressString)(no)).includes(to)}catch{}return!1}_ensureKnownAddress(eo){if(!this._isKnownAddress(eo))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(eo){const to=eo.from?(0,util_1$3.ensureAddressString)(eo.from):this.selectedAddress;if(!to)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(to);const ro=eo.to?(0,util_1$3.ensureAddressString)(eo.to):null,no=eo.value!=null?(0,util_1$3.ensureBigInt)(eo.value):BigInt(0),io=eo.data?(0,util_1$3.ensureBuffer)(eo.data):Buffer$3.alloc(0),oo=eo.nonce!=null?(0,util_1$3.ensureIntNumber)(eo.nonce):null,ao=eo.gasPrice!=null?(0,util_1$3.ensureBigInt)(eo.gasPrice):null,so=eo.maxFeePerGas!=null?(0,util_1$3.ensureBigInt)(eo.maxFeePerGas):null,co=eo.maxPriorityFeePerGas!=null?(0,util_1$3.ensureBigInt)(eo.maxPriorityFeePerGas):null,lo=eo.gas!=null?(0,util_1$3.ensureBigInt)(eo.gas):null,fo=eo.chainId?(0,util_1$3.ensureIntNumber)(eo.chainId):this.getChainId();return{fromAddress:to,toAddress:ro,weiValue:no,data:io,nonce:oo,gasPriceInWei:ao,maxFeePerGas:so,maxPriorityFeePerGas:co,gasLimit:lo,chainId:fo}}_isAuthorized(){return this._addresses.length>0}_requireAuthorization(){if(!this._isAuthorized())throw error_1$5.standardErrors.provider.unauthorized({})}_throwUnsupportedMethodError(){throw error_1$5.standardErrors.provider.unsupportedMethod({})}async _signEthereumMessage(eo,to,ro,no){this._ensureKnownAddress(to);try{const oo=await this.initializeRelay().signEthereumMessage(eo,to,ro,no);if((0,Web3Response_1.isErrorResponse)(oo))throw new Error(oo.errorMessage);return{jsonrpc:"2.0",id:0,result:oo.result}}catch(io){throw typeof io.message=="string"&&io.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied message signature"):io}}async _ethereumAddressFromSignedMessage(eo,to,ro){const io=await this.initializeRelay().ethereumAddressFromSignedMessage(eo,to,ro);if((0,Web3Response_1.isErrorResponse)(io))throw new Error(io.errorMessage);return{jsonrpc:"2.0",id:0,result:io.result}}_eth_accounts(){return[...this._addresses]}_eth_coinbase(){return this.selectedAddress||null}_net_version(){return this.getChainId().toString(10)}_eth_chainId(){return(0,util_1$3.hexStringFromIntNumber)(this.getChainId())}getChainId(){const eo=this._storage.getItem(DEFAULT_CHAIN_ID_KEY);if(!eo)return(0,util_1$3.ensureIntNumber)(1);const to=parseInt(eo,10);return(0,util_1$3.ensureIntNumber)(to)}async _eth_requestAccounts(){if(this._isAuthorized())return Promise.resolve({jsonrpc:"2.0",id:0,result:this._addresses});let eo;try{if(eo=await this.initializeRelay().requestEthereumAccounts(),(0,Web3Response_1.isErrorResponse)(eo))throw new Error(eo.errorMessage)}catch(to){throw typeof to.message=="string"&&to.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied account authorization"):to}if(!eo.result)throw new Error("accounts received is empty");return this._setAddresses(eo.result),{jsonrpc:"2.0",id:0,result:this._addresses}}_eth_sign(eo){this._requireAuthorization();const to=(0,util_1$3.ensureAddressString)(eo[0]),ro=(0,util_1$3.ensureBuffer)(eo[1]);return this._signEthereumMessage(ro,to,!1)}_eth_ecRecover(eo){const to=(0,util_1$3.ensureBuffer)(eo[0]),ro=(0,util_1$3.ensureBuffer)(eo[1]);return this._ethereumAddressFromSignedMessage(to,ro,!1)}_personal_sign(eo){this._requireAuthorization();const to=(0,util_1$3.ensureBuffer)(eo[0]),ro=(0,util_1$3.ensureAddressString)(eo[1]);return this._signEthereumMessage(to,ro,!0)}_personal_ecRecover(eo){const to=(0,util_1$3.ensureBuffer)(eo[0]),ro=(0,util_1$3.ensureBuffer)(eo[1]);return this._ethereumAddressFromSignedMessage(to,ro,!0)}async _eth_signTransaction(eo){this._requireAuthorization();const to=this._prepareTransactionParams(eo[0]||{});try{const no=await this.initializeRelay().signEthereumTransaction(to);if((0,Web3Response_1.isErrorResponse)(no))throw new Error(no.errorMessage);return{jsonrpc:"2.0",id:0,result:no.result}}catch(ro){throw typeof ro.message=="string"&&ro.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):ro}}async _eth_sendRawTransaction(eo){const to=(0,util_1$3.ensureBuffer)(eo[0]),no=await this.initializeRelay().submitEthereumTransaction(to,this.getChainId());if((0,Web3Response_1.isErrorResponse)(no))throw new Error(no.errorMessage);return{jsonrpc:"2.0",id:0,result:no.result}}async _eth_sendTransaction(eo){this._requireAuthorization();const to=this._prepareTransactionParams(eo[0]||{});try{const no=await this.initializeRelay().signAndSubmitEthereumTransaction(to);if((0,Web3Response_1.isErrorResponse)(no))throw new Error(no.errorMessage);return{jsonrpc:"2.0",id:0,result:no.result}}catch(ro){throw typeof ro.message=="string"&&ro.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):ro}}async _eth_signTypedData_v1(eo){this._requireAuthorization();const to=(0,util_1$3.ensureParsedJSONObject)(eo[0]),ro=(0,util_1$3.ensureAddressString)(eo[1]);this._ensureKnownAddress(ro);const no=eth_eip712_util_1.default.hashForSignTypedDataLegacy({data:to}),io=JSON.stringify(to,null,2);return this._signEthereumMessage(no,ro,!1,io)}async _eth_signTypedData_v3(eo){this._requireAuthorization();const to=(0,util_1$3.ensureAddressString)(eo[0]),ro=(0,util_1$3.ensureParsedJSONObject)(eo[1]);this._ensureKnownAddress(to);const no=eth_eip712_util_1.default.hashForSignTypedData_v3({data:ro}),io=JSON.stringify(ro,null,2);return this._signEthereumMessage(no,to,!1,io)}async _eth_signTypedData_v4(eo){this._requireAuthorization();const to=(0,util_1$3.ensureAddressString)(eo[0]),ro=(0,util_1$3.ensureParsedJSONObject)(eo[1]);this._ensureKnownAddress(to);const no=eth_eip712_util_1.default.hashForSignTypedData_v4({data:ro}),io=JSON.stringify(ro,null,2);return this._signEthereumMessage(no,to,!1,io)}async _wallet_addEthereumChain(eo){var to,ro,no,io;const oo=eo[0];if(((to=oo.rpcUrls)===null||to===void 0?void 0:to.length)===0)return{jsonrpc:"2.0",id:0,error:{code:2,message:"please pass in at least 1 rpcUrl"}};if(!oo.chainName||oo.chainName.trim()==="")throw error_1$5.standardErrors.rpc.invalidParams("chainName is a required field");if(!oo.nativeCurrency)throw error_1$5.standardErrors.rpc.invalidParams("nativeCurrency is a required field");const ao=parseInt(oo.chainId,16);return await this.addEthereumChain(ao,(ro=oo.rpcUrls)!==null&&ro!==void 0?ro:[],(no=oo.blockExplorerUrls)!==null&&no!==void 0?no:[],oo.chainName,(io=oo.iconUrls)!==null&&io!==void 0?io:[],oo.nativeCurrency)?{jsonrpc:"2.0",id:0,result:null}:{jsonrpc:"2.0",id:0,error:{code:2,message:"unable to add ethereum chain"}}}async _wallet_switchEthereumChain(eo){const to=eo[0];return await this.switchEthereumChain(parseInt(to.chainId,16)),{jsonrpc:"2.0",id:0,result:null}}async _wallet_watchAsset(eo){const to=Array.isArray(eo)?eo[0]:eo;if(!to.type)throw error_1$5.standardErrors.rpc.invalidParams("Type is required");if((to==null?void 0:to.type)!=="ERC20")throw error_1$5.standardErrors.rpc.invalidParams(`Asset of type '${to.type}' is not supported`);if(!(to!=null&&to.options))throw error_1$5.standardErrors.rpc.invalidParams("Options are required");if(!(to!=null&&to.options.address))throw error_1$5.standardErrors.rpc.invalidParams("Address is required");const ro=this.getChainId(),{address:no,symbol:io,image:oo,decimals:ao}=to.options;return{jsonrpc:"2.0",id:0,result:await this.watchAsset(to.type,no,io,ao,oo,ro)}}initializeRelay(){if(!this._relay){const eo=new WalletLinkRelay_1.WalletLinkRelay({linkAPIUrl:constants_2.WALLETLINK_URL,storage:this._storage});eo.setAppInfo(this._appName,this._appLogoUrl),eo.attachUI(),eo.setAccountsCallback((to,ro)=>this._setAddresses(to,ro)),eo.setChainCallback((to,ro)=>{this.updateProviderInfo(ro,parseInt(to,10))}),this._relay=eo}return this._relay}}WalletLinkSigner$1.WalletLinkSigner=WalletLinkSigner;var provider={};Object.defineProperty(provider,"__esModule",{value:!0});provider.checkErrorForInvalidRequestArgs=provider.getCoinbaseInjectedProvider=provider.getCoinbaseInjectedSigner=provider.fetchRPCRequest=void 0;const version_1$2=version$b,error_1$4=error$2;async function fetchRPCRequest(Xr,eo){if(!eo.rpcUrl)throw error_1$4.standardErrors.rpc.internal("No RPC URL set for chain");const to=Object.assign(Object.assign({},Xr),{jsonrpc:"2.0",id:crypto.randomUUID()});return(await(await window.fetch(eo.rpcUrl,{method:"POST",body:JSON.stringify(to),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":version_1$2.LIB_VERSION}})).json()).result}provider.fetchRPCRequest=fetchRPCRequest;function getCoinbaseInjectedSigner(){return globalThis.coinbaseWalletSigner}provider.getCoinbaseInjectedSigner=getCoinbaseInjectedSigner;function getCoinbaseInjectedLegacyProvider(){return globalThis.coinbaseWalletExtension}function getInjectedEthereum(){var Xr,eo;try{const to=globalThis;return(Xr=to.ethereum)!==null&&Xr!==void 0?Xr:(eo=to.top)===null||eo===void 0?void 0:eo.ethereum}catch{return}}function getCoinbaseInjectedProvider({metadata:Xr,preference:eo}){var to;if(eo.options!=="smartWalletOnly"){if(getCoinbaseInjectedSigner())return;const io=getCoinbaseInjectedLegacyProvider();if(io){const{appName:oo,appLogoUrl:ao,appChainIds:so}=Xr;return(to=io.setAppInfo)===null||to===void 0||to.call(io,oo,ao,so),io}}const ro=getInjectedEthereum();if(ro!=null&&ro.isCoinbaseBrowser)return ro}provider.getCoinbaseInjectedProvider=getCoinbaseInjectedProvider;function checkErrorForInvalidRequestArgs(Xr){if(!Xr||typeof Xr!="object"||Array.isArray(Xr))return error_1$4.standardErrors.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:Xr});const{method:eo,params:to}=Xr;if(typeof eo!="string"||eo.length===0)return error_1$4.standardErrors.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:Xr});if(to!==void 0&&!Array.isArray(to)&&(typeof to!="object"||to===null))return error_1$4.standardErrors.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:Xr})}provider.checkErrorForInvalidRequestArgs=checkErrorForInvalidRequestArgs;Object.defineProperty(util$5,"__esModule",{value:!0});util$5.createSigner=util$5.fetchSignerType=util$5.storeSignerType=util$5.loadSignerType=void 0;const SCWSigner_1=SCWSigner$1,WalletLinkSigner_1=WalletLinkSigner$1,error_1$3=error$2,provider_1$2=provider,ScopedLocalStorage_1$2=ScopedLocalStorage$1,SIGNER_TYPE_KEY="SignerType",storage$1=new ScopedLocalStorage_1$2.ScopedLocalStorage("CBWSDK","SignerConfigurator");function loadSignerType(){return storage$1.getItem(SIGNER_TYPE_KEY)}util$5.loadSignerType=loadSignerType;function storeSignerType(Xr){storage$1.setItem(SIGNER_TYPE_KEY,Xr)}util$5.storeSignerType=storeSignerType;async function fetchSignerType(Xr){const{communicator:eo,metadata:to}=Xr;listenForWalletLinkSessionRequest(eo,to).catch(()=>{});const ro={id:crypto.randomUUID(),event:"selectSignerType",data:Xr.preference},{data:no}=await eo.postRequestAndWaitForResponse(ro);return no}util$5.fetchSignerType=fetchSignerType;function createSigner(Xr){const{signerType:eo,metadata:to,communicator:ro,updateListener:no}=Xr;switch(eo){case"scw":return new SCWSigner_1.SCWSigner({metadata:to,updateListener:no,communicator:ro});case"walletlink":return new WalletLinkSigner_1.WalletLinkSigner({metadata:to,updateListener:no});case"extension":{const io=(0,provider_1$2.getCoinbaseInjectedSigner)();if(!io)throw error_1$3.standardErrors.rpc.internal("injected signer not found");return io}}}util$5.createSigner=createSigner;async function listenForWalletLinkSessionRequest(Xr,eo){await Xr.onMessage(({event:ro})=>ro==="WalletLinkSessionRequest");const to=new WalletLinkSigner_1.WalletLinkSigner({metadata:eo});Xr.postMessage({event:"WalletLinkUpdate",data:{session:to.getSession()}}),await to.handshake(),Xr.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}var Communicator$1={},util={};Object.defineProperty(util,"__esModule",{value:!0});util.closePopup=util.openPopup=void 0;const error_1$2=error$2,POPUP_WIDTH=420,POPUP_HEIGHT=540;function openPopup(Xr){const eo=(window.innerWidth-POPUP_WIDTH)/2+window.screenX,to=(window.innerHeight-POPUP_HEIGHT)/2+window.screenY,ro=window.open(Xr,"Smart Wallet",`width=${POPUP_WIDTH}, height=${POPUP_HEIGHT}, left=${eo}, top=${to}`);if(ro==null||ro.focus(),!ro)throw error_1$2.standardErrors.rpc.internal("Pop up window failed to open");return ro}util.openPopup=openPopup;function closePopup(Xr){Xr&&!Xr.closed&&Xr.close()}util.closePopup=closePopup;Object.defineProperty(Communicator$1,"__esModule",{value:!0});Communicator$1.Communicator=void 0;const version_1$1=version$b,util_1$2=util,constants_1=constants$3,error_1$1=error$2;class Communicator{constructor(eo=constants_1.CB_KEYS_URL){this.popup=null,this.listeners=new Map,this.postMessage=async to=>{(await this.waitForPopupLoaded()).postMessage(to,this.url.origin)},this.postRequestAndWaitForResponse=async to=>{const ro=this.onMessage(({requestId:no})=>no===to.id);return this.postMessage(to),await ro},this.onMessage=async to=>new Promise((ro,no)=>{const io=oo=>{if(oo.origin!==this.url.origin)return;const ao=oo.data;to(ao)&&(ro(ao),window.removeEventListener("message",io),this.listeners.delete(io))};window.addEventListener("message",io),this.listeners.set(io,{reject:no})}),this.disconnect=()=>{(0,util_1$2.closePopup)(this.popup),this.popup=null,this.listeners.forEach(({reject:to},ro)=>{to(error_1$1.standardErrors.provider.userRejectedRequest("Request rejected")),window.removeEventListener("message",ro)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(this.popup=(0,util_1$2.openPopup)(this.url),this.onMessage(({event:to})=>to==="PopupUnload").then(this.disconnect).catch(()=>{}),this.onMessage(({event:to})=>to==="PopupLoaded").then(to=>{this.postMessage({requestId:to.id,data:{version:version_1$1.LIB_VERSION}})}).then(()=>{if(!this.popup)throw error_1$1.standardErrors.rpc.internal();return this.popup})),this.url=new URL(eo)}}Communicator$1.Communicator=Communicator;var method={};Object.defineProperty(method,"__esModule",{value:!0});method.determineMethodCategory=void 0;const mapping={handshake:["eth_requestAccounts"],sign:["eth_ecRecover","personal_sign","personal_ecRecover","eth_signTransaction","eth_sendTransaction","eth_signTypedData_v1","eth_signTypedData_v3","eth_signTypedData_v4","eth_signTypedData","wallet_addEthereumChain","wallet_switchEthereumChain","wallet_watchAsset","wallet_getCapabilities","wallet_sendCalls","wallet_showCallsStatus"],state:["eth_chainId","eth_accounts","eth_coinbase","net_version"],deprecated:["eth_sign","eth_signTypedData_v2"],unsupported:["eth_subscribe","eth_unsubscribe"],fetch:[]};function determineMethodCategory(Xr){for(const eo in mapping){const to=eo;if(mapping[to].includes(Xr))return to}}method.determineMethodCategory=determineMethodCategory;var __rest$2=commonjsGlobal&&commonjsGlobal.__rest||function(Xr,eo){var to={};for(var ro in Xr)Object.prototype.hasOwnProperty.call(Xr,ro)&&eo.indexOf(ro)<0&&(to[ro]=Xr[ro]);if(Xr!=null&&typeof Object.getOwnPropertySymbols=="function")for(var no=0,ro=Object.getOwnPropertySymbols(Xr);no{try{if(this.connected)return this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),this.accounts;const lo=await this.requestSignerSelection(),fo=this.initSigner(lo),ho=await fo.handshake();return this.signer=fo,(0,util_2.storeSignerType)(lo),this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),ho}catch(lo){throw this.handleUnauthorizedError(lo),lo}},sign:async co=>{if(!this.connected||!this.signer)throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods");try{return await this.signer.request(co)}catch(lo){throw this.handleUnauthorizedError(lo),lo}},fetch:co=>(0,provider_1$1.fetchRPCRequest)(co,this.chain),state:co=>{const lo=()=>{if(this.connected)return this.accounts;throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods")};switch(co.method){case"eth_chainId":return(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id));case"net_version":return this.chain.id;case"eth_accounts":return lo();case"eth_coinbase":return lo()[0];default:return this.handlers.unsupported(co)}},deprecated:({method:co})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${co} is deprecated.`)},unsupported:({method:co})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${co} is not supported.`)}},this.isCoinbaseWallet=!0,this.updateListener={onAccountsUpdate:({accounts:co,source:lo})=>{(0,util_1$1.areAddressArraysEqual)(this.accounts,co)||(this.accounts=co,lo!=="storage"&&this.emit("accountsChanged",this.accounts))},onChainUpdate:({chain:co,source:lo})=>{co.id===this.chain.id&&co.rpcUrl===this.chain.rpcUrl||(this.chain=co,lo!=="storage"&&this.emit("chainChanged",(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(co.id))))}},this.metadata=no,this.preference=ao,this.communicator=new Communicator_1.Communicator(oo),this.chain={id:(ro=(to=no.appChainIds)===null||to===void 0?void 0:to[0])!==null&&ro!==void 0?ro:1};const so=(0,util_2.loadSignerType)();this.signer=so?this.initSigner(so):null}get connected(){return this.accounts.length>0}async request(eo){var to;try{const ro=(0,provider_1$1.checkErrorForInvalidRequestArgs)(eo);if(ro)throw ro;const no=(to=(0,method_1.determineMethodCategory)(eo.method))!==null&&to!==void 0?to:"fetch";return this.handlers[no](eo)}catch(ro){return Promise.reject((0,serialize_1$1.serializeError)(ro,eo.method))}}handleUnauthorizedError(eo){eo.code===error_1.standardErrorCodes.provider.unauthorized&&this.disconnect()}async enable(){return console.warn('.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.'),await this.request({method:"eth_requestAccounts"})}async disconnect(){this.accounts=[],this.chain={id:1},ScopedLocalStorage_1$1.ScopedLocalStorage.clearAll(),this.emit("disconnect",error_1.standardErrors.provider.disconnected("User initiated disconnection"))}requestSignerSelection(){return(0,util_2.fetchSignerType)({communicator:this.communicator,preference:this.preference,metadata:this.metadata})}initSigner(eo){return(0,util_2.createSigner)({signerType:eo,metadata:this.metadata,communicator:this.communicator,updateListener:this.updateListener})}}CoinbaseWalletProvider$1.CoinbaseWalletProvider=CoinbaseWalletProvider;Object.defineProperty(CoinbaseWalletSDK$1,"__esModule",{value:!0});CoinbaseWalletSDK$1.CoinbaseWalletSDK=void 0;const wallet_logo_1=walletLogo$1,CoinbaseWalletProvider_1=CoinbaseWalletProvider$1,ScopedLocalStorage_1=ScopedLocalStorage$1,version_1=version$b,util_1=util$6,provider_1=provider;class CoinbaseWalletSDK{constructor(eo){this.metadata={appName:eo.appName||"Dapp",appLogoUrl:eo.appLogoUrl||(0,util_1.getFavicon)(),appChainIds:eo.appChainIds||[]},this.storeLatestVersion()}makeWeb3Provider(eo={options:"all"}){var to;const ro={metadata:this.metadata,preference:eo};return(to=(0,provider_1.getCoinbaseInjectedProvider)(ro))!==null&&to!==void 0?to:new CoinbaseWalletProvider_1.CoinbaseWalletProvider(ro)}getCoinbaseWalletLogo(eo,to=240){return(0,wallet_logo_1.walletLogo)(eo,to)}storeLatestVersion(){new ScopedLocalStorage_1.ScopedLocalStorage("CBWSDK").setItem("VERSION",version_1.LIB_VERSION)}}CoinbaseWalletSDK$1.CoinbaseWalletSDK=CoinbaseWalletSDK;(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.CoinbaseWalletSDK=void 0;const eo=CoinbaseWalletSDK$1;Xr.default=eo.CoinbaseWalletSDK;var to=CoinbaseWalletSDK$1;Object.defineProperty(Xr,"CoinbaseWalletSDK",{enumerable:!0,get:function(){return to.CoinbaseWalletSDK}})})(dist);let coinbaseProvider;const baseSepolia=84532,baseMainnet=8453,getCoinbaseProvider=({appLogoUrl:Xr,appName:eo,evmNetworks:to,walletPreference:ro}={})=>{const no=to==null?void 0:to.map(ao=>Number(ao.chainId));return(to==null?void 0:to.some(ao=>ao.chainId===baseSepolia))&&(no==null||no.sort((ao,so)=>ao===baseSepolia?-1:so===baseSepolia?1:0)),(to==null?void 0:to.some(ao=>ao.chainId===baseMainnet))&&(no==null||no.sort((ao,so)=>ao===baseMainnet?-1:so===baseMainnet?1:0)),coinbaseProvider||(coinbaseProvider=new dist.CoinbaseWalletSDK({appChainIds:no,appLogoUrl:Xr,appName:eo}).makeWeb3Provider({options:ro??"all"})),coinbaseProvider};class Coinbase extends EthWalletConnector{constructor(eo){var{appName:to,appLogoUrl:ro,evmNetworks:no,coinbaseWalletPreference:io}=eo,oo=__rest$6(eo,["appName","appLogoUrl","evmNetworks","coinbaseWalletPreference"]);super(Object.assign({evmNetworks:no},oo)),this.name="Coinbase",this.overrideKey="coinbase",this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.canConnectViaQrCode=!1,this.canConnectViaCustodialService=!this.isInstalledOnBrowser(),this.coinbaseProviderOpts={appLogoUrl:ro,appName:to,evmNetworks:no,walletPreference:io}}get coinbaseProvider(){return getCoinbaseProvider(this.coinbaseProviderOpts)}getConnectedAccounts(){return __awaiter$a(this,void 0,void 0,function*(){try{const eo=yield this.coinbaseProvider.request({method:"eth_accounts"});return eo[0]&&this.setActiveAccount(eo[0]),eo}catch{return[]}})}isInstalledOnBrowser(){var eo;return!!(!((eo=window==null?void 0:window.coinbaseWalletExtension)===null||eo===void 0)&&eo.isCoinbaseWallet)}getAddress(){return __awaiter$a(this,void 0,void 0,function*(){const[eo]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});return this.setActiveAccount(eo),eo})}signMessage(eo){return __awaiter$a(this,void 0,void 0,function*(){const[to]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});try{return yield this.coinbaseProvider.request({method:"personal_sign",params:[toHex$1(toBytes$1(eo)),to.toLowerCase()]})}catch{return}})}setupEventListeners(){const{handleAccountChange:eo,handleChainChange:to,handleDisconnect:ro}=eventListenerHandlers(this);this.coinbaseProvider.on("accountsChanged",eo),this.coinbaseProvider.on("chainChanged",to),this.coinbaseProvider.on("disconnect",ro),this.teardownEventListeners=()=>{this.coinbaseProvider.removeListener("accountsChanged",eo),this.coinbaseProvider.removeListener("chainChanged",to),this.coinbaseProvider.removeListener("disconnect",ro)}}getWalletClient(eo){return createWalletClient({account:this.getActiveAccount(),chain:eo?chainsMap[eo]:void 0,transport:custom$1(this.coinbaseProvider)})}}assertPackageVersion("@dynamic-labs/ethereum",version$c);const EthereumWalletConnectors=Xr=>[...injectedWalletOverrides$1,...fetchInjectedWalletConnector(Xr),...fetchWalletConnectWallets(Xr),...TurnkeyEVMWalletConnectors(Xr),Coinbase,UnknownInjected$1,FallbackEvmConnector,getWalletConnectConnector()];var version$a="3.4.4";function __awaiter$6(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;let config$1=null;const setConfig=Xr=>{config$1=Xr};let LEVELS=function(Xr){return Xr[Xr.debug=5]="debug",Xr[Xr.info=4]="info",Xr[Xr.log=3]="log",Xr[Xr.warn=2]="warn",Xr[Xr.error=1]="error",Xr}({});const buildLoggerMessageArgs=Xr=>{const{title:eo,message:to}=Xr;return[` +}`;var _p=x_(function(){return Rp(Hl,tp+"return "+Fu).apply(to,iu)});if(_p.source=Fu,J1(_p))throw _p;return _p}function I3(Io){return Op(Io).toLowerCase()}function R3(Io){return Op(Io).toUpperCase()}function A3(Io,Oo,Uo){if(Io=Op(Io),Io&&(Uo||Oo===to))return Pv(Io);if(!Io||!(Oo=bm(Oo)))return Io;var yl=Nm(Io),Rl=Nm(Oo),Hl=Ov(yl,Rl),iu=Nv(yl,Rl)+1;return d0(yl,Hl,iu).join("")}function P3(Io,Oo,Uo){if(Io=Op(Io),Io&&(Uo||Oo===to))return Io.slice(0,jv(Io)+1);if(!Io||!(Oo=bm(Oo)))return Io;var yl=Nm(Io),Rl=Nv(yl,Nm(Oo))+1;return d0(yl,0,Rl).join("")}function O3(Io,Oo,Uo){if(Io=Op(Io),Io&&(Uo||Oo===to))return Io.replace(Yo,"");if(!Io||!(Oo=bm(Oo)))return Io;var yl=Nm(Io),Rl=Ov(yl,Nm(Oo));return d0(yl,Rl).join("")}function N3(Io,Oo){var Uo=Xo,yl=Lo;if(Gp(Oo)){var Rl="separator"in Oo?Oo.separator:Rl;Uo="length"in Oo?vp(Oo.length):Uo,yl="omission"in Oo?bm(Oo.omission):yl}Io=Op(Io);var Hl=Io.length;if(M0(Io)){var iu=Nm(Io);Hl=iu.length}if(Uo>=Hl)return Io;var du=Uo-j0(yl);if(du<1)return yl;var bu=iu?d0(iu,0,du).join(""):Io.slice(0,du);if(Rl===to)return bu+yl;if(iu&&(du+=bu.length-du),Y1(Rl)){if(Io.slice(du).search(Rl)){var Pu,Ou=bu;for(Rl.global||(Rl=d1(Rl.source,Op(lu.exec(Rl))+"g")),Rl.lastIndex=0;Pu=Rl.exec(Ou);)var Fu=Pu.index;bu=bu.slice(0,Fu===to?du:Fu)}}else if(Io.indexOf(bm(Rl),du)!=du){var _d=bu.lastIndexOf(Rl);_d>-1&&(bu=bu.slice(0,_d))}return bu+yl}function M3(Io){return Io=Op(Io),Io&&Yu.test(Io)?Io.replace(mu,ax):Io}var j3=q0(function(Io,Oo,Uo){return Io+(Uo?" ":"")+Oo.toUpperCase()}),lv=Ew("toUpperCase");function __(Io,Oo,Uo){return Io=Op(Io),Oo=Uo?to:Oo,Oo===to?tx(Io)?lx(Io):V_(Io):Io.match(Oo)||[]}var x_=xp(function(Io,Oo){try{return nm(Io,to,Oo)}catch(Uo){return J1(Uo)?Uo:new hp(Uo)}}),B3=Ym(function(Io,Oo){return Sm(Oo,function(Uo){Uo=zm(Uo),Zm(Io,Uo,G1(Io[Uo],Io))}),Io});function D3(Io){var Oo=Io==null?0:Io.length,Uo=ap();return Io=Oo?Vp(Io,function(yl){if(typeof yl[1]!="function")throw new km(oo);return[Uo(yl[0]),yl[1]]}):[],xp(function(yl){for(var Rl=-1;++Rl$o)return[];var Uo=So,yl=am(Io,So);Oo=ap(Oo),Io-=So;for(var Rl=c1(yl,Oo);++Uo0||Oo<0)?new Sp(Uo):(Io<0?Uo=Uo.takeRight(-Io):Io&&(Uo=Uo.drop(Io)),Oo!==to&&(Oo=vp(Oo),Uo=Oo<0?Uo.dropRight(-Oo):Uo.take(Oo-Io)),Uo)},Sp.prototype.takeRightWhile=function(Io){return this.reverse().takeWhile(Io).reverse()},Sp.prototype.toArray=function(){return this.take(So)},Wm(Sp.prototype,function(Io,Oo){var Uo=/^(?:filter|find|map|reject)|While$/.test(Oo),yl=/^(?:head|last)$/.test(Oo),Rl=Dl[yl?"take"+(Oo=="last"?"Right":""):Oo],Hl=yl||/^find/.test(Oo);Rl&&(Dl.prototype[Oo]=function(){var iu=this.__wrapped__,du=yl?[1]:arguments,bu=iu instanceof Sp,Pu=du[0],Ou=bu||gp(iu),Fu=function($p){var Cp=Rl.apply(Dl,o0([$p],du));return yl&&_d?Cp[0]:Cp};Ou&&Uo&&typeof Pu=="function"&&Pu.length!=1&&(bu=Ou=!1);var _d=this.__chain__,tp=!!this.__actions__.length,sp=Hl&&!_d,_p=bu&&!tp;if(!Hl&&Ou){iu=_p?iu:new Sp(this);var cp=Io.apply(iu,du);return cp.__actions__.push({func:zy,args:[Fu],thisArg:to}),new Cm(cp,_d)}return sp&&_p?Io.apply(this,du):(cp=this.thru(Fu),sp?yl?cp.value()[0]:cp.value():cp)})}),Sm(["pop","push","shift","sort","splice","unshift"],function(Io){var Oo=gy[Io],Uo=/^(?:push|sort|unshift)$/.test(Io)?"tap":"thru",yl=/^(?:pop|shift)$/.test(Io);Dl.prototype[Io]=function(){var Rl=arguments;if(yl&&!this.__chain__){var Hl=this.value();return Oo.apply(gp(Hl)?Hl:[],Rl)}return this[Uo](function(iu){return Oo.apply(gp(iu)?iu:[],Rl)})}}),Wm(Sp.prototype,function(Io,Oo){var Uo=Dl[Oo];if(Uo){var yl=Uo.name+"";Np.call(U0,yl)||(U0[yl]=[]),U0[yl].push({name:Oo,func:Uo})}}),U0[By(to,Eo).name]=[{name:"wrapper",func:to}],Sp.prototype.clone=Px,Sp.prototype.reverse=Ox,Sp.prototype.value=Nx,Dl.prototype.at=l$,Dl.prototype.chain=u$,Dl.prototype.commit=d$,Dl.prototype.next=f$,Dl.prototype.plant=p$,Dl.prototype.reverse=m$,Dl.prototype.toJSON=Dl.prototype.valueOf=Dl.prototype.value=g$,Dl.prototype.first=Dl.prototype.head,Q0&&(Dl.prototype[Q0]=h$),Dl},B0=ux();Jp?((Jp.exports=B0)._=B0,jp._=B0):kp._=B0}).call(ge$2)})(Ui$1,Ui$1.exports);var Gg=Object.defineProperty,zg=Object.defineProperties,Kg=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Yg=Object.prototype.hasOwnProperty,Zg=Object.prototype.propertyIsEnumerable,ya=(Xr,eo,to)=>eo in Xr?Gg(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,cr$2=(Xr,eo)=>{for(var to in eo||(eo={}))Yg.call(eo,to)&&ya(Xr,to,eo[to]);if(Ea)for(var to of Ea(eo))Zg.call(eo,to)&&ya(Xr,to,eo[to]);return Xr},Jg=(Xr,eo)=>zg(Xr,Kg(eo));function ft$2(Xr,eo,to){var ro;const no=ve$2(Xr);return((ro=eo.rpcMap)==null?void 0:ro[no.reference])||`${Bg}?chainId=${no.namespace}:${no.reference}&projectId=${to}`}function Ct$2(Xr){return Xr.includes(":")?Xr.split(":")[1]:Xr}function Sa(Xr){return Xr.map(eo=>`${eo.split(":")[0]}:${eo.split(":")[1]}`)}function Xg(Xr,eo){const to=Object.keys(eo.namespaces).filter(no=>no.includes(Xr));if(!to.length)return[];const ro=[];return to.forEach(no=>{const io=eo.namespaces[no].accounts;ro.push(...io)}),ro}function Oa(Xr={},eo={}){const to=Ra(Xr),ro=Ra(eo);return Ui$1.exports.merge(to,ro)}function Ra(Xr){var eo,to,ro,no;const io={};if(!B$5(Xr))return io;for(const[oo,ao]of Object.entries(Xr)){const so=oe$3(oo)?[oo]:ao.chains,co=ao.methods||[],lo=ao.events||[],fo=ao.rpcMap||{},ho=en$1(oo);io[ho]=Jg(cr$2(cr$2({},io[ho]),ao),{chains:S$7(so,(eo=io[ho])==null?void 0:eo.chains),methods:S$7(co,(to=io[ho])==null?void 0:to.methods),events:S$7(lo,(ro=io[ho])==null?void 0:ro.events),rpcMap:cr$2(cr$2({},fo),(no=io[ho])==null?void 0:no.rpcMap)})}return io}function Qg(Xr){return Xr.includes(":")?Xr.split(":")[2]:Xr}function Vg(Xr){const eo={};for(const[to,ro]of Object.entries(Xr)){const no=ro.methods||[],io=ro.events||[],oo=ro.accounts||[],ao=oe$3(to)?[to]:ro.chains?ro.chains:Sa(ro.accounts);eo[to]={chains:ao,methods:no,events:io,accounts:oo}}return eo}function Wi$1(Xr){return typeof Xr=="number"?Xr:Xr.includes("0x")?parseInt(Xr,16):(Xr=Xr.includes(":")?Xr.split(":")[1]:Xr,isNaN(Number(Xr))?Xr:Number(Xr))}const ba$1={},z$5=Xr=>ba$1[Xr],Fi$1=(Xr,eo)=>{ba$1[Xr]=eo};class kg{constructor(eo){this.name="polkadot",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getAccounts(){const eo=this.namespace.accounts;return eo?eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2])||[]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class jg{constructor(eo){this.name="eip155",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(eo){switch(eo.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(eo);case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(eo.request.method)?await this.client.request(eo):this.getHttpProvider().request(eo.request)}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(parseInt(eo),to),this.chainId=parseInt(eo),this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}createHttpProvider(eo,to){const ro=to||ft$2(`${this.name}:${eo}`,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=parseInt(Ct$2(to));eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}getHttpProvider(){const eo=this.chainId,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}async handleSwitchChain(eo){var to,ro;let no=eo.request.params?(to=eo.request.params[0])==null?void 0:to.chainId:"0x0";no=no.startsWith("0x")?no:`0x${no}`;const io=parseInt(no,16);if(this.isChainApproved(io))this.setDefaultChain(`${io}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:eo.topic,request:{method:eo.request.method,params:[{chainId:no}]},chainId:(ro=this.namespace.chains)==null?void 0:ro[0]}),this.setDefaultChain(`${io}`);else throw new Error(`Failed to switch to chain 'eip155:${io}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(eo){return this.namespace.chains.includes(`${this.name}:${eo}`)}}class nv{constructor(eo){this.name="solana",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class tv{constructor(eo){this.name="cosmos",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class ev{constructor(eo){this.name="cip34",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{const ro=this.getCardanoRPCUrl(to),no=Ct$2(to);eo[no]=this.createHttpProvider(no,ro)}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}getCardanoRPCUrl(eo){const to=this.namespace.rpcMap;if(to)return to[eo]}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||this.getCardanoRPCUrl(eo);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class rv{constructor(eo){this.name="elrond",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class iv{constructor(eo){this.name="multiversx",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){this.httpProviders[eo]||this.setHttpProvider(eo,to),this.chainId=eo,this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${eo}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}getAccounts(){const eo=this.namespace.accounts;return eo?[...new Set(eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2]))]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;const no=Ct$2(to);eo[no]=this.createHttpProvider(no,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace,this.client.core.projectId);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);return new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}class sv{constructor(eo){this.name="near",this.namespace=eo.namespace,this.events=z$5("events"),this.client=z$5("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(eo){this.namespace=Object.assign(this.namespace,eo)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const eo=this.namespace.chains[0];if(!eo)throw new Error("ChainId not found");return eo.split(":")[1]}request(eo){return this.namespace.methods.includes(eo.request.method)?this.client.request(eo):this.getHttpProvider().request(eo.request)}setDefaultChain(eo,to){if(this.chainId=eo,!this.httpProviders[eo]){const ro=to||ft$2(`${this.name}:${eo}`,this.namespace);if(!ro)throw new Error(`No RPC url provided for chainId: ${eo}`);this.setHttpProvider(eo,ro)}this.events.emit(Vn$1.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const eo=this.namespace.accounts;return eo?eo.filter(to=>to.split(":")[1]===this.chainId.toString()).map(to=>to.split(":")[2])||[]:[]}createHttpProviders(){const eo={};return this.namespace.chains.forEach(to=>{var ro;eo[to]=this.createHttpProvider(to,(ro=this.namespace.rpcMap)==null?void 0:ro[to])}),eo}getHttpProvider(){const eo=`${this.name}:${this.chainId}`,to=this.httpProviders[eo];if(typeof to>"u")throw new Error(`JSON-RPC provider for ${eo} not found`);return to}setHttpProvider(eo,to){const ro=this.createHttpProvider(eo,to);ro&&(this.httpProviders[eo]=ro)}createHttpProvider(eo,to){const ro=to||ft$2(eo,this.namespace);return typeof ro>"u"?void 0:new JsonRpcProvider(new f$7(ro,z$5("disableProviderPing")))}}var uv=Object.defineProperty,av=Object.defineProperties,ov=Object.getOwnPropertyDescriptors,Ta=Object.getOwnPropertySymbols,fv=Object.prototype.hasOwnProperty,cv=Object.prototype.propertyIsEnumerable,La=(Xr,eo,to)=>eo in Xr?uv(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,hr$1=(Xr,eo)=>{for(var to in eo||(eo={}))fv.call(eo,to)&&La(Xr,to,eo[to]);if(Ta)for(var to of Ta(eo))cv.call(eo,to)&&La(Xr,to,eo[to]);return Xr},Mi$1=(Xr,eo)=>av(Xr,ov(eo));let lr$2=class I_{constructor(eo){this.events=new EventEmitter$1,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=eo,this.logger=typeof(eo==null?void 0:eo.logger)<"u"&&typeof(eo==null?void 0:eo.logger)!="string"?eo.logger:Hg(k$2({level:(eo==null?void 0:eo.logger)||Ia})),this.disableProviderPing=(eo==null?void 0:eo.disableProviderPing)||!1}static async init(eo){const to=new I_(eo);return await to.initialize(),to}async request(eo,to,ro){const[no,io]=this.validateChain(to);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(no).request({request:hr$1({},eo),chainId:`${no}:${io}`,topic:this.session.topic,expiry:ro})}sendAsync(eo,to,ro,no){const io=new Date().getTime();this.request(eo,ro,no).then(oo=>to(null,formatJsonRpcResult(io,oo))).catch(oo=>to(oo,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var eo;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(eo=this.session)==null?void 0:eo.topic,reason:U$6("USER_DISCONNECTED")}),await this.cleanup()}async connect(eo){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(eo),await this.cleanupPendingPairings(),!eo.skipPairing)return await this.pair(eo.pairingTopic)}on(eo,to){this.events.on(eo,to)}once(eo,to){this.events.once(eo,to)}removeListener(eo,to){this.events.removeListener(eo,to)}off(eo,to){this.events.off(eo,to)}get isWalletConnect(){return!0}async pair(eo){this.shouldAbortPairingAttempt=!1;let to=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(to>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:ro,approval:no}=await this.client.connect({pairingTopic:eo,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});ro&&(this.uri=ro,this.events.emit("display_uri",ro)),await no().then(io=>{this.session=io;const oo=Vg(io.namespaces);this.namespaces=Oa(this.namespaces,oo),this.persist("namespaces",this.namespaces)}).catch(io=>{if(io.message!==ae$2)throw io;to++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(eo,to){try{if(!this.session)return;const[ro,no]=this.validateChain(eo);this.getProvider(ro).setDefaultChain(no,to)}catch(ro){if(!/Please call connect/.test(ro.message))throw ro}}async cleanupPendingPairings(eo={}){this.logger.info("Cleaning up inactive pairings...");const to=this.client.pairing.getAll();if(k$4(to)){for(const ro of to)eo.deletePairings?this.client.core.expirer.set(ro.topic,0):await this.client.core.relayer.subscriber.unsubscribe(ro.topic);this.logger.info(`Inactive pairings cleared: ${to.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const eo=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[eo]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await Q$4.init({logger:this.providerOpts.logger||Ia,relayUrl:this.providerOpts.relayUrl||Fg,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const eo=[...new Set(Object.keys(this.session.namespaces).map(to=>en$1(to)))];Fi$1("client",this.client),Fi$1("events",this.events),Fi$1("disableProviderPing",this.disableProviderPing),eo.forEach(to=>{if(!this.session)return;const ro=Xg(to,this.session),no=Sa(ro),io=Oa(this.namespaces,this.optionalNamespaces),oo=Mi$1(hr$1({},io[to]),{accounts:ro,chains:no});switch(to){case"eip155":this.rpcProviders[to]=new jg({namespace:oo});break;case"solana":this.rpcProviders[to]=new nv({namespace:oo});break;case"cosmos":this.rpcProviders[to]=new tv({namespace:oo});break;case"polkadot":this.rpcProviders[to]=new kg({namespace:oo});break;case"cip34":this.rpcProviders[to]=new ev({namespace:oo});break;case"elrond":this.rpcProviders[to]=new rv({namespace:oo});break;case"multiversx":this.rpcProviders[to]=new iv({namespace:oo});break;case"near":this.rpcProviders[to]=new sv({namespace:oo});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",eo=>{this.events.emit("session_ping",eo)}),this.client.on("session_event",eo=>{const{params:to}=eo,{event:ro}=to;if(ro.name==="accountsChanged"){const no=ro.data;no&&k$4(no)&&this.events.emit("accountsChanged",no.map(Qg))}else if(ro.name==="chainChanged"){const no=to.chainId,io=to.event.data,oo=en$1(no),ao=Wi$1(no)!==Wi$1(io)?`${oo}:${Wi$1(io)}`:no;this.onChainChanged(ao)}else this.events.emit(ro.name,ro.data);this.events.emit("session_event",eo)}),this.client.on("session_update",({topic:eo,params:to})=>{var ro;const{namespaces:no}=to,io=(ro=this.client)==null?void 0:ro.session.get(eo);this.session=Mi$1(hr$1({},io),{namespaces:no}),this.onSessionUpdate(),this.events.emit("session_update",{topic:eo,params:to})}),this.client.on("session_delete",async eo=>{await this.cleanup(),this.events.emit("session_delete",eo),this.events.emit("disconnect",Mi$1(hr$1({},U$6("USER_DISCONNECTED")),{data:eo.topic}))}),this.on(Vn$1.DEFAULT_CHAIN_CHANGED,eo=>{this.onChainChanged(eo,!0)})}getProvider(eo){if(!this.rpcProviders[eo])throw new Error(`Provider not found: ${eo}`);return this.rpcProviders[eo]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(eo=>{var to;this.getProvider(eo).updateNamespace((to=this.session)==null?void 0:to.namespaces[eo])})}setNamespaces(eo){const{namespaces:to,optionalNamespaces:ro,sessionProperties:no}=eo;to&&Object.keys(to).length&&(this.namespaces=to),ro&&Object.keys(ro).length&&(this.optionalNamespaces=ro),this.sessionProperties=no,this.persist("namespaces",to),this.persist("optionalNamespaces",ro)}validateChain(eo){const[to,ro]=(eo==null?void 0:eo.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[to,ro];if(to&&!Object.keys(this.namespaces||{}).map(oo=>en$1(oo)).includes(to))throw new Error(`Namespace '${to}' is not configured. Please call connect() first with namespace config.`);if(to&&ro)return[to,ro];const no=en$1(Object.keys(this.namespaces)[0]),io=this.rpcProviders[no].getDefaultChain();return[no,io]}async requestAccounts(){const[eo]=this.validateChain();return await this.getProvider(eo).requestAccounts()}onChainChanged(eo,to=!1){if(!this.namespaces)return;const[ro,no]=this.validateChain(eo);no&&(to||this.getProvider(ro).setDefaultChain(no),this.namespaces[ro]?this.namespaces[ro].defaultChain=no:this.namespaces[`${ro}:${no}`]?this.namespaces[`${ro}:${no}`].defaultChain=no:this.namespaces[`${ro}:${no}`]={defaultChain:no},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",no))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(eo,to){this.client.core.storage.setItem(`${xa}/${eo}`,to)}async getFromStore(eo){return await this.client.core.storage.getItem(`${xa}/${eo}`)}};const hv=lr$2,P$4="wc",S$4="ethereum_provider",$$3=`${P$4}@2:${S$4}:`,j$6="https://rpc.walletconnect.com/v1/",u$4=["eth_sendTransaction","personal_sign"],E$3=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m$3=["chainChanged","accountsChanged"],_$6=["chainChanged","accountsChanged","message","disconnect","connect"];var N$5=Object.defineProperty,q$5=Object.defineProperties,D$3=Object.getOwnPropertyDescriptors,y$7=Object.getOwnPropertySymbols,U$4=Object.prototype.hasOwnProperty,Q$3=Object.prototype.propertyIsEnumerable,O$6=(Xr,eo,to)=>eo in Xr?N$5(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,p$3=(Xr,eo)=>{for(var to in eo||(eo={}))U$4.call(eo,to)&&O$6(Xr,to,eo[to]);if(y$7)for(var to of y$7(eo))Q$3.call(eo,to)&&O$6(Xr,to,eo[to]);return Xr},M$3=(Xr,eo)=>q$5(Xr,D$3(eo));function g$5(Xr){return Number(Xr[0].split(":")[1])}function f$6(Xr){return`0x${Xr.toString(16)}`}function L$5(Xr){const{chains:eo,optionalChains:to,methods:ro,optionalMethods:no,events:io,optionalEvents:oo,rpcMap:ao}=Xr;if(!k$4(eo))throw new Error("Invalid chains");const so={chains:eo,methods:ro||u$4,events:io||m$3,rpcMap:p$3({},eo.length?{[g$5(eo)]:ao[g$5(eo)]}:{})},co=io==null?void 0:io.filter(go=>!m$3.includes(go)),lo=ro==null?void 0:ro.filter(go=>!u$4.includes(go));if(!to&&!oo&&!no&&!(co!=null&&co.length)&&!(lo!=null&&lo.length))return{required:eo.length?so:void 0};const fo=(co==null?void 0:co.length)&&(lo==null?void 0:lo.length)||!to,ho={chains:[...new Set(fo?so.chains.concat(to||[]):to)],methods:[...new Set(so.methods.concat(no!=null&&no.length?no:E$3))],events:[...new Set(so.events.concat(oo!=null&&oo.length?oo:_$6))],rpcMap:ao};return{required:eo.length?so:void 0,optional:to.length?ho:void 0}}let v$3=class R_{constructor(){this.events=new eventsExports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=$$3,this.on=(eo,to)=>(this.events.on(eo,to),this),this.once=(eo,to)=>(this.events.once(eo,to),this),this.removeListener=(eo,to)=>(this.events.removeListener(eo,to),this),this.off=(eo,to)=>(this.events.off(eo,to),this),this.parseAccount=eo=>this.isCompatibleChainId(eo)?this.parseAccountId(eo).address:eo,this.signer={},this.rpc={}}static async init(eo){const to=new R_;return await to.initialize(eo),to}async request(eo,to){return await this.signer.request(eo,this.formatChainId(this.chainId),to)}sendAsync(eo,to,ro){this.signer.sendAsync(eo,to,this.formatChainId(this.chainId),ro)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(eo){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(eo);const{required:to,optional:ro}=L$5(this.rpc);try{const no=await new Promise(async(oo,ao)=>{var so;this.rpc.showQrModal&&((so=this.modal)==null||so.subscribeModal(co=>{!co.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),ao(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M$3(p$3({namespaces:p$3({},to&&{[this.namespace]:to})},ro&&{optionalNamespaces:{[this.namespace]:ro}}),{pairingTopic:eo==null?void 0:eo.pairingTopic})).then(co=>{oo(co)}).catch(co=>{ao(new Error(co.message))})});if(!no)return;const io=Un$1(no.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:io),this.setAccounts(io),this.events.emit("connect",{chainId:f$6(this.chainId)})}catch(no){throw this.signer.logger.error(no),no}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",eo=>{const{params:to}=eo,{event:ro}=to;ro.name==="accountsChanged"?(this.accounts=this.parseAccounts(ro.data),this.events.emit("accountsChanged",this.accounts)):ro.name==="chainChanged"?this.setChainId(this.formatChainId(ro.data)):this.events.emit(ro.name,ro.data),this.events.emit("session_event",eo)}),this.signer.on("chainChanged",eo=>{const to=parseInt(eo);this.chainId=to,this.events.emit("chainChanged",f$6(this.chainId)),this.persist()}),this.signer.on("session_update",eo=>{this.events.emit("session_update",eo)}),this.signer.on("session_delete",eo=>{this.reset(),this.events.emit("session_delete",eo),this.events.emit("disconnect",M$3(p$3({},U$6("USER_DISCONNECTED")),{data:eo.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",eo=>{var to,ro;this.rpc.showQrModal&&((to=this.modal)==null||to.closeModal(),(ro=this.modal)==null||ro.openModal({uri:eo})),this.events.emit("display_uri",eo)})}switchEthereumChain(eo){this.request({method:"wallet_switchEthereumChain",params:[{chainId:eo.toString(16)}]})}isCompatibleChainId(eo){return typeof eo=="string"?eo.startsWith(`${this.namespace}:`):!1}formatChainId(eo){return`${this.namespace}:${eo}`}parseChainId(eo){return Number(eo.split(":")[1])}setChainIds(eo){const to=eo.filter(ro=>this.isCompatibleChainId(ro)).map(ro=>this.parseChainId(ro));to.length&&(this.chainId=to[0],this.events.emit("chainChanged",f$6(this.chainId)),this.persist())}setChainId(eo){if(this.isCompatibleChainId(eo)){const to=this.parseChainId(eo);this.chainId=to,this.switchEthereumChain(to)}}parseAccountId(eo){const[to,ro,no]=eo.split(":");return{chainId:`${to}:${ro}`,address:no}}setAccounts(eo){this.accounts=eo.filter(to=>this.parseChainId(this.parseAccountId(to).chainId)===this.chainId).map(to=>this.parseAccountId(to).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(eo){var to,ro;const no=(to=eo==null?void 0:eo.chains)!=null?to:[],io=(ro=eo==null?void 0:eo.optionalChains)!=null?ro:[],oo=no.concat(io);if(!oo.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const ao=no.length?(eo==null?void 0:eo.methods)||u$4:[],so=no.length?(eo==null?void 0:eo.events)||m$3:[],co=(eo==null?void 0:eo.optionalMethods)||[],lo=(eo==null?void 0:eo.optionalEvents)||[],fo=(eo==null?void 0:eo.rpcMap)||this.buildRpcMap(oo,eo.projectId),ho=(eo==null?void 0:eo.qrModalOptions)||void 0;return{chains:no==null?void 0:no.map(go=>this.formatChainId(go)),optionalChains:io.map(go=>this.formatChainId(go)),methods:ao,events:so,optionalMethods:co,optionalEvents:lo,rpcMap:fo,showQrModal:!!(eo!=null&&eo.showQrModal),qrModalOptions:ho,projectId:eo.projectId,metadata:eo.metadata}}buildRpcMap(eo,to){const ro={};return eo.forEach(no=>{ro[no]=this.getRpcUrl(no,to)}),ro}async initialize(eo){if(this.rpc=this.getRpcConfig(eo),this.chainId=this.rpc.chains.length?g$5(this.rpc.chains):g$5(this.rpc.optionalChains),this.signer=await hv.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:eo.disableProviderPing,relayUrl:eo.relayUrl,storageOptions:eo.storageOptions}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let to;try{const{WalletConnectModal:ro}=await __vitePreload(()=>import("./index-Cl2DsYqV.js").then(no=>no.i),[]);to=ro}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(to)try{this.modal=new to(p$3({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(ro){throw this.signer.logger.error(ro),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(eo){if(!eo)return;const{chains:to,optionalChains:ro,rpcMap:no}=eo;to&&k$4(to)&&(this.rpc.chains=to.map(io=>this.formatChainId(io)),to.forEach(io=>{this.rpc.rpcMap[io]=(no==null?void 0:no[io])||this.getRpcUrl(io)})),ro&&k$4(ro)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=ro==null?void 0:ro.map(io=>this.formatChainId(io)),ro.forEach(io=>{this.rpc.rpcMap[io]=(no==null?void 0:no[io])||this.getRpcUrl(io)}))}getRpcUrl(eo,to){var ro;return((ro=this.rpc.rpcMap)==null?void 0:ro[eo])||`${j$6}?chainId=eip155:${eo}&projectId=${to||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const eo=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),to=this.session.namespaces[`${this.namespace}:${eo}`]?this.session.namespaces[`${this.namespace}:${eo}`]:this.session.namespaces[this.namespace];this.setChainIds(eo?[this.formatChainId(eo)]:to==null?void 0:to.accounts),this.setAccounts(to==null?void 0:to.accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(eo){return typeof eo=="string"||eo instanceof String?[this.parseAccount(eo)]:eo.map(to=>this.parseAccount(to))}};const parseIntSafe=(Xr,eo=10)=>{try{const to=parseInt(String(Xr),eo);if(isNaN(to)){logger$9.error(`Error parsing ${Xr}`);return}return to}catch(to){logger$9.error(`Error parsing ${Xr} to int: ${to}`)}},activeAccountKey=Xr=>`dynamic-wc2-active-account-${Xr}`,sessionTopicKey=Xr=>`dynamic-wc2-session-topic-${Xr}`,swicthedNetworkKey=Xr=>`dynamic-wc2-switched-network-${Xr}`,currentChainKey=Xr=>`dynamic-wc2-current-chain-${Xr}`,ee$2=new EventEmitter$3;class WalletConnect extends EthWalletConnector{constructor(eo){var to;super(eo),this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.isInitialized=!1,this.canConnectViaQrCode=!0,this.isWalletConnect=!0,this.preferredChains=[],this._hasSwitchedNetwork=!1,this.sessionEventHandler=()=>{},this.sessionDeleteHandler=()=>{},this.name=eo.walletName,this.projectId=eo.projectId,this.deepLinkPreference=eo.deepLinkPreference||"native",this.preferredChains=eo.walletConnectPreferredChains||[],this.hasSwitchedNetwork=(to=!!localStorage.getItem(this.swicthedNetworkKey))!==null&&to!==void 0?to:!1;const ro=localStorage.getItem(this.currentChainKey);this.currentChainId=ro?parseIntSafe(ro):void 0}getMappedChains(){return this.evmNetworks.filter(eo=>eo.chainId!==11297108109).map(eo=>`eip155:${eo.chainId}`)}getMappedChainsByPreferredOrder(){const eo=this.getMappedChains(),to=this.preferredChains.filter(no=>eo.includes(no)),ro=eo.filter(no=>!this.preferredChains.includes(no));return[...to,...ro].map(no=>Number(no.split(":")[1]))}initConnection(){return __awaiter$a(this,void 0,void 0,function*(){const{provider:eo}=WalletConnect;if(!eo)throw new DynamicError("No provider found (init connection)");eo!=null&&eo.signer.uri||eo.connect().catch(to=>{logger$9.error(to),ee$2.emit("walletconnect_connection_failed",to)})})}createProvider(){return __awaiter$a(this,void 0,void 0,function*(){return v$3.init({events:["chainChanged","accountsChanged"],methods:[],optionalChains:this.getMappedChainsByPreferredOrder(),optionalMethods:["eth_chainId","eth_signTypedData","eth_signTransaction","eth_sign","personal_sign","eth_sendTransaction","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain"],projectId:this.projectId,rpcMap:this.evmNetworkRpcMap(),showQrModal:!1})})}getWalletClientFromInitializedProvider(){return __awaiter$a(this,void 0,void 0,function*(){const eo=this.createProvider();return createWalletClient({account:this.getActiveAccount(),transport:custom$1(yield eo)})})}createInitProviderPromise(){return __awaiter$a(this,void 0,void 0,function*(){WalletConnect.provider=yield this.createProvider(),this.teardownEventListeners(),this.setupEventListeners()})}initProvider(){return __awaiter$a(this,void 0,void 0,function*(){const{provider:eo}=WalletConnect;eo||(this.initializePromise===void 0&&(this.initializePromise=this.createInitProviderPromise()),yield this.initializePromise)})}refreshSession(){var eo,to,ro,no,io;!((to=(eo=WalletConnect.provider)===null||eo===void 0?void 0:eo.session)===null||to===void 0)&&to.topic&&localStorage.getItem(this.sessionTopicKey)===((no=(ro=WalletConnect.provider)===null||ro===void 0?void 0:ro.session)===null||no===void 0?void 0:no.topic)&&(this.session=WalletConnect.provider.session,this.setActiveAccount((io=localStorage.getItem(this.activeAccountKey))!==null&&io!==void 0?io:void 0))}init(){return __awaiter$a(this,void 0,void 0,function*(){yield this.initProvider(),yield this.initConnection(),this.isInitialized=!0})}get sessionTopicKey(){return sessionTopicKey(this.key)}get activeAccountKey(){return activeAccountKey(this.key)}get swicthedNetworkKey(){return swicthedNetworkKey(this.key)}get currentChainKey(){return currentChainKey(this.key)}set currentChainId(eo){this._currentChainId=eo,eo?localStorage.setItem(this.currentChainKey,eo.toString()):localStorage.removeItem(this.currentChainKey)}get currentChainId(){return this._currentChainId}set hasSwitchedNetwork(eo){this._hasSwitchedNetwork=eo,eo?localStorage.setItem(this.swicthedNetworkKey,eo.toString()):localStorage.removeItem(this.swicthedNetworkKey)}get hasSwitchedNetwork(){return this._hasSwitchedNetwork}supportsNetworkSwitching(){return!0}setupEventListeners(){WalletConnect.provider&&(this.sessionEventHandler=({params:eo})=>{if(logger$9.debug("session_event was called",{params:eo}),!eo||!eo.event){logger$9.debug("session_event was called without params or params.event");return}const{name:to,data:ro}=eo.event;if(to==="chainChanged"){const no=parseIntSafe(ro);if(no===this.currentChainId){logger$9.debug(`ignoring chainChanged event with same chain id as current chain id: ${no}`);return}if(no===void 0){logger$9.debug(`received unexpected data for chainChanged: ${ro} with type ${typeof ro}}`);return}this.currentChainId=no,this.emit("chainChange",{chain:String(no)}),this.hasSwitchedNetwork=!0,this.switchNetwork({networkChainId:no})}else if(to==="accountsChanged"){if(!Array.isArray(ro)){logger$9.debug(`received unexpected data for accountsChanged: ${ro} with type ${typeof ro}}`);return}const no=ro[0].split(":")[2];this.setWCActiveAccount(no)}},WalletConnect.provider.on("session_event",this.sessionEventHandler),this.sessionDeleteHandler=()=>__awaiter$a(this,void 0,void 0,function*(){this.endSession(),this.emit("disconnect")}),WalletConnect.provider.on("session_delete",this.sessionDeleteHandler))}teardownEventListeners(){WalletConnect.provider&&(WalletConnect.provider.off("session_event",this.sessionEventHandler),WalletConnect.provider.off("session_delete",this.sessionDeleteHandler))}getWalletClient(eo){if(WalletConnect.provider)return createWalletClient({account:this.getActiveAccount(),chain:chainsMap[eo??String(this.currentChainId)],transport:custom$1(WalletConnect.provider)})}getAddress(eo){return __awaiter$a(this,void 0,void 0,function*(){var to,ro;const no=this.getActiveAccount();if(no!=null&&no.address)return no.address;if((!WalletConnect.provider||!(!((to=WalletConnect.provider)===null||to===void 0)&&to.signer.uri))&&(logger$9.debug("No WC2 provider found, re-initializing..."),yield this.endSession(),yield this.init(),yield sleep$1(1e3),!WalletConnect.provider||!(!((ro=WalletConnect.provider)===null||ro===void 0)&&ro.signer.uri)))throw logger$9.debug("No WC2 provider found, escaping and throwing error"),new DynamicError("No provider found");const io=getWalletBookWallet(this.walletBook,this.key,this.walletFallback);return performPlatformSpecificConnectionMethod(WalletConnect.provider.signer.uri,io,{onDesktopUri:eo==null?void 0:eo.onDesktopUri,onDisplayUri:eo==null?void 0:eo.onDisplayUri},this.deepLinkPreference),new Promise((oo,ao)=>{if(!WalletConnect.provider){ao(new DynamicError("No provider found"));return}const so=()=>{const fo=new DynamicError("Connection rejected. Please try again.");fo.code="connection_rejected",WalletConnect.provider&&(WalletConnect.provider.signer.uri=void 0,this.init()),ao(fo),lo()},co=()=>{var fo;const ho=(fo=WalletConnect.provider)===null||fo===void 0?void 0:fo.session;if(!ho){ao(new DynamicError("No session found"));return}this.setSession(ho),this.setWCActiveAccount(ho.namespaces.eip155.accounts[0].split(":")[2]),this.getNetwork().then(go=>{var yo;this.currentChainId=go,oo((yo=this.getActiveAccount())===null||yo===void 0?void 0:yo.address)}),lo()},lo=()=>{var fo;ee$2.off("walletconnect_connection_failed",so),(fo=WalletConnect.provider)===null||fo===void 0||fo.off("connect",co)};ee$2.on("walletconnect_connection_failed",so),WalletConnect.provider.on("connect",co)})})}waitForSignMessage(eo,to){return __awaiter$a(this,void 0,void 0,function*(){const no=yield new Promise((io,oo)=>{this.on("chainChange",()=>io({success:!1})),eo(to).then(ao=>io({signedMessage:ao,success:!0})).catch(oo)});return no.success===!1?eo(to):no.signedMessage})}getDeepLink(){var eo;if(!this.session)return;const to=getWalletBookWallet(this.walletBook,this.key),ro=getDeepLink({metadata:to,mode:"regular",preference:this.deepLinkPreference,uri:(eo=WalletConnect.provider)===null||eo===void 0?void 0:eo.signer.uri});if(ro)return`${ro}?sessionTopic=${this.session.topic}`}signMessage(eo){return __awaiter$a(this,void 0,void 0,function*(){if(!this.session)throw new DynamicError("no session");const to=this.getDeepLink();isMobile$1()&&to&&(window.location.href=to);const ro=io=>__awaiter$a(this,void 0,void 0,function*(){const oo=this.getActiveAccount();return oo?(yield this.getWalletClientFromInitializedProvider()).signMessage({account:oo,message:io}):void 0});return yield this.waitForSignMessage(ro,eo)})}clearActiveAccount(){localStorage.removeItem(this.activeAccountKey),this.setActiveAccount(void 0)}clearSession(){localStorage.removeItem(this.sessionTopicKey),this.session=void 0}setWCActiveAccount(eo){localStorage.setItem(this.activeAccountKey,eo),this.setActiveAccount(eo),this.emit("accountChange",{accounts:[eo]})}setSession(eo){localStorage.setItem(this.sessionTopicKey,eo.topic),this.session=eo}endSession(){return __awaiter$a(this,void 0,void 0,function*(){var eo;if(this.clearActiveAccount(),this.clearSession(),this.hasSwitchedNetwork=!1,this.currentChainId=void 0,!!(!((eo=WalletConnect.provider)===null||eo===void 0)&&eo.session))try{yield WalletConnect.provider.disconnect(),WalletConnect.provider=void 0}catch(to){logger$9.debug(to)}})}getNetwork(){const eo=Object.create(null,{getNetwork:{get:()=>super.getNetwork}});return __awaiter$a(this,void 0,void 0,function*(){return this.currentChainId?this.currentChainId:(yield this.initProvider(),eo.getNetwork.call(this))})}providerSwitchNetwork(eo){const to=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$a(this,arguments,void 0,function*({network:ro}){const no=yield this.getSupportedNetworks();if(!(no!=null&&no.includes(ro.chainId.toString()))){const ao=new DynamicError("Network switching is not available at this time. The user should manually switch network in their wallet");throw ao.code="network_switching_only_available_in_wallet",ao}const io=yield this.getNetwork();if(io&&io===ro.chainId)return;if(this.switchNetworkOnlyFromWallet)throw new DynamicError("Network switching is only supported through the wallet");if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching not supported");const oo=yield this.getWalletClientFromInitializedProvider();if(this.isMetaMask()){const ao=this.getDeepLink();ao&&(window.location.href=ao)}yield to.providerSwitchNetwork.call(this,{network:ro,provider:oo}),this.currentChainId=ro.chainId,this.hasSwitchedNetwork=!0,this.emit("chainChange",{chain:String(ro.chainId)})})}getConnectedAccounts(){return __awaiter$a(this,void 0,void 0,function*(){this.isInitialized===!1&&(yield this.initProvider(),this.refreshSession(),this.isInitialized=!0);const eo=this.getActiveAccount();return eo!=null&&eo.address?[eo.address]:[]})}isMetaMask(){var eo,to,ro,no,io;return(io=(no=(ro=(to=(eo=this.session)===null||eo===void 0?void 0:eo.peer)===null||to===void 0?void 0:to.metadata)===null||ro===void 0?void 0:ro.name)===null||no===void 0?void 0:no.toLowerCase().startsWith("metamask"))!==null&&io!==void 0?io:!1}getSupportedNetworks(){return __awaiter$a(this,void 0,void 0,function*(){var eo;if(yield this.initProvider(),this.refreshSession(),this.isMetaMask())return this.hasSwitchedNetwork?[String(this.currentChainId)]:this.evmNetworks.map(ro=>ro.chainId.toString());if(!this.session)return[];const to=[];return Object.keys(this.session.namespaces).forEach(ro=>{ro.startsWith("eip155:")&&to.push(ro.split(":")[1])}),(eo=this.session.namespaces.eip155)===null||eo===void 0||eo.accounts.forEach(ro=>to.push(ro.split(":")[1])),to.length?to:this.evmNetworks.map(ro=>ro.chainId.toString())})}}let InjectedWalletBase$1=class extends EthWalletConnector{constructor(){super(...arguments),this.supportedChains=["ETH","EVM"],this.connectedChain="EVM",this.walletConnectorFallback=!1}getEthProviderHelper(){return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.wallet&&!this.ethProviderHelper&&(this.ethProviderHelper=new EthProviderHelper(this.wallet,this)),this.ethProviderHelper}getMobileOrInstalledWallet(){var eo,to;return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.isInstalledOnBrowser()?this:!((to=(eo=this.wallet)===null||eo===void 0?void 0:eo.mobile)===null||to===void 0)&&to.inAppBrowser&&this.mobileExperience==="in-app-browser"&&isMobile$1()?this:this.walletConnectorFallback?new WalletConnect(Object.assign(Object.assign({},this.constructorProps),{walletName:this.name})):this}findProvider(){const eo=this.getEthProviderHelper();if(eo)return eo.getInstalledProvider()}setupEventListeners(){if(!this.getWalletClient())return;const to=this.getEthProviderHelper();if(!to)return;const{tearDownEventListeners:ro}=to._setupEventListeners(this);this.teardownEventListeners=ro}getWalletClient(eo){var to;return(to=this.getEthProviderHelper())===null||to===void 0?void 0:to.findWalletClient(eo)}isInstalledOnBrowser(){var eo;return((eo=this.getEthProviderHelper())===null||eo===void 0?void 0:eo.findProvider())!==void 0}getAddress(){return __awaiter$a(this,void 0,void 0,function*(){var eo;return(eo=this.getEthProviderHelper())===null||eo===void 0?void 0:eo.getAddress()})}connect(){return __awaiter$a(this,void 0,void 0,function*(){yield this.getAddress()})}signMessage(eo){return __awaiter$a(this,void 0,void 0,function*(){var to;return(to=this.getEthProviderHelper())===null||to===void 0?void 0:to.signMessage(eo)})}proveOwnership(eo,to){return __awaiter$a(this,void 0,void 0,function*(){return yield this.validateActiveWallet(eo),this.signMessage(to)})}endSession(){return __awaiter$a(this,void 0,void 0,function*(){})}providerSwitchNetwork(eo){const to=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$a(this,arguments,void 0,function*({network:ro,provider:no}){return to.providerSwitchNetwork.call(this,{network:ro,provider:no})})}};class PhantomEvm extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="Phantom",this.overrideKey="phantomevm",this.wallet=findWalletBookWallet(this.walletBook,this.key)}getAddress(){const eo=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$a(this,void 0,void 0,function*(){if(this.isInstalledOnBrowser())return eo.getAddress.call(this);isMobile$1()&&handleMobileWalletRedirect({nativeLink:"phantom://browse",universalLink:"https://phantom.app/ul/browse"})})}canGetChainAddress(){var eo,to;return!!(!((to=(eo=this.getEthProviderHelper())===null||eo===void 0?void 0:eo.findProvider())===null||to===void 0)&&to.selectedAddress)}}class ExodusEvm extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="ExodusEvm",this.overrideKey="exodusevm",this.walletConnectorFallback=!0,this.wallet=findWalletBookWallet(this.walletBook,this.key)}}let UnknownInjected$1=class extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="Unknown",this.overrideKey="unknown",this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}};class FallbackEvmConnector extends InjectedWalletBase$1{constructor(eo){super(eo),this.name="Fallback Connector",this.overrideKey="fallbackconnector",this.isAvailable=!1,this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}}const injectedWalletOverrides$1=[PhantomEvm,ExodusEvm],filteredInjectedWalletKeysOverrides$1=["phantomevm","coinbase","exodusevm"],fetchInjectedWalletConnector=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).filter(([to,ro])=>{var no;return((no=ro.injectedConfig)===null||no===void 0?void 0:no.find(io=>io.chain==="evm"))&&!filteredInjectedWalletKeysOverrides$1.includes(to)}).map(([to,ro])=>{const{shortName:no}=ro,io=no||ro.name,oo=!!ro.walletConnect;return class extends InjectedWalletBase$1{constructor(ao){super(Object.assign({},ao)),this.name=io,this.wallet=ro,this.walletConnectorFallback=oo,this.overrideKey=to}getAddress(){const ao=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$a(this,void 0,void 0,function*(){var so;if(this.isInstalledOnBrowser())return ao.getAddress.call(this);const co=(so=this.wallet.mobile)===null||so===void 0?void 0:so.inAppBrowser;if(!co){const lo=new Error(`No inAppBrowserBase found for ${this.name}.`);throw logger$9.error(lo.message),lo}window.location.href=`${co}/${window.location.href}`})}}})},fetchWalletConnectWallets=({walletBook:Xr})=>{var eo;return Object.entries((eo=Xr==null?void 0:Xr.wallets)!==null&&eo!==void 0?eo:{}).filter(([,to])=>to.walletConnect&&!to.filterFromWalletConnect).map(([to,ro])=>{const{shortName:no}=ro,io=no||ro.name;return class extends WalletConnect{constructor(oo){super(Object.assign(Object.assign({},oo),{walletName:io})),this.overrideKey=to}}})},getWalletConnectConnector=()=>class extends WalletConnect{constructor(Xr){super(Object.assign(Object.assign({},Xr),{walletName:"WalletConnect"}))}};var dist={},CoinbaseWalletSDK$1={},walletLogo$1={};Object.defineProperty(walletLogo$1,"__esModule",{value:!0});walletLogo$1.walletLogo=void 0;const walletLogo=(Xr,eo)=>{let to;switch(Xr){case"standard":return to=eo,`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;case"circle":return to=eo,`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${eo}' height='${to}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;case"text":return to=(.1*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogo":return to=(.25*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;case"textLight":return to=(.1*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogoLight":return to=(.25*eo).toFixed(2),`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;default:return to=eo,`data:image/svg+xml,%3Csvg width='${eo}' height='${to}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `}};walletLogo$1.walletLogo=walletLogo;var CoinbaseWalletProvider$1={};const require$$0$2=getAugmentedNamespace(eventemitter3$1);var error$2={},constants$5={};Object.defineProperty(constants$5,"__esModule",{value:!0});constants$5.errorValues=constants$5.standardErrorCodes=void 0;constants$5.standardErrorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}};constants$5.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}};var errors$1={},utils$2={};(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.serialize=Xr.getErrorCode=Xr.isValidCode=Xr.getMessageFromCode=Xr.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const eo=constants$5,to="Unspecified error message.";Xr.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function ro(ho,go=to){if(ho&&Number.isInteger(ho)){const yo=ho.toString();if(lo(eo.errorValues,yo))return eo.errorValues[yo].message;if(so(ho))return Xr.JSON_RPC_SERVER_ERROR_MESSAGE}return go}Xr.getMessageFromCode=ro;function no(ho){if(!Number.isInteger(ho))return!1;const go=ho.toString();return!!(eo.errorValues[go]||so(ho))}Xr.isValidCode=no;function io(ho){var go;if(typeof ho=="number")return ho;if(oo(ho))return(go=ho.code)!==null&&go!==void 0?go:ho.errorCode}Xr.getErrorCode=io;function oo(ho){return typeof ho=="object"&&ho!==null&&(typeof ho.code=="number"||typeof ho.errorCode=="number")}function ao(ho,{shouldIncludeStack:go=!1}={}){const yo={};if(ho&&typeof ho=="object"&&!Array.isArray(ho)&&lo(ho,"code")&&no(ho.code)){const vo=ho;yo.code=vo.code,vo.message&&typeof vo.message=="string"?(yo.message=vo.message,lo(vo,"data")&&(yo.data=vo.data)):(yo.message=ro(yo.code),yo.data={originalError:co(ho)})}else yo.code=eo.standardErrorCodes.rpc.internal,yo.message=fo(ho,"message")?ho.message:to,yo.data={originalError:co(ho)};return go&&(yo.stack=fo(ho,"stack")?ho.stack:void 0),yo}Xr.serialize=ao;function so(ho){return ho>=-32099&&ho<=-32e3}function co(ho){return ho&&typeof ho=="object"&&!Array.isArray(ho)?Object.assign({},ho):ho}function lo(ho,go){return Object.prototype.hasOwnProperty.call(ho,go)}function fo(ho,go){return typeof ho=="object"&&ho!==null&&go in ho&&typeof ho[go]=="string"}})(utils$2);Object.defineProperty(errors$1,"__esModule",{value:!0});errors$1.standardErrors=void 0;const constants_1$6=constants$5,utils_1$1=utils$2;errors$1.standardErrors={rpc:{parse:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.parse,Xr),invalidRequest:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidRequest,Xr),invalidParams:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidParams,Xr),methodNotFound:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotFound,Xr),internal:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.internal,Xr),server:Xr=>{if(!Xr||typeof Xr!="object"||Array.isArray(Xr))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:eo}=Xr;if(!Number.isInteger(eo)||eo>-32005||eo<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return getEthJsonRpcError(eo,Xr)},invalidInput:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidInput,Xr),resourceNotFound:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceNotFound,Xr),resourceUnavailable:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceUnavailable,Xr),transactionRejected:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.transactionRejected,Xr),methodNotSupported:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotSupported,Xr),limitExceeded:Xr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.limitExceeded,Xr)},provider:{userRejectedRequest:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.userRejectedRequest,Xr),unauthorized:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unauthorized,Xr),unsupportedMethod:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedMethod,Xr),disconnected:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.disconnected,Xr),chainDisconnected:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.chainDisconnected,Xr),unsupportedChain:Xr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedChain,Xr),custom:Xr=>{if(!Xr||typeof Xr!="object"||Array.isArray(Xr))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:eo,message:to,data:ro}=Xr;if(!to||typeof to!="string")throw new Error('"message" must be a nonempty string');return new EthereumProviderError(eo,to,ro)}}};function getEthJsonRpcError(Xr,eo){const[to,ro]=parseOpts(eo);return new EthereumRpcError(Xr,to||(0,utils_1$1.getMessageFromCode)(Xr),ro)}function getEthProviderError(Xr,eo){const[to,ro]=parseOpts(eo);return new EthereumProviderError(Xr,to||(0,utils_1$1.getMessageFromCode)(Xr),ro)}function parseOpts(Xr){if(Xr){if(typeof Xr=="string")return[Xr];if(typeof Xr=="object"&&!Array.isArray(Xr)){const{message:eo,data:to}=Xr;if(eo&&typeof eo!="string")throw new Error("Must specify string message.");return[eo||void 0,to]}}return[]}class EthereumRpcError extends Error{constructor(eo,to,ro){if(!Number.isInteger(eo))throw new Error('"code" must be an integer.');if(!to||typeof to!="string")throw new Error('"message" must be a nonempty string.');super(to),this.code=eo,ro!==void 0&&(this.data=ro)}}class EthereumProviderError extends EthereumRpcError{constructor(eo,to,ro){if(!isValidEthProviderCode(eo))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(eo,to,ro)}}function isValidEthProviderCode(Xr){return Number.isInteger(Xr)&&Xr>=1e3&&Xr<=4999}(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.standardErrors=Xr.standardErrorCodes=void 0;var eo=constants$5;Object.defineProperty(Xr,"standardErrorCodes",{enumerable:!0,get:function(){return eo.standardErrorCodes}});var to=errors$1;Object.defineProperty(Xr,"standardErrors",{enumerable:!0,get:function(){return to.standardErrors}})})(error$2);var serialize$1={},Web3Response={};Object.defineProperty(Web3Response,"__esModule",{value:!0});Web3Response.isErrorResponse=void 0;function isErrorResponse(Xr){return Xr.errorMessage!==void 0}Web3Response.isErrorResponse=isErrorResponse;var version$b={};Object.defineProperty(version$b,"__esModule",{value:!0});version$b.LIB_VERSION=void 0;version$b.LIB_VERSION="4.0.4";Object.defineProperty(serialize$1,"__esModule",{value:!0});serialize$1.serializeError=void 0;const Web3Response_1$2=Web3Response,version_1$3=version$b,constants_1$5=constants$5,utils_1=utils$2;function serializeError(Xr,eo){const to=(0,utils_1.serialize)(getErrorObject(Xr),{shouldIncludeStack:!0}),ro=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");ro.searchParams.set("version",version_1$3.LIB_VERSION),ro.searchParams.set("code",to.code.toString());const no=getMethod(to.data,eo);return no&&ro.searchParams.set("method",no),ro.searchParams.set("message",to.message),Object.assign(Object.assign({},to),{docUrl:ro.href})}serialize$1.serializeError=serializeError;function getErrorObject(Xr){return typeof Xr=="string"?{message:Xr,code:constants_1$5.standardErrorCodes.rpc.internal}:(0,Web3Response_1$2.isErrorResponse)(Xr)?Object.assign(Object.assign({},Xr),{message:Xr.errorMessage,code:Xr.errorCode,data:{method:Xr.method}}):Xr}function getMethod(Xr,eo){const to=Xr==null?void 0:Xr.method;if(to)return to;if(eo!==void 0){if(typeof eo=="string")return eo;if(Array.isArray(eo)){if(eo.length>0)return eo[0].method}else return eo.method}}var type$3={};Object.defineProperty(type$3,"__esModule",{value:!0});type$3.RegExpString=type$3.IntNumber=type$3.BigIntString=type$3.AddressString=type$3.HexString=type$3.OpaqueType=void 0;function OpaqueType(){return Xr=>Xr}type$3.OpaqueType=OpaqueType;type$3.HexString=OpaqueType();type$3.AddressString=OpaqueType();type$3.BigIntString=OpaqueType();function IntNumber(Xr){return Math.floor(Xr)}type$3.IntNumber=IntNumber;type$3.RegExpString=OpaqueType();var util$6={};Object.defineProperty(util$6,"__esModule",{value:!0});util$6.areAddressArraysEqual=util$6.getFavicon=util$6.range=util$6.isBigNumber=util$6.ensureParsedJSONObject=util$6.ensureBigInt=util$6.ensureRegExpString=util$6.ensureIntNumber=util$6.ensureBuffer=util$6.ensureAddressString=util$6.ensureEvenLengthHexString=util$6.ensureHexString=util$6.isHexString=util$6.prepend0x=util$6.strip0x=util$6.has0xPrefix=util$6.hexStringFromIntNumber=util$6.intNumberFromHexString=util$6.bigIntStringFromBigInt=util$6.hexStringFromBuffer=util$6.hexStringToUint8Array=util$6.uint8ArrayToHex=util$6.randomBytesHex=void 0;const error_1$8=error$2,_1=type$3,INT_STRING_REGEX=/^[0-9]*$/,HEXADECIMAL_STRING_REGEX=/^[a-f0-9]*$/;function randomBytesHex(Xr){return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(Xr)))}util$6.randomBytesHex=randomBytesHex;function uint8ArrayToHex(Xr){return[...Xr].map(eo=>eo.toString(16).padStart(2,"0")).join("")}util$6.uint8ArrayToHex=uint8ArrayToHex;function hexStringToUint8Array(Xr){return new Uint8Array(Xr.match(/.{1,2}/g).map(eo=>parseInt(eo,16)))}util$6.hexStringToUint8Array=hexStringToUint8Array;function hexStringFromBuffer(Xr,eo=!1){const to=Xr.toString("hex");return(0,_1.HexString)(eo?`0x${to}`:to)}util$6.hexStringFromBuffer=hexStringFromBuffer;function bigIntStringFromBigInt(Xr){return(0,_1.BigIntString)(Xr.toString(10))}util$6.bigIntStringFromBigInt=bigIntStringFromBigInt;function intNumberFromHexString(Xr){return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(Xr,!0))))}util$6.intNumberFromHexString=intNumberFromHexString;function hexStringFromIntNumber(Xr){return(0,_1.HexString)(`0x${BigInt(Xr).toString(16)}`)}util$6.hexStringFromIntNumber=hexStringFromIntNumber;function has0xPrefix(Xr){return Xr.startsWith("0x")||Xr.startsWith("0X")}util$6.has0xPrefix=has0xPrefix;function strip0x$1(Xr){return has0xPrefix(Xr)?Xr.slice(2):Xr}util$6.strip0x=strip0x$1;function prepend0x(Xr){return has0xPrefix(Xr)?`0x${Xr.slice(2)}`:`0x${Xr}`}util$6.prepend0x=prepend0x;function isHexString$1(Xr){if(typeof Xr!="string")return!1;const eo=strip0x$1(Xr).toLowerCase();return HEXADECIMAL_STRING_REGEX.test(eo)}util$6.isHexString=isHexString$1;function ensureHexString(Xr,eo=!1){if(typeof Xr=="string"){const to=strip0x$1(Xr).toLowerCase();if(HEXADECIMAL_STRING_REGEX.test(to))return(0,_1.HexString)(eo?`0x${to}`:to)}throw error_1$8.standardErrors.rpc.invalidParams(`"${String(Xr)}" is not a hexadecimal string`)}util$6.ensureHexString=ensureHexString;function ensureEvenLengthHexString(Xr,eo=!1){let to=ensureHexString(Xr,!1);return to.length%2===1&&(to=(0,_1.HexString)(`0${to}`)),eo?(0,_1.HexString)(`0x${to}`):to}util$6.ensureEvenLengthHexString=ensureEvenLengthHexString;function ensureAddressString(Xr){if(typeof Xr=="string"){const eo=strip0x$1(Xr).toLowerCase();if(isHexString$1(eo)&&eo.length===40)return(0,_1.AddressString)(prepend0x(eo))}throw error_1$8.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(Xr)}`)}util$6.ensureAddressString=ensureAddressString;function ensureBuffer(Xr){if(Buffer$3.isBuffer(Xr))return Xr;if(typeof Xr=="string"){if(isHexString$1(Xr)){const eo=ensureEvenLengthHexString(Xr,!1);return Buffer$3.from(eo,"hex")}return Buffer$3.from(Xr,"utf8")}throw error_1$8.standardErrors.rpc.invalidParams(`Not binary data: ${String(Xr)}`)}util$6.ensureBuffer=ensureBuffer;function ensureIntNumber(Xr){if(typeof Xr=="number"&&Number.isInteger(Xr))return(0,_1.IntNumber)(Xr);if(typeof Xr=="string"){if(INT_STRING_REGEX.test(Xr))return(0,_1.IntNumber)(Number(Xr));if(isHexString$1(Xr))return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(Xr,!0))))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(Xr)}`)}util$6.ensureIntNumber=ensureIntNumber;function ensureRegExpString(Xr){if(Xr instanceof RegExp)return(0,_1.RegExpString)(Xr.toString());throw error_1$8.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(Xr)}`)}util$6.ensureRegExpString=ensureRegExpString;function ensureBigInt(Xr){if(Xr!==null&&(typeof Xr=="bigint"||isBigNumber(Xr)))return BigInt(Xr.toString(10));if(typeof Xr=="number")return BigInt(ensureIntNumber(Xr));if(typeof Xr=="string"){if(INT_STRING_REGEX.test(Xr))return BigInt(Xr);if(isHexString$1(Xr))return BigInt(ensureEvenLengthHexString(Xr,!0))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(Xr)}`)}util$6.ensureBigInt=ensureBigInt;function ensureParsedJSONObject(Xr){if(typeof Xr=="string")return JSON.parse(Xr);if(typeof Xr=="object")return Xr;throw error_1$8.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(Xr)}`)}util$6.ensureParsedJSONObject=ensureParsedJSONObject;function isBigNumber(Xr){if(Xr==null||typeof Xr.constructor!="function")return!1;const{constructor:eo}=Xr;return typeof eo.config=="function"&&typeof eo.EUCLID=="number"}util$6.isBigNumber=isBigNumber;function range(Xr,eo){return Array.from({length:eo-Xr},(to,ro)=>Xr+ro)}util$6.range=range;function getFavicon(){const Xr=document.querySelector('link[sizes="192x192"]')||document.querySelector('link[sizes="180x180"]')||document.querySelector('link[rel="icon"]')||document.querySelector('link[rel="shortcut icon"]'),{protocol:eo,host:to}=document.location,ro=Xr?Xr.getAttribute("href"):null;return!ro||ro.startsWith("javascript:")||ro.startsWith("vbscript:")?null:ro.startsWith("http://")||ro.startsWith("https://")||ro.startsWith("data:")?ro:ro.startsWith("//")?eo+ro:`${eo}//${to}${ro}`}util$6.getFavicon=getFavicon;function areAddressArraysEqual(Xr,eo){return Xr.length===eo.length&&Xr.every((to,ro)=>to===eo[ro])}util$6.areAddressArraysEqual=areAddressArraysEqual;var util$5={},SCWSigner$1={},SCWKeyManager$1={},cipher={};Object.defineProperty(cipher,"__esModule",{value:!0});cipher.decryptContent=cipher.encryptContent=cipher.importKeyFromHexString=cipher.exportKeyToHexString=cipher.decrypt=cipher.encrypt=cipher.deriveSharedSecret=cipher.generateKeyPair=void 0;const util_1$b=util$6;async function generateKeyPair(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}cipher.generateKeyPair=generateKeyPair;async function deriveSharedSecret(Xr,eo){return crypto.subtle.deriveKey({name:"ECDH",public:eo},Xr,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}cipher.deriveSharedSecret=deriveSharedSecret;async function encrypt(Xr,eo){const to=crypto.getRandomValues(new Uint8Array(12)),ro=await crypto.subtle.encrypt({name:"AES-GCM",iv:to},Xr,new TextEncoder().encode(eo));return{iv:to,cipherText:ro}}cipher.encrypt=encrypt;async function decrypt(Xr,{iv:eo,cipherText:to}){const ro=await crypto.subtle.decrypt({name:"AES-GCM",iv:eo},Xr,to);return new TextDecoder().decode(ro)}cipher.decrypt=decrypt;function getFormat(Xr){switch(Xr){case"public":return"spki";case"private":return"pkcs8"}}async function exportKeyToHexString(Xr,eo){const to=getFormat(Xr),ro=await crypto.subtle.exportKey(to,eo);return(0,util_1$b.uint8ArrayToHex)(new Uint8Array(ro))}cipher.exportKeyToHexString=exportKeyToHexString;async function importKeyFromHexString(Xr,eo){const to=getFormat(Xr),ro=(0,util_1$b.hexStringToUint8Array)(eo).buffer;return await crypto.subtle.importKey(to,ro,{name:"ECDH",namedCurve:"P-256"},!0,Xr==="private"?["deriveKey"]:[])}cipher.importKeyFromHexString=importKeyFromHexString;async function encryptContent(Xr,eo){const to=JSON.stringify(Xr,(ro,no)=>{if(!(no instanceof Error))return no;const io=no;return Object.assign(Object.assign({},io.code?{code:io.code}:{}),{message:io.message})});return encrypt(eo,to)}cipher.encryptContent=encryptContent;async function decryptContent(Xr,eo){return JSON.parse(await decrypt(eo,Xr))}cipher.decryptContent=decryptContent;var ScopedLocalStorage$1={};Object.defineProperty(ScopedLocalStorage$1,"__esModule",{value:!0});ScopedLocalStorage$1.ScopedLocalStorage=void 0;class ScopedLocalStorage{constructor(eo,to){this.scope=eo,this.module=to}setItem(eo,to){localStorage.setItem(this.scopedKey(eo),to)}getItem(eo){return localStorage.getItem(this.scopedKey(eo))}removeItem(eo){localStorage.removeItem(this.scopedKey(eo))}clear(){const eo=this.scopedKey(""),to=[];for(let ro=0;rolocalStorage.removeItem(ro))}scopedKey(eo){return`-${this.scope}${this.module?`:${this.module}`:""}:${eo}`}static clearAll(){new ScopedLocalStorage("CBWSDK").clear(),new ScopedLocalStorage("walletlink").clear()}}ScopedLocalStorage$1.ScopedLocalStorage=ScopedLocalStorage;Object.defineProperty(SCWKeyManager$1,"__esModule",{value:!0});SCWKeyManager$1.SCWKeyManager=void 0;const cipher_1$1=cipher,ScopedLocalStorage_1$6=ScopedLocalStorage$1,OWN_PRIVATE_KEY={storageKey:"ownPrivateKey",keyType:"private"},OWN_PUBLIC_KEY={storageKey:"ownPublicKey",keyType:"public"},PEER_PUBLIC_KEY={storageKey:"peerPublicKey",keyType:"public"};class SCWKeyManager{constructor(){this.storage=new ScopedLocalStorage_1$6.ScopedLocalStorage("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(eo){this.sharedSecret=null,this.peerPublicKey=eo,await this.storeKey(PEER_PUBLIC_KEY,eo),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(OWN_PUBLIC_KEY.storageKey),this.storage.removeItem(OWN_PRIVATE_KEY.storageKey),this.storage.removeItem(PEER_PUBLIC_KEY.storageKey)}async generateKeyPair(){const eo=await(0,cipher_1$1.generateKeyPair)();this.ownPrivateKey=eo.privateKey,this.ownPublicKey=eo.publicKey,await this.storeKey(OWN_PRIVATE_KEY,eo.privateKey),await this.storeKey(OWN_PUBLIC_KEY,eo.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(OWN_PRIVATE_KEY)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(OWN_PUBLIC_KEY)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey(PEER_PUBLIC_KEY)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await(0,cipher_1$1.deriveSharedSecret)(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(eo){const to=this.storage.getItem(eo.storageKey);return to?(0,cipher_1$1.importKeyFromHexString)(eo.keyType,to):null}async storeKey(eo,to){const ro=await(0,cipher_1$1.exportKeyToHexString)(eo.keyType,to);this.storage.setItem(eo.storageKey,ro)}}SCWKeyManager$1.SCWKeyManager=SCWKeyManager;var SCWStateManager$1={};Object.defineProperty(SCWStateManager$1,"__esModule",{value:!0});SCWStateManager$1.SCWStateManager=void 0;const ScopedLocalStorage_1$5=ScopedLocalStorage$1,ACCOUNTS_KEY="accounts",ACTIVE_CHAIN_STORAGE_KEY="activeChain",AVAILABLE_CHAINS_STORAGE_KEY="availableChains",WALLET_CAPABILITIES_STORAGE_KEY="walletCapabilities";class SCWStateManager{get accounts(){return this._accounts}get activeChain(){return this._activeChain}get walletCapabilities(){return this._walletCapabilities}constructor(eo){var to,ro;this.storage=new ScopedLocalStorage_1$5.ScopedLocalStorage("CBWSDK","SCWStateManager"),this.updateListener=eo.updateListener,this.availableChains=this.loadItemFromStorage(AVAILABLE_CHAINS_STORAGE_KEY),this._walletCapabilities=this.loadItemFromStorage(WALLET_CAPABILITIES_STORAGE_KEY);const no=this.loadItemFromStorage(ACCOUNTS_KEY),io=this.loadItemFromStorage(ACTIVE_CHAIN_STORAGE_KEY);no&&this.updateListener.onAccountsUpdate({accounts:no,source:"storage"}),io&&this.updateListener.onChainUpdate({chain:io,source:"storage"}),this._accounts=no||[],this._activeChain=io||{id:(ro=(to=eo.appChainIds)===null||to===void 0?void 0:to[0])!==null&&ro!==void 0?ro:1}}updateAccounts(eo){this._accounts=eo,this.storeItemToStorage(ACCOUNTS_KEY,eo),this.updateListener.onAccountsUpdate({accounts:eo,source:"wallet"})}switchChain(eo){var to;const ro=(to=this.availableChains)===null||to===void 0?void 0:to.find(no=>no.id===eo);return ro?(ro===this._activeChain||(this._activeChain=ro,this.storeItemToStorage(ACTIVE_CHAIN_STORAGE_KEY,ro),this.updateListener.onChainUpdate({chain:ro,source:"wallet"})),!0):!1}updateAvailableChains(eo){if(!eo||Object.keys(eo).length===0)return;const to=Object.entries(eo).map(([ro,no])=>({id:Number(ro),rpcUrl:no}));this.availableChains=to,this.storeItemToStorage(AVAILABLE_CHAINS_STORAGE_KEY,to),this.switchChain(this._activeChain.id)}updateWalletCapabilities(eo){this._walletCapabilities=eo,this.storeItemToStorage(WALLET_CAPABILITIES_STORAGE_KEY,eo)}storeItemToStorage(eo,to){this.storage.setItem(eo,JSON.stringify(to))}loadItemFromStorage(eo){const to=this.storage.getItem(eo);return to?JSON.parse(to):void 0}clear(){this.storage.clear()}}SCWStateManager$1.SCWStateManager=SCWStateManager;Object.defineProperty(SCWSigner$1,"__esModule",{value:!0});SCWSigner$1.SCWSigner=void 0;const SCWKeyManager_1=SCWKeyManager$1,SCWStateManager_1=SCWStateManager$1,error_1$7=error$2,util_1$a=util$6,cipher_1=cipher;class SCWSigner{constructor(eo){this.metadata=eo.metadata,this.communicator=eo.communicator,this.keyManager=new SCWKeyManager_1.SCWKeyManager,this.stateManager=new SCWStateManager_1.SCWStateManager({appChainIds:this.metadata.appChainIds,updateListener:eo.updateListener}),this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(){const eo=await this.createRequestMessage({handshake:{method:"eth_requestAccounts",params:this.metadata}}),to=await this.communicator.postRequestAndWaitForResponse(eo);if("failure"in to.content)throw to.content.failure;const ro=await(0,cipher_1.importKeyFromHexString)("public",to.sender);await this.keyManager.setPeerPublicKey(ro);const no=await this.decryptResponseMessage(to);this.updateInternalState({method:"eth_requestAccounts"},no);const io=no.result;if("error"in io)throw io.error;return this.stateManager.accounts}async request(eo){const to=this.tryLocalHandling(eo);if(to!==void 0){if(to instanceof Error)throw to;return to}await this.communicator.waitForPopupLoaded();const ro=await this.sendEncryptedRequest(eo),no=await this.decryptResponseMessage(ro);this.updateInternalState(eo,no);const io=no.result;if("error"in io)throw io.error;return io.value}async disconnect(){this.stateManager.clear(),await this.keyManager.clear()}tryLocalHandling(eo){var to;switch(eo.method){case"wallet_switchEthereumChain":{const ro=eo.params;if(!ro||!(!((to=ro[0])===null||to===void 0)&&to.chainId))throw error_1$7.standardErrors.rpc.invalidParams();const no=(0,util_1$a.ensureIntNumber)(ro[0].chainId);return this.stateManager.switchChain(no)?null:void 0}case"wallet_getCapabilities":{const ro=this.stateManager.walletCapabilities;if(!ro)throw error_1$7.standardErrors.provider.unauthorized("No wallet capabilities found, please disconnect and reconnect");return ro}default:return}}async sendEncryptedRequest(eo){const to=await this.keyManager.getSharedSecret();if(!to)throw error_1$7.standardErrors.provider.unauthorized("No valid session found, try requestAccounts before other methods");const ro=await(0,cipher_1.encryptContent)({action:eo,chainId:this.stateManager.activeChain.id},to),no=await this.createRequestMessage({encrypted:ro});return this.communicator.postRequestAndWaitForResponse(no)}async createRequestMessage(eo){const to=await(0,cipher_1.exportKeyToHexString)("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:to,content:eo,timestamp:new Date}}async decryptResponseMessage(eo){const to=eo.content;if("failure"in to)throw to.failure;const ro=await this.keyManager.getSharedSecret();if(!ro)throw error_1$7.standardErrors.provider.unauthorized("Invalid session");return(0,cipher_1.decryptContent)(to.encrypted,ro)}updateInternalState(eo,to){var ro,no;const io=(ro=to.data)===null||ro===void 0?void 0:ro.chains;io&&this.stateManager.updateAvailableChains(io);const oo=(no=to.data)===null||no===void 0?void 0:no.capabilities;oo&&this.stateManager.updateWalletCapabilities(oo);const ao=to.result;if(!("error"in ao))switch(eo.method){case"eth_requestAccounts":{const so=ao.value;this.stateManager.updateAccounts(so);break}case"wallet_switchEthereumChain":{if(ao.value!==null)return;const so=eo.params,co=(0,util_1$a.ensureIntNumber)(so[0].chainId);this.stateManager.switchChain(co);break}}}}SCWSigner$1.SCWSigner=SCWSigner;var WalletLinkSigner$1={};const{Transform:Transform$1}=requireReadableBrowser$1();var keccak$3=Xr=>class A_ extends Transform$1{constructor(to,ro,no,io,oo){super(oo),this._rate=to,this._capacity=ro,this._delimitedSuffix=no,this._hashBitLength=io,this._options=oo,this._state=new Xr,this._state.initialize(to,ro),this._finalized=!1}_transform(to,ro,no){let io=null;try{this.update(to,ro)}catch(oo){io=oo}no(io)}_flush(to){let ro=null;try{this.push(this.digest())}catch(no){ro=no}to(ro)}update(to,ro){if(!Buffer$3.isBuffer(to)&&typeof to!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return Buffer$3.isBuffer(to)||(to=Buffer$3.from(to,ro)),this._state.absorb(to),this}digest(to){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let ro=this._state.squeeze(this._hashBitLength/8);return to!==void 0&&(ro=ro.toString(to)),this._resetState(),ro}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const to=new A_(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(to._state),to._finalized=this._finalized,to}};const{Transform}=requireReadableBrowser$1();var shake=Xr=>class P_ extends Transform{constructor(to,ro,no,io){super(io),this._rate=to,this._capacity=ro,this._delimitedSuffix=no,this._options=io,this._state=new Xr,this._state.initialize(to,ro),this._finalized=!1}_transform(to,ro,no){let io=null;try{this.update(to,ro)}catch(oo){io=oo}no(io)}_flush(){}_read(to){this.push(this.squeeze(to))}update(to,ro){if(!Buffer$3.isBuffer(to)&&typeof to!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return Buffer$3.isBuffer(to)||(to=Buffer$3.from(to,ro)),this._state.absorb(to),this}squeeze(to,ro){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let no=this._state.squeeze(to);return ro!==void 0&&(no=no.toString(ro)),no}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const to=new P_(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(to._state),to._finalized=this._finalized,to}};const createKeccak=keccak$3,createShake=shake;var api=function(Xr){const eo=createKeccak(Xr),to=createShake(Xr);return function(ro,no){switch(typeof ro=="string"?ro.toLowerCase():ro){case"keccak224":return new eo(1152,448,null,224,no);case"keccak256":return new eo(1088,512,null,256,no);case"keccak384":return new eo(832,768,null,384,no);case"keccak512":return new eo(576,1024,null,512,no);case"sha3-224":return new eo(1152,448,6,224,no);case"sha3-256":return new eo(1088,512,6,256,no);case"sha3-384":return new eo(832,768,6,384,no);case"sha3-512":return new eo(576,1024,6,512,no);case"shake128":return new to(1344,256,31,no);case"shake256":return new to(1088,512,31,no);default:throw new Error("Invald algorithm: "+ro)}}},keccakStateUnroll={};const P1600_ROUND_CONSTANTS=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];keccakStateUnroll.p1600=function(Xr){for(let eo=0;eo<24;++eo){const to=Xr[0]^Xr[10]^Xr[20]^Xr[30]^Xr[40],ro=Xr[1]^Xr[11]^Xr[21]^Xr[31]^Xr[41],no=Xr[2]^Xr[12]^Xr[22]^Xr[32]^Xr[42],io=Xr[3]^Xr[13]^Xr[23]^Xr[33]^Xr[43],oo=Xr[4]^Xr[14]^Xr[24]^Xr[34]^Xr[44],ao=Xr[5]^Xr[15]^Xr[25]^Xr[35]^Xr[45],so=Xr[6]^Xr[16]^Xr[26]^Xr[36]^Xr[46],co=Xr[7]^Xr[17]^Xr[27]^Xr[37]^Xr[47],lo=Xr[8]^Xr[18]^Xr[28]^Xr[38]^Xr[48],fo=Xr[9]^Xr[19]^Xr[29]^Xr[39]^Xr[49];let ho=lo^(no<<1|io>>>31),go=fo^(io<<1|no>>>31);const yo=Xr[0]^ho,vo=Xr[1]^go,wo=Xr[10]^ho,Eo=Xr[11]^go,ko=Xr[20]^ho,Ao=Xr[21]^go,Po=Xr[30]^ho,jo=Xr[31]^go,Mo=Xr[40]^ho,No=Xr[41]^go;ho=to^(oo<<1|ao>>>31),go=ro^(ao<<1|oo>>>31);const Do=Xr[2]^ho,Fo=Xr[3]^go,Xo=Xr[12]^ho,Lo=Xr[13]^go,Bo=Xr[22]^ho,xo=Xr[23]^go,uo=Xr[32]^ho,po=Xr[33]^go,bo=Xr[42]^ho,_o=Xr[43]^go;ho=no^(so<<1|co>>>31),go=io^(co<<1|so>>>31);const $o=Xr[4]^ho,Co=Xr[5]^go,Ro=Xr[14]^ho,So=Xr[15]^go,mo=Xr[24]^ho,To=Xr[25]^go,Vo=Xr[34]^ho,Zo=Xr[35]^go,Qo=Xr[44]^ho,qo=Xr[45]^go;ho=oo^(lo<<1|fo>>>31),go=ao^(fo<<1|lo>>>31);const Ho=Xr[6]^ho,$a=Xr[7]^go,zo=Xr[16]^ho,Ko=Xr[17]^go,_c=Xr[26]^ho,Cl=Xr[27]^go,ga=Xr[36]^ho,El=Xr[37]^go,Al=Xr[46]^ho,Ol=Xr[47]^go;ho=so^(to<<1|ro>>>31),go=co^(ro<<1|to>>>31);const Wl=Xr[8]^ho,zl=Xr[9]^go,Tl=Xr[18]^ho,Ml=Xr[19]^go,ou=Xr[28]^ho,Vl=Xr[29]^go,Ll=Xr[38]^ho,uu=Xr[39]^go,ru=Xr[48]^ho,tu=Xr[49]^go,ku=yo,au=vo,wl=Eo<<4|wo>>>28,Jo=wo<<4|Eo>>>28,Go=ko<<3|Ao>>>29,$l=Ao<<3|ko>>>29,Zl=jo<<9|Po>>>23,Ul=Po<<9|jo>>>23,Gl=Mo<<18|No>>>14,Nu=No<<18|Mo>>>14,hu=Do<<1|Fo>>>31,cu=Fo<<1|Do>>>31,Wu=Lo<<12|Xo>>>20,mu=Xo<<12|Lo>>>20,yu=Bo<<10|xo>>>22,Yu=xo<<10|Bo>>>22,_u=po<<13|uo>>>19,Il=uo<<13|po>>>19,Nl=bo<<2|_o>>>30,Pl=_o<<2|bo>>>30,Bl=Co<<30|$o>>>2,fu=$o<<30|Co>>>2,eu=Ro<<6|So>>>26,Xl=So<<6|Ro>>>26,$u=To<<11|mo>>>21,Yo=mo<<11|To>>>21,_l=Vo<<15|Zo>>>17,Sl=Zo<<15|Vo>>>17,Wo=qo<<29|Qo>>>3,xl=Qo<<29|qo>>>3,Ql=Ho<<28|$a>>>4,Fl=$a<<28|Ho>>>4,Jl=Ko<<23|zo>>>9,xu=zo<<23|Ko>>>9,lu=_c<<25|Cl>>>7,su=Cl<<25|_c>>>7,Xu=ga<<21|El>>>11,ju=El<<21|ga>>>11,zu=Ol<<24|Al>>>8,Ku=Al<<24|Ol>>>8,Hu=Wl<<27|zl>>>5,Gu=zl<<27|Wl>>>5,Zu=Tl<<20|Ml>>>12,Vu=Ml<<20|Tl>>>12,Ju=Vl<<7|ou>>>25,Uu=ou<<7|Vl>>>25,qu=Ll<<8|uu>>>24,Mu=uu<<8|Ll>>>24,Bu=ru<<14|tu>>>18,Au=tu<<14|ru>>>18;Xr[0]=ku^~Wu&$u,Xr[1]=au^~mu&Yo,Xr[10]=Ql^~Zu&Go,Xr[11]=Fl^~Vu&$l,Xr[20]=hu^~eu&lu,Xr[21]=cu^~Xl&su,Xr[30]=Hu^~wl&yu,Xr[31]=Gu^~Jo&Yu,Xr[40]=Bl^~Jl&Ju,Xr[41]=fu^~xu&Uu,Xr[2]=Wu^~$u&Xu,Xr[3]=mu^~Yo&ju,Xr[12]=Zu^~Go&_u,Xr[13]=Vu^~$l&Il,Xr[22]=eu^~lu&qu,Xr[23]=Xl^~su&Mu,Xr[32]=wl^~yu&_l,Xr[33]=Jo^~Yu&Sl,Xr[42]=Jl^~Ju&Zl,Xr[43]=xu^~Uu&Ul,Xr[4]=$u^~Xu&Bu,Xr[5]=Yo^~ju&Au,Xr[14]=Go^~_u&Wo,Xr[15]=$l^~Il&xl,Xr[24]=lu^~qu&Gl,Xr[25]=su^~Mu&Nu,Xr[34]=yu^~_l&zu,Xr[35]=Yu^~Sl&Ku,Xr[44]=Ju^~Zl&Nl,Xr[45]=Uu^~Ul&Pl,Xr[6]=Xu^~Bu&ku,Xr[7]=ju^~Au&au,Xr[16]=_u^~Wo&Ql,Xr[17]=Il^~xl&Fl,Xr[26]=qu^~Gl&hu,Xr[27]=Mu^~Nu&cu,Xr[36]=_l^~zu&Hu,Xr[37]=Sl^~Ku&Gu,Xr[46]=Zl^~Nl&Bl,Xr[47]=Ul^~Pl&fu,Xr[8]=Bu^~ku&Wu,Xr[9]=Au^~au&mu,Xr[18]=Wo^~Ql&Zu,Xr[19]=xl^~Fl&Vu,Xr[28]=Gl^~hu&eu,Xr[29]=Nu^~cu&Xl,Xr[38]=zu^~Hu&wl,Xr[39]=Ku^~Gu&Jo,Xr[48]=Nl^~Bl&Jl,Xr[49]=Pl^~fu&xu,Xr[0]^=P1600_ROUND_CONSTANTS[eo*2],Xr[1]^=P1600_ROUND_CONSTANTS[eo*2+1]}};const keccakState=keccakStateUnroll;function Keccak$1(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}Keccak$1.prototype.initialize=function(Xr,eo){for(let to=0;to<50;++to)this.state[to]=0;this.blockSize=Xr/8,this.count=0,this.squeezing=!1};Keccak$1.prototype.absorb=function(Xr){for(let eo=0;eo>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(keccakState.p1600(this.state),this.count=0);return eo};Keccak$1.prototype.copy=function(Xr){for(let eo=0;eo<50;++eo)Xr.state[eo]=this.state[eo];Xr.blockSize=this.blockSize,Xr.count=this.count,Xr.squeezing=this.squeezing};var keccak$2=Keccak$1,js$1=api(keccak$2);const createKeccakHash=js$1;function zeros(Xr){return Buffer$3.allocUnsafe(Xr).fill(0)}function bitLengthFromBigInt(Xr){return Xr.toString(2).length}function bufferBEFromBigInt(Xr,eo){let to=Xr.toString(16);to.length%2!==0&&(to="0"+to);const ro=to.match(/.{1,2}/g).map(no=>parseInt(no,16));for(;ro.length"u")throw new Error("Not an array?");if(to=parseTypeArray(Xr),to!=="dynamic"&&to!==0&&eo.length>to)throw new Error("Elements exceed array size: "+to);no=[],Xr=Xr.slice(0,Xr.lastIndexOf("[")),typeof eo=="string"&&(eo=JSON.parse(eo));for(io in eo)no.push(encodeSingle(Xr,eo[io]));if(to==="dynamic"){var oo=encodeSingle("uint256",eo.length);no.unshift(oo)}return Buffer$3.concat(no)}else{if(Xr==="bytes")return eo=new Buffer$3(eo),no=Buffer$3.concat([encodeSingle("uint256",eo.length),eo]),eo.length%32!==0&&(no=Buffer$3.concat([no,util$3.zeros(32-eo.length%32)])),no;if(Xr.startsWith("bytes")){if(to=parseTypeN(Xr),to<1||to>32)throw new Error("Invalid bytes width: "+to);return util$3.setLengthRight(eo,32)}else if(Xr.startsWith("uint")){if(to=parseTypeN(Xr),to%8||to<8||to>256)throw new Error("Invalid uint width: "+to);ro=parseNumber(eo);const ao=util$3.bitLengthFromBigInt(ro);if(ao>to)throw new Error("Supplied uint exceeds width: "+to+" vs "+ao);if(ro<0)throw new Error("Supplied uint is negative");return util$3.bufferBEFromBigInt(ro,32)}else if(Xr.startsWith("int")){if(to=parseTypeN(Xr),to%8||to<8||to>256)throw new Error("Invalid int width: "+to);ro=parseNumber(eo);const ao=util$3.bitLengthFromBigInt(ro);if(ao>to)throw new Error("Supplied int exceeds width: "+to+" vs "+ao);const so=util$3.twosFromBigInt(ro,256);return util$3.bufferBEFromBigInt(so,32)}else if(Xr.startsWith("ufixed")){if(to=parseTypeNxM(Xr),ro=parseNumber(eo),ro<0)throw new Error("Supplied ufixed is negative");return encodeSingle("uint256",ro*BigInt(2)**BigInt(to[1]))}else if(Xr.startsWith("fixed"))return to=parseTypeNxM(Xr),encodeSingle("int256",parseNumber(eo)*BigInt(2)**BigInt(to[1]))}throw new Error("Unsupported or invalid type: "+Xr)}function isDynamic(Xr){return Xr==="string"||Xr==="bytes"||parseTypeArray(Xr)==="dynamic"}function isArray$3(Xr){return Xr.lastIndexOf("]")===Xr.length-1}function rawEncode(Xr,eo){var to=[],ro=[],no=32*Xr.length;for(var io in Xr){var oo=elementaryName(Xr[io]),ao=eo[io],so=encodeSingle(oo,ao);isDynamic(oo)?(to.push(encodeSingle("uint256",no)),ro.push(so),no+=so.length):to.push(so)}return Buffer$3.concat(to.concat(ro))}function solidityPack(Xr,eo){if(Xr.length!==eo.length)throw new Error("Number of types are not matching the values");for(var to,ro,no=[],io=0;io32)throw new Error("Invalid bytes width: "+to);no.push(util$3.setLengthRight(ao,to))}else if(oo.startsWith("uint")){if(to=parseTypeN(oo),to%8||to<8||to>256)throw new Error("Invalid uint width: "+to);ro=parseNumber(ao);const so=util$3.bitLengthFromBigInt(ro);if(so>to)throw new Error("Supplied uint exceeds width: "+to+" vs "+so);no.push(util$3.bufferBEFromBigInt(ro,to/8))}else if(oo.startsWith("int")){if(to=parseTypeN(oo),to%8||to<8||to>256)throw new Error("Invalid int width: "+to);ro=parseNumber(ao);const so=util$3.bitLengthFromBigInt(ro);if(so>to)throw new Error("Supplied int exceeds width: "+to+" vs "+so);const co=util$3.twosFromBigInt(ro,to);no.push(util$3.bufferBEFromBigInt(co,to/8))}else throw new Error("Unsupported or invalid type: "+oo)}return Buffer$3.concat(no)}function soliditySHA3(Xr,eo){return util$3.keccak(solidityPack(Xr,eo))}var abi$1={rawEncode,solidityPack,soliditySHA3};const util$2=util$4,abi=abi$1,TYPED_MESSAGE_SCHEMA={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},TypedDataUtils={encodeData(Xr,eo,to,ro=!0){const no=["bytes32"],io=[this.hashType(Xr,to)];if(ro){const oo=(ao,so,co)=>{if(to[so]!==void 0)return["bytes32",co==null?"0x0000000000000000000000000000000000000000000000000000000000000000":util$2.keccak(this.encodeData(so,co,to,ro))];if(co===void 0)throw new Error(`missing value for field ${ao} of type ${so}`);if(so==="bytes")return["bytes32",util$2.keccak(co)];if(so==="string")return typeof co=="string"&&(co=Buffer$3.from(co,"utf8")),["bytes32",util$2.keccak(co)];if(so.lastIndexOf("]")===so.length-1){const lo=so.slice(0,so.lastIndexOf("[")),fo=co.map(ho=>oo(ao,lo,ho));return["bytes32",util$2.keccak(abi.rawEncode(fo.map(([ho])=>ho),fo.map(([,ho])=>ho)))]}return[so,co]};for(const ao of to[Xr]){const[so,co]=oo(ao.name,ao.type,eo[ao.name]);no.push(so),io.push(co)}}else for(const oo of to[Xr]){let ao=eo[oo.name];if(ao!==void 0)if(oo.type==="bytes")no.push("bytes32"),ao=util$2.keccak(ao),io.push(ao);else if(oo.type==="string")no.push("bytes32"),typeof ao=="string"&&(ao=Buffer$3.from(ao,"utf8")),ao=util$2.keccak(ao),io.push(ao);else if(to[oo.type]!==void 0)no.push("bytes32"),ao=util$2.keccak(this.encodeData(oo.type,ao,to,ro)),io.push(ao);else{if(oo.type.lastIndexOf("]")===oo.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");no.push(oo.type),io.push(ao)}}return abi.rawEncode(no,io)},encodeType(Xr,eo){let to="",ro=this.findTypeDependencies(Xr,eo).filter(no=>no!==Xr);ro=[Xr].concat(ro.sort());for(const no of ro){if(!eo[no])throw new Error("No type definition specified: "+no);to+=no+"("+eo[no].map(({name:oo,type:ao})=>ao+" "+oo).join(",")+")"}return to},findTypeDependencies(Xr,eo,to=[]){if(Xr=Xr.match(/^\w*/)[0],to.includes(Xr)||eo[Xr]===void 0)return to;to.push(Xr);for(const ro of eo[Xr])for(const no of this.findTypeDependencies(ro.type,eo,to))!to.includes(no)&&to.push(no);return to},hashStruct(Xr,eo,to,ro=!0){return util$2.keccak(this.encodeData(Xr,eo,to,ro))},hashType(Xr,eo){return util$2.keccak(this.encodeType(Xr,eo))},sanitizeData(Xr){const eo={};for(const to in TYPED_MESSAGE_SCHEMA.properties)Xr[to]&&(eo[to]=Xr[to]);return eo.types&&(eo.types=Object.assign({EIP712Domain:[]},eo.types)),eo},hash(Xr,eo=!0){const to=this.sanitizeData(Xr),ro=[Buffer$3.from("1901","hex")];return ro.push(this.hashStruct("EIP712Domain",to.domain,to.types,eo)),to.primaryType!=="EIP712Domain"&&ro.push(this.hashStruct(to.primaryType,to.message,to.types,eo)),util$2.keccak(Buffer$3.concat(ro))}};var ethEip712Util={TYPED_MESSAGE_SCHEMA,TypedDataUtils,hashForSignTypedDataLegacy:function(Xr){return typedSignatureHashLegacy(Xr.data)},hashForSignTypedData_v3:function(Xr){return TypedDataUtils.hash(Xr.data,!1)},hashForSignTypedData_v4:function(Xr){return TypedDataUtils.hash(Xr.data)}};function typedSignatureHashLegacy(Xr){const eo=new Error("Expect argument to be non-empty array");if(typeof Xr!="object"||!Xr.length)throw eo;const to=Xr.map(function(io){return io.type==="bytes"?util$2.toBuffer(io.value):io.value}),ro=Xr.map(function(io){return io.type}),no=Xr.map(function(io){if(!io.name)throw eo;return io.type+" "+io.name});return abi.soliditySHA3(["bytes32","bytes32"],[abi.soliditySHA3(new Array(Xr.length).fill("string"),no),abi.soliditySHA3(ro,to)])}var constants$4={};Object.defineProperty(constants$4,"__esModule",{value:!0});constants$4.APP_VERSION_KEY=constants$4.LOCAL_STORAGE_ADDRESSES_KEY=constants$4.WALLET_USER_NAME_KEY=void 0;constants$4.WALLET_USER_NAME_KEY="walletUsername";constants$4.LOCAL_STORAGE_ADDRESSES_KEY="Addresses";constants$4.APP_VERSION_KEY="AppVersion";var RelayEventManager$1={};Object.defineProperty(RelayEventManager$1,"__esModule",{value:!0});RelayEventManager$1.RelayEventManager=void 0;const util_1$9=util$6;class RelayEventManager{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const eo=this._nextRequestId,to=(0,util_1$9.prepend0x)(eo.toString(16));return this.callbacks.get(to)&&this.callbacks.delete(to),eo}}RelayEventManager$1.RelayEventManager=RelayEventManager;var WalletLinkRelay$1={},WalletLinkConnection$1={},WalletLinkCipher$1={};Object.defineProperty(WalletLinkCipher$1,"__esModule",{value:!0});WalletLinkCipher$1.WalletLinkCipher=void 0;const util_1$8=util$6;class WalletLinkCipher{constructor(eo){this.secret=eo}async encrypt(eo){const to=this.secret;if(to.length!==64)throw Error("secret must be 256 bits");const ro=crypto.getRandomValues(new Uint8Array(12)),no=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(to),{name:"aes-gcm"},!1,["encrypt","decrypt"]),io=new TextEncoder,oo=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:ro},no,io.encode(eo)),ao=16,so=oo.slice(oo.byteLength-ao),co=oo.slice(0,oo.byteLength-ao),lo=new Uint8Array(so),fo=new Uint8Array(co),ho=new Uint8Array([...ro,...lo,...fo]);return(0,util_1$8.uint8ArrayToHex)(ho)}async decrypt(eo){const to=this.secret;if(to.length!==64)throw Error("secret must be 256 bits");return new Promise((ro,no)=>{(async function(){const io=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(to),{name:"aes-gcm"},!1,["encrypt","decrypt"]),oo=(0,util_1$8.hexStringToUint8Array)(eo),ao=oo.slice(0,12),so=oo.slice(12,28),co=oo.slice(28),lo=new Uint8Array([...co,...so]),fo={name:"AES-GCM",iv:new Uint8Array(ao)};try{const ho=await window.crypto.subtle.decrypt(fo,io,lo),go=new TextDecoder;ro(go.decode(ho))}catch(ho){no(ho)}})()})}}WalletLinkCipher$1.WalletLinkCipher=WalletLinkCipher;var WalletLinkHTTP$1={};Object.defineProperty(WalletLinkHTTP$1,"__esModule",{value:!0});WalletLinkHTTP$1.WalletLinkHTTP=void 0;class WalletLinkHTTP{constructor(eo,to,ro){this.linkAPIUrl=eo,this.sessionId=to;const no=`${to}:${ro}`;this.auth=`Basic ${btoa(no)}`}async markUnseenEventsAsSeen(eo){return Promise.all(eo.map(to=>fetch(`${this.linkAPIUrl}/events/${to.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(to=>console.error("Unabled to mark event as failed:",to))}async fetchUnseenEvents(){var eo;const to=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(to.ok){const{events:ro,error:no}=await to.json();if(no)throw new Error(`Check unseen events failed: ${no}`);const io=(eo=ro==null?void 0:ro.filter(oo=>oo.event==="Web3Response").map(oo=>({type:"Event",sessionId:this.sessionId,eventId:oo.id,event:oo.event,data:oo.data})))!==null&&eo!==void 0?eo:[];return this.markUnseenEventsAsSeen(io),io}throw new Error(`Check unseen events failed: ${to.status}`)}}WalletLinkHTTP$1.WalletLinkHTTP=WalletLinkHTTP;var WalletLinkWebSocket$1={};Object.defineProperty(WalletLinkWebSocket$1,"__esModule",{value:!0});WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket$1.ConnectionState=void 0;var ConnectionState;(function(Xr){Xr[Xr.DISCONNECTED=0]="DISCONNECTED",Xr[Xr.CONNECTING=1]="CONNECTING",Xr[Xr.CONNECTED=2]="CONNECTED"})(ConnectionState||(WalletLinkWebSocket$1.ConnectionState=ConnectionState={}));class WalletLinkWebSocket{setConnectionStateListener(eo){this.connectionStateListener=eo}setIncomingDataListener(eo){this.incomingDataListener=eo}constructor(eo,to=WebSocket){this.WebSocketClass=to,this.webSocket=null,this.pendingData=[],this.url=eo.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((eo,to)=>{var ro;let no;try{this.webSocket=no=new this.WebSocketClass(this.url)}catch(io){to(io);return}(ro=this.connectionStateListener)===null||ro===void 0||ro.call(this,ConnectionState.CONNECTING),no.onclose=io=>{var oo;this.clearWebSocket(),to(new Error(`websocket error ${io.code}: ${io.reason}`)),(oo=this.connectionStateListener)===null||oo===void 0||oo.call(this,ConnectionState.DISCONNECTED)},no.onopen=io=>{var oo;eo(),(oo=this.connectionStateListener)===null||oo===void 0||oo.call(this,ConnectionState.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(so=>this.sendData(so)),this.pendingData=[])},no.onmessage=io=>{var oo,ao;if(io.data==="h")(oo=this.incomingDataListener)===null||oo===void 0||oo.call(this,{type:"Heartbeat"});else try{const so=JSON.parse(io.data);(ao=this.incomingDataListener)===null||ao===void 0||ao.call(this,so)}catch{}}})}disconnect(){var eo;const{webSocket:to}=this;if(to){this.clearWebSocket(),(eo=this.connectionStateListener)===null||eo===void 0||eo.call(this,ConnectionState.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{to.close()}catch{}}}sendData(eo){const{webSocket:to}=this;if(!to){this.pendingData.push(eo),this.connect();return}to.send(eo)}clearWebSocket(){const{webSocket:eo}=this;eo&&(this.webSocket=null,eo.onclose=null,eo.onerror=null,eo.onmessage=null,eo.onopen=null)}}WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket;Object.defineProperty(WalletLinkConnection$1,"__esModule",{value:!0});WalletLinkConnection$1.WalletLinkConnection=void 0;const constants_1$4=constants$4,WalletLinkCipher_1=WalletLinkCipher$1,WalletLinkHTTP_1=WalletLinkHTTP$1,WalletLinkWebSocket_1=WalletLinkWebSocket$1,type_1$1=type$3,HEARTBEAT_INTERVAL=1e4,REQUEST_TIMEOUT=6e4;class WalletLinkConnection{constructor({session:eo,linkAPIUrl:to,listener:ro,WebSocketClass:no=WebSocket}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=(0,type_1$1.IntNumber)(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=oo=>{if(!oo)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",so=>oo.JsonRpcUrl&&this.handleChainUpdated(so,oo.JsonRpcUrl)]]).forEach((so,co)=>{const lo=oo[co];lo!==void 0&&so(lo)})},this.handleDestroyed=oo=>{var ao;oo==="1"&&((ao=this.listener)===null||ao===void 0||ao.resetAndReload())},this.handleAccountUpdated=async oo=>{var ao;{const so=await this.cipher.decrypt(oo);(ao=this.listener)===null||ao===void 0||ao.accountUpdated(so)}},this.handleMetadataUpdated=async(oo,ao)=>{var so;{const co=await this.cipher.decrypt(ao);(so=this.listener)===null||so===void 0||so.metadataUpdated(oo,co)}},this.handleWalletUsernameUpdated=async oo=>{this.handleMetadataUpdated(constants_1$4.WALLET_USER_NAME_KEY,oo)},this.handleAppVersionUpdated=async oo=>{this.handleMetadataUpdated(constants_1$4.APP_VERSION_KEY,oo)},this.handleChainUpdated=async(oo,ao)=>{var so;{const co=await this.cipher.decrypt(oo),lo=await this.cipher.decrypt(ao);(so=this.listener)===null||so===void 0||so.chainUpdated(co,lo)}},this.session=eo,this.cipher=new WalletLinkCipher_1.WalletLinkCipher(eo.secret),this.listener=ro;const io=new WalletLinkWebSocket_1.WalletLinkWebSocket(`${to}/rpc`,no);io.setConnectionStateListener(async oo=>{let ao=!1;switch(oo){case WalletLinkWebSocket_1.ConnectionState.DISCONNECTED:if(!this.destroyed){const so=async()=>{await new Promise(co=>setTimeout(co,5e3)),this.destroyed||io.connect().catch(()=>{so()})};so()}break;case WalletLinkWebSocket_1.ConnectionState.CONNECTED:try{await this.authenticate(),this.sendIsLinked(),this.sendGetSessionConfig(),ao=!0}catch{}this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},HEARTBEAT_INTERVAL),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case WalletLinkWebSocket_1.ConnectionState.CONNECTING:break}this.connected!==ao&&(this.connected=ao)}),io.setIncomingDataListener(oo=>{var ao;switch(oo.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const so=oo.type==="IsLinkedOK"?oo.linked:void 0;this.linked=so||oo.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(oo.metadata);break}case"Event":{this.handleIncomingEvent(oo);break}}oo.id!==void 0&&((ao=this.requestResolutions.get(oo.id))===null||ao===void 0||ao(oo))}),this.ws=io,this.http=new WalletLinkHTTP_1.WalletLinkHTTP(to,eo.id,eo.key)}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}destroy(){this.destroyed=!0,this.ws.disconnect(),this.listener=void 0}get isDestroyed(){return this.destroyed}get connected(){return this._connected}set connected(eo){var to;this._connected=eo,eo&&((to=this.onceConnected)===null||to===void 0||to.call(this))}setOnceConnected(eo){return new Promise(to=>{this.connected?eo().then(to):this.onceConnected=()=>{eo().then(to),this.onceConnected=void 0}})}get linked(){return this._linked}set linked(eo){var to,ro;this._linked=eo,eo&&((to=this.onceLinked)===null||to===void 0||to.call(this)),(ro=this.listener)===null||ro===void 0||ro.linkedUpdated(eo)}setOnceLinked(eo){return new Promise(to=>{this.linked?eo().then(to):this.onceLinked=()=>{eo().then(to),this.onceLinked=void 0}})}async handleIncomingEvent(eo){var to;if(!(eo.type!=="Event"||eo.event!=="Web3Response")){const ro=await this.cipher.decrypt(eo.data),no=JSON.parse(ro);if(no.type!=="WEB3_RESPONSE")return;(to=this.listener)===null||to===void 0||to.handleWeb3ResponseMessage(no)}}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(eo=>setTimeout(eo,250));try{await this.fetchUnseenEventsAPI()}catch(eo){console.error("Unable to check for unseen events",eo)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(to=>this.handleIncomingEvent(to))}async setSessionMetadata(eo,to){const ro={type:"SetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,metadata:{[eo]:to}};return this.setOnceConnected(async()=>{const no=await this.makeRequest(ro);if(no.type==="Fail")throw new Error(no.error||"failed to set session metadata")})}async publishEvent(eo,to,ro=!1){const no=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},to),{origin:location.origin,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),io={type:"PublishEvent",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,event:eo,data:no,callWebhook:ro};return this.setOnceLinked(async()=>{const oo=await this.makeRequest(io);if(oo.type==="Fail")throw new Error(oo.error||"failed to publish event");return oo.eventId})}sendData(eo){this.ws.sendData(JSON.stringify(eo))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>HEARTBEAT_INTERVAL*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(eo,to=REQUEST_TIMEOUT){const ro=eo.id;this.sendData(eo);let no;return Promise.race([new Promise((io,oo)=>{no=window.setTimeout(()=>{oo(new Error(`request ${ro} timed out`))},to)}),new Promise(io=>{this.requestResolutions.set(ro,oo=>{clearTimeout(no),io(oo),this.requestResolutions.delete(ro)})})])}async authenticate(){const eo={type:"HostSession",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key},to=await this.makeRequest(eo);if(to.type==="Fail")throw new Error(to.error||"failed to authenticate")}sendIsLinked(){const eo={type:"IsLinked",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(eo)}sendGetSessionConfig(){const eo={type:"GetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(eo)}}WalletLinkConnection$1.WalletLinkConnection=WalletLinkConnection;var WalletLinkSession$1={};Object.defineProperty(WalletLinkSession$1,"__esModule",{value:!0});WalletLinkSession$1.WalletLinkSession=void 0;const sha_js_1=requireSha_js(),util_1$7=util$6,STORAGE_KEY_SESSION_ID="session:id",STORAGE_KEY_SESSION_SECRET="session:secret",STORAGE_KEY_SESSION_LINKED="session:linked";class WalletLinkSession{constructor(eo,to,ro,no){this._storage=eo,this._id=to||(0,util_1$7.randomBytesHex)(16),this._secret=ro||(0,util_1$7.randomBytesHex)(32),this._key=new sha_js_1.sha256().update(`${this._id}, ${this._secret} WalletLink`).digest("hex"),this._linked=!!no}static load(eo){const to=eo.getItem(STORAGE_KEY_SESSION_ID),ro=eo.getItem(STORAGE_KEY_SESSION_LINKED),no=eo.getItem(STORAGE_KEY_SESSION_SECRET);return to&&no?new WalletLinkSession(eo,to,no,ro==="1"):null}get id(){return this._id}get secret(){return this._secret}get key(){return this._key}get linked(){return this._linked}set linked(eo){this._linked=eo,this.persistLinked()}save(){return this._storage.setItem(STORAGE_KEY_SESSION_ID,this._id),this._storage.setItem(STORAGE_KEY_SESSION_SECRET,this._secret),this.persistLinked(),this}persistLinked(){this._storage.setItem(STORAGE_KEY_SESSION_LINKED,this._linked?"1":"0")}}WalletLinkSession$1.WalletLinkSession=WalletLinkSession;var util$1={};Object.defineProperty(util$1,"__esModule",{value:!0});util$1.isDarkMode=util$1.isMobileWeb=util$1.getLocation=util$1.createQrUrl=void 0;function createQrUrl(Xr,eo,to,ro,no,io){const oo=ro?"parent-id":"id",ao=new URLSearchParams({[oo]:Xr,secret:eo,server:to,v:no,chainId:io.toString()}).toString();return`${to}/#/link?${ao}`}util$1.createQrUrl=createQrUrl;function isInIFrame(){try{return window.frameElement!==null}catch{return!1}}function getLocation(){try{return isInIFrame()&&window.top?window.top.location:window.location}catch{return window.location}}util$1.getLocation=getLocation;function isMobileWeb(){var Xr;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((Xr=window==null?void 0:window.navigator)===null||Xr===void 0?void 0:Xr.userAgent)}util$1.isMobileWeb=isMobileWeb;function isDarkMode(){var Xr,eo;return(eo=(Xr=window==null?void 0:window.matchMedia)===null||Xr===void 0?void 0:Xr.call(window,"(prefers-color-scheme: dark)").matches)!==null&&eo!==void 0?eo:!1}util$1.isDarkMode=isDarkMode;var WalletLinkRelayUI$1={},cssReset={},cssResetCss={};Object.defineProperty(cssResetCss,"__esModule",{value:!0});cssResetCss.default='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';var __importDefault$4=commonjsGlobal&&commonjsGlobal.__importDefault||function(Xr){return Xr&&Xr.__esModule?Xr:{default:Xr}};Object.defineProperty(cssReset,"__esModule",{value:!0});cssReset.injectCssReset=void 0;const cssReset_css_1=__importDefault$4(cssResetCss);function injectCssReset(){const Xr=document.createElement("style");Xr.type="text/css",Xr.appendChild(document.createTextNode(cssReset_css_1.default)),document.documentElement.appendChild(Xr)}cssReset.injectCssReset=injectCssReset;var Snackbar={};function r$3(Xr){var eo,to,ro="";if(typeof Xr=="string"||typeof Xr=="number")ro+=Xr;else if(typeof Xr=="object")if(Array.isArray(Xr))for(eo=0;eo2&&(oo.children=arguments.length>3?n$1.call(arguments,2):to),typeof Xr=="function"&&Xr.defaultProps!=null)for(io in Xr.defaultProps)oo[io]===void 0&&(oo[io]=Xr.defaultProps[io]);return g$4(Xr,oo,ro,no,null)}function g$4(Xr,eo,to,ro,no){var io={type:Xr,props:eo,key:to,ref:ro,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:no??++u$3,__i:-1,__u:0};return no==null&&l$4.vnode!=null&&l$4.vnode(io),io}function m$2(){return{current:null}}function b$4(Xr){return Xr.children}function k$1(Xr,eo){this.props=Xr,this.context=eo}function x$3(Xr,eo){if(eo==null)return Xr.__?x$3(Xr.__,Xr.__i+1):null;for(var to;eoeo&&i$3.sort(f$5));M$2.__r=0}function P$3(Xr,eo,to,ro,no,io,oo,ao,so,co,lo){var fo,ho,go,yo,vo,wo=ro&&ro.__k||v$2,Eo=eo.length;for(to.__d=so,$$2(to,eo,wo),so=to.__d,fo=0;fo0?g$4(no.type,no.props,no.key,no.ref?no.ref:null,no.__v):no).__=Xr,no.__b=Xr.__b+1,io=null,(ao=no.__i=L$4(no,to,oo,lo))!==-1&&(lo--,(io=to[ao])&&(io.__u|=131072)),io==null||io.__v===null?(ao==-1&&fo--,typeof no.type!="function"&&(no.__u|=65536)):ao!==oo&&(ao==oo-1?fo--:ao==oo+1?fo++:(ao>oo?fo--:fo++,no.__u|=65536))):no=Xr.__k[ro]=null;if(lo)for(ro=0;ro(so!=null&&!(131072&so.__u)?1:0))for(;oo>=0||ao=0){if((so=eo[oo])&&!(131072&so.__u)&&no==so.key&&io===so.type)return oo;oo--}if(ao2&&(ao.children=arguments.length>3?n$1.call(arguments,2):to),g$4(Xr.type,ao,ro||Xr.key,no||Xr.ref,null)}function G$2(Xr,eo){var to={__c:eo="__cC"+a$3++,__:Xr,Consumer:function(ro,no){return ro.children(no)},Provider:function(ro){var no,io;return this.getChildContext||(no=new Set,(io={})[eo]=this,this.getChildContext=function(){return io},this.componentWillUnmount=function(){no=null},this.shouldComponentUpdate=function(oo){this.props.value!==oo.value&&no.forEach(function(ao){ao.__e=!0,S$3(ao)})},this.sub=function(oo){no.add(oo);var ao=oo.componentWillUnmount;oo.componentWillUnmount=function(){no&&no.delete(oo),ao&&ao.call(oo)}}),ro.children}};return to.Provider.__=to.Consumer.contextType=to}n$1=v$2.slice,l$4={__e:function(Xr,eo,to,ro){for(var no,io,oo;eo=eo.__;)if((no=eo.__c)&&!no.__)try{if((io=no.constructor)&&io.getDerivedStateFromError!=null&&(no.setState(io.getDerivedStateFromError(Xr)),oo=no.__d),no.componentDidCatch!=null&&(no.componentDidCatch(Xr,ro||{}),oo=no.__d),oo)return no.__E=no}catch(ao){Xr=ao}throw Xr}},u$3=0,t$3=function(Xr){return Xr!=null&&Xr.constructor==null},k$1.prototype.setState=function(Xr,eo){var to;to=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=d$5({},this.state),typeof Xr=="function"&&(Xr=Xr(d$5({},to),this.props)),Xr&&d$5(to,Xr),Xr!=null&&this.__v&&(eo&&this._sb.push(eo),S$3(this))},k$1.prototype.forceUpdate=function(Xr){this.__v&&(this.__e=!0,Xr&&this.__h.push(Xr),S$3(this))},k$1.prototype.render=b$4,i$3=[],r$2=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,f$5=function(Xr,eo){return Xr.__v.__b-eo.__v.__b},M$2.__r=0,e$2=0,c$2=F$4(!1),s$3=F$4(!0),a$3=0;const preact_module=Object.freeze(Object.defineProperty({__proto__:null,Component:k$1,Fragment:b$4,cloneElement:E$2,createContext:G$2,createElement:_$5,createRef:m$2,h:_$5,hydrate:D$2,get isValidElement(){return t$3},get options(){return l$4},render:B$3,toChildArray:H$2},Symbol.toStringTag,{value:"Module"})),require$$1=getAugmentedNamespace(preact_module);var t$2,r$1,u$2,i$2,o$2=0,f$4=[],c$1=l$4,e$1=c$1.__b,a$2=c$1.__r,v$1=c$1.diffed,l$3=c$1.__c,m$1=c$1.unmount,s$2=c$1.__;function d$4(Xr,eo){c$1.__h&&c$1.__h(r$1,Xr,o$2||eo),o$2=0;var to=r$1.__H||(r$1.__H={__:[],__h:[]});return Xr>=to.__.length&&to.__.push({}),to.__[Xr]}function h$3(Xr){return o$2=1,p$1(D$1,Xr)}function p$1(Xr,eo,to){var ro=d$4(t$2++,2);if(ro.t=Xr,!ro.__c&&(ro.__=[to?to(eo):D$1(void 0,eo),function(ao){var so=ro.__N?ro.__N[0]:ro.__[0],co=ro.t(so,ao);so!==co&&(ro.__N=[co,ro.__[1]],ro.__c.setState({}))}],ro.__c=r$1,!r$1.u)){var no=function(ao,so,co){if(!ro.__c.__H)return!0;var lo=ro.__c.__H.__.filter(function(ho){return!!ho.__c});if(lo.every(function(ho){return!ho.__N}))return!io||io.call(this,ao,so,co);var fo=!1;return lo.forEach(function(ho){if(ho.__N){var go=ho.__[0];ho.__=ho.__N,ho.__N=void 0,go!==ho.__[0]&&(fo=!0)}}),!(!fo&&ro.__c.props===ao)&&(!io||io.call(this,ao,so,co))};r$1.u=!0;var io=r$1.shouldComponentUpdate,oo=r$1.componentWillUpdate;r$1.componentWillUpdate=function(ao,so,co){if(this.__e){var lo=io;io=void 0,no(ao,so,co),io=lo}oo&&oo.call(this,ao,so,co)},r$1.shouldComponentUpdate=no}return ro.__N||ro.__}function y$5(Xr,eo){var to=d$4(t$2++,3);!c$1.__s&&C$4(to.__H,eo)&&(to.__=Xr,to.i=eo,r$1.__H.__h.push(to))}function _$4(Xr,eo){var to=d$4(t$2++,4);!c$1.__s&&C$4(to.__H,eo)&&(to.__=Xr,to.i=eo,r$1.__h.push(to))}function A$4(Xr){return o$2=5,T$5(function(){return{current:Xr}},[])}function F$3(Xr,eo,to){o$2=6,_$4(function(){return typeof Xr=="function"?(Xr(eo()),function(){return Xr(null)}):Xr?(Xr.current=eo(),function(){return Xr.current=null}):void 0},to==null?to:to.concat(Xr))}function T$5(Xr,eo){var to=d$4(t$2++,7);return C$4(to.__H,eo)&&(to.__=Xr(),to.__H=eo,to.__h=Xr),to.__}function q$3(Xr,eo){return o$2=8,T$5(function(){return Xr},eo)}function x$2(Xr){var eo=r$1.context[Xr.__c],to=d$4(t$2++,9);return to.c=Xr,eo?(to.__==null&&(to.__=!0,eo.sub(r$1)),eo.props.value):Xr.__}function P$2(Xr,eo){c$1.useDebugValue&&c$1.useDebugValue(eo?eo(Xr):Xr)}function b$3(Xr){var eo=d$4(t$2++,10),to=h$3();return eo.__=Xr,r$1.componentDidCatch||(r$1.componentDidCatch=function(ro,no){eo.__&&eo.__(ro,no),to[1](ro)}),[to[0],function(){to[1](void 0)}]}function g$3(){var Xr=d$4(t$2++,11);if(!Xr.__){for(var eo=r$1.__v;eo!==null&&!eo.__m&&eo.__!==null;)eo=eo.__;var to=eo.__m||(eo.__m=[0,0]);Xr.__="P"+to[0]+"-"+to[1]++}return Xr.__}function j$4(){for(var Xr;Xr=f$4.shift();)if(Xr.__P&&Xr.__H)try{Xr.__H.__h.forEach(z$3),Xr.__H.__h.forEach(B$2),Xr.__H.__h=[]}catch(eo){Xr.__H.__h=[],c$1.__e(eo,Xr.__v)}}c$1.__b=function(Xr){r$1=null,e$1&&e$1(Xr)},c$1.__=function(Xr,eo){Xr&&eo.__k&&eo.__k.__m&&(Xr.__m=eo.__k.__m),s$2&&s$2(Xr,eo)},c$1.__r=function(Xr){a$2&&a$2(Xr),t$2=0;var eo=(r$1=Xr.__c).__H;eo&&(u$2===r$1?(eo.__h=[],r$1.__h=[],eo.__.forEach(function(to){to.__N&&(to.__=to.__N),to.i=to.__N=void 0})):(eo.__h.forEach(z$3),eo.__h.forEach(B$2),eo.__h=[],t$2=0)),u$2=r$1},c$1.diffed=function(Xr){v$1&&v$1(Xr);var eo=Xr.__c;eo&&eo.__H&&(eo.__H.__h.length&&(f$4.push(eo)!==1&&i$2===c$1.requestAnimationFrame||((i$2=c$1.requestAnimationFrame)||w$2)(j$4)),eo.__H.__.forEach(function(to){to.i&&(to.__H=to.i),to.i=void 0})),u$2=r$1=null},c$1.__c=function(Xr,eo){eo.some(function(to){try{to.__h.forEach(z$3),to.__h=to.__h.filter(function(ro){return!ro.__||B$2(ro)})}catch(ro){eo.some(function(no){no.__h&&(no.__h=[])}),eo=[],c$1.__e(ro,to.__v)}}),l$3&&l$3(Xr,eo)},c$1.unmount=function(Xr){m$1&&m$1(Xr);var eo,to=Xr.__c;to&&to.__H&&(to.__H.__.forEach(function(ro){try{z$3(ro)}catch(no){eo=no}}),to.__H=void 0,eo&&c$1.__e(eo,to.__v))};var k=typeof requestAnimationFrame=="function";function w$2(Xr){var eo,to=function(){clearTimeout(ro),k&&cancelAnimationFrame(eo),setTimeout(Xr)},ro=setTimeout(to,100);k&&(eo=requestAnimationFrame(to))}function z$3(Xr){var eo=r$1,to=Xr.__c;typeof to=="function"&&(Xr.__c=void 0,to()),r$1=eo}function B$2(Xr){var eo=r$1;Xr.__c=Xr.__(),r$1=eo}function C$4(Xr,eo){return!Xr||Xr.length!==eo.length||eo.some(function(to,ro){return to!==Xr[ro]})}function D$1(Xr,eo){return typeof eo=="function"?eo(Xr):eo}const hooks_module=Object.freeze(Object.defineProperty({__proto__:null,useCallback:q$3,useContext:x$2,useDebugValue:P$2,useEffect:y$5,useErrorBoundary:b$3,useId:g$3,useImperativeHandle:F$3,useLayoutEffect:_$4,useMemo:T$5,useReducer:p$1,useRef:A$4,useState:h$3},Symbol.toStringTag,{value:"Module"})),require$$2$1=getAugmentedNamespace(hooks_module);var SnackbarCss={};Object.defineProperty(SnackbarCss,"__esModule",{value:!0});SnackbarCss.default=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}";(function(Xr){var eo=commonjsGlobal&&commonjsGlobal.__importDefault||function(ho){return ho&&ho.__esModule?ho:{default:ho}};Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.SnackbarInstance=Xr.SnackbarContainer=Xr.Snackbar=void 0;const to=eo(require$$0$1),ro=require$$1,no=require$$2$1,io=util$1,oo=eo(SnackbarCss),ao="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",so="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class co{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=(0,io.isDarkMode)()}attach(go){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",go.appendChild(this.root),this.render()}presentItem(go){const yo=this.nextItemKey++;return this.items.set(yo,go),this.render(),()=>{this.items.delete(yo),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,ro.render)((0,ro.h)("div",null,(0,ro.h)(Xr.SnackbarContainer,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([go,yo])=>(0,ro.h)(Xr.SnackbarInstance,Object.assign({},yo,{key:go}))))),this.root)}}Xr.Snackbar=co;const lo=ho=>(0,ro.h)("div",{class:(0,to.default)("-cbwsdk-snackbar-container")},(0,ro.h)("style",null,oo.default),(0,ro.h)("div",{class:"-cbwsdk-snackbar"},ho.children));Xr.SnackbarContainer=lo;const fo=({autoExpand:ho,message:go,menuItems:yo})=>{const[vo,wo]=(0,no.useState)(!0),[Eo,ko]=(0,no.useState)(ho??!1);(0,no.useEffect)(()=>{const Po=[window.setTimeout(()=>{wo(!1)},1),window.setTimeout(()=>{ko(!0)},1e4)];return()=>{Po.forEach(window.clearTimeout)}});const Ao=()=>{ko(!Eo)};return(0,ro.h)("div",{class:(0,to.default)("-cbwsdk-snackbar-instance",vo&&"-cbwsdk-snackbar-instance-hidden",Eo&&"-cbwsdk-snackbar-instance-expanded")},(0,ro.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:Ao},(0,ro.h)("img",{src:ao,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,ro.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},go),(0,ro.h)("div",{class:"-gear-container"},!Eo&&(0,ro.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,ro.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,ro.h)("img",{src:so,class:"-gear-icon",title:"Expand"}))),yo&&yo.length>0&&(0,ro.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},yo.map((Po,jo)=>(0,ro.h)("div",{class:(0,to.default)("-cbwsdk-snackbar-instance-menu-item",Po.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:Po.onClick,key:jo},(0,ro.h)("svg",{width:Po.svgWidth,height:Po.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,ro.h)("path",{"fill-rule":Po.defaultFillRule,"clip-rule":Po.defaultClipRule,d:Po.path,fill:"#AAAAAA"})),(0,ro.h)("span",{class:(0,to.default)("-cbwsdk-snackbar-instance-menu-item-info",Po.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},Po.info)))))};Xr.SnackbarInstance=fo})(Snackbar);Object.defineProperty(WalletLinkRelayUI$1,"__esModule",{value:!0});WalletLinkRelayUI$1.WalletLinkRelayUI=void 0;const cssReset_1$1=cssReset,Snackbar_1$1=Snackbar;class WalletLinkRelayUI{constructor(){this.attached=!1,this.snackbar=new Snackbar_1$1.Snackbar}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const eo=document.documentElement,to=document.createElement("div");to.className="-cbwsdk-css-reset",eo.appendChild(to),this.snackbar.attach(to),this.attached=!0,(0,cssReset_1$1.injectCssReset)()}showConnecting(eo){let to;return eo.isUnlinkedErrorState?to={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:eo.onResetConnection}]}:to={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:eo.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:eo.onResetConnection}]},this.snackbar.presentItem(to)}}WalletLinkRelayUI$1.WalletLinkRelayUI=WalletLinkRelayUI;var WLMobileRelayUI$1={},RedirectDialog$1={},RedirectDialogCss={};Object.defineProperty(RedirectDialogCss,"__esModule",{value:!0});RedirectDialogCss.default=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";var __importDefault$3=commonjsGlobal&&commonjsGlobal.__importDefault||function(Xr){return Xr&&Xr.__esModule?Xr:{default:Xr}};Object.defineProperty(RedirectDialog$1,"__esModule",{value:!0});RedirectDialog$1.RedirectDialog=void 0;const clsx_1=__importDefault$3(require$$0$1),preact_1=require$$1,cssReset_1=cssReset,Snackbar_1=Snackbar,util_1$6=util$1,RedirectDialog_css_1=__importDefault$3(RedirectDialogCss);class RedirectDialog{constructor(){this.root=null,this.darkMode=(0,util_1$6.isDarkMode)()}attach(){const eo=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",eo.appendChild(this.root),(0,cssReset_1.injectCssReset)()}present(eo){this.render(eo)}clear(){this.render(null)}render(eo){this.root&&((0,preact_1.render)(null,this.root),eo&&(0,preact_1.render)((0,preact_1.h)(RedirectDialogContent,Object.assign({},eo,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}RedirectDialog$1.RedirectDialog=RedirectDialog;const RedirectDialogContent=({title:Xr,buttonText:eo,darkMode:to,onButtonClick:ro,onDismiss:no})=>{const io=to?"dark":"light";return(0,preact_1.h)(Snackbar_1.SnackbarContainer,{darkMode:to},(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,preact_1.h)("style",null,RedirectDialog_css_1.default),(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:no}),(0,preact_1.h)("div",{class:(0,clsx_1.default)("-cbwsdk-redirect-dialog-box",io)},(0,preact_1.h)("p",null,Xr),(0,preact_1.h)("button",{onClick:ro},eo))))};var constants$3={};Object.defineProperty(constants$3,"__esModule",{value:!0});constants$3.CBW_MOBILE_DEEPLINK_URL=constants$3.WALLETLINK_URL=constants$3.CB_KEYS_URL=void 0;constants$3.CB_KEYS_URL="https://keys.coinbase.com/connect";constants$3.WALLETLINK_URL="https://www.walletlink.org";constants$3.CBW_MOBILE_DEEPLINK_URL="https://go.cb-w.com/walletlink";Object.defineProperty(WLMobileRelayUI$1,"__esModule",{value:!0});WLMobileRelayUI$1.WLMobileRelayUI=void 0;const RedirectDialog_1=RedirectDialog$1,util_1$5=util$1,constants_1$3=constants$3;class WLMobileRelayUI{constructor(){this.attached=!1,this.redirectDialog=new RedirectDialog_1.RedirectDialog}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(eo){const to=new URL(constants_1$3.CBW_MOBILE_DEEPLINK_URL);to.searchParams.append("redirect_url",(0,util_1$5.getLocation)().href),eo&&to.searchParams.append("wl_url",eo);const ro=document.createElement("a");ro.target="cbw-opener",ro.href=to.href,ro.rel="noreferrer noopener",ro.click()}openCoinbaseWalletDeeplink(eo){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(eo)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(eo)},99)}showConnecting(eo){return()=>{this.redirectDialog.clear()}}}WLMobileRelayUI$1.WLMobileRelayUI=WLMobileRelayUI;Object.defineProperty(WalletLinkRelay$1,"__esModule",{value:!0});WalletLinkRelay$1.WalletLinkRelay=void 0;const WalletLinkConnection_1=WalletLinkConnection$1,constants_1$2=constants$4,RelayEventManager_1$1=RelayEventManager$1,WalletLinkSession_1=WalletLinkSession$1,Web3Response_1$1=Web3Response,util_1$4=util$1,WalletLinkRelayUI_1=WalletLinkRelayUI$1,WLMobileRelayUI_1=WLMobileRelayUI$1,error_1$6=error$2,util_2$1=util$6,ScopedLocalStorage_1$4=ScopedLocalStorage$1;class WalletLinkRelay{constructor(eo){this.accountsCallback=null,this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.chainCallback=null,this.dappDefaultChain=1,this.isMobileWeb=(0,util_1$4.isMobileWeb)(),this.appName="",this.appLogoUrl=null,this.linkedUpdated=io=>{this.isLinked=io;const oo=this.storage.getItem(constants_1$2.LOCAL_STORAGE_ADDRESSES_KEY);if(io&&(this._session.linked=io),this.isUnlinkedErrorState=!1,oo){const ao=oo.split(" "),so=this.storage.getItem("IsStandaloneSigning")==="true";ao[0]!==""&&!io&&this._session.linked&&!so&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(io,oo)=>{this.storage.setItem(io,oo)},this.chainUpdated=(io,oo)=>{this.chainCallbackParams.chainId===io&&this.chainCallbackParams.jsonRpcUrl===oo||(this.chainCallbackParams={chainId:io,jsonRpcUrl:oo},this.chainCallback&&this.chainCallback(io,oo))},this.accountUpdated=io=>{this.accountsCallback&&this.accountsCallback([io]),WalletLinkRelay.accountRequestCallbackIds.size>0&&(Array.from(WalletLinkRelay.accountRequestCallbackIds.values()).forEach(oo=>{const ao={type:"WEB3_RESPONSE",id:oo,response:{method:"requestEthereumAccounts",result:[io]}};this.invokeCallback(Object.assign(Object.assign({},ao),{id:oo}))}),WalletLinkRelay.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=eo.linkAPIUrl,this.storage=eo.storage;const{session:to,ui:ro,connection:no}=this.subscribe();this._session=to,this.connection=no,this.relayEventManager=new RelayEventManager_1$1.RelayEventManager,this.ui=ro}subscribe(){const eo=WalletLinkSession_1.WalletLinkSession.load(this.storage)||new WalletLinkSession_1.WalletLinkSession(this.storage).save(),{linkAPIUrl:to}=this,ro=new WalletLinkConnection_1.WalletLinkConnection({session:eo,linkAPIUrl:to,listener:this}),no=this.isMobileWeb?new WLMobileRelayUI_1.WLMobileRelayUI:new WalletLinkRelayUI_1.WalletLinkRelayUI;return ro.connect(),{session:eo,ui:no,connection:ro}}attachUI(){this.ui.attach()}resetAndReload(){Promise.race([this.connection.setSessionMetadata("__destroyed","1"),new Promise(eo=>setTimeout(()=>eo(null),1e3))]).then(()=>{this.connection.destroy();const eo=WalletLinkSession_1.WalletLinkSession.load(this.storage);(eo==null?void 0:eo.id)===this._session.id&&ScopedLocalStorage_1$4.ScopedLocalStorage.clearAll(),document.location.reload()}).catch(eo=>{})}setAppInfo(eo,to){this.appName=eo,this.appLogoUrl=to}getStorageItem(eo){return this.storage.getItem(eo)}setStorageItem(eo,to){this.storage.setItem(eo,to)}signEthereumMessage(eo,to,ro,no){return this.sendRequest({method:"signEthereumMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(eo,!0),address:to,addPrefix:ro,typedDataJson:no||null}})}ethereumAddressFromSignedMessage(eo,to,ro){return this.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(eo,!0),signature:(0,util_2$1.hexStringFromBuffer)(to,!0),addPrefix:ro}})}signEthereumTransaction(eo){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:eo.fromAddress,toAddress:eo.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(eo.weiValue),data:(0,util_2$1.hexStringFromBuffer)(eo.data,!0),nonce:eo.nonce,gasPriceInWei:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,maxFeePerGas:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,maxPriorityFeePerGas:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,gasLimit:eo.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(eo.gasLimit):null,chainId:eo.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(eo){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:eo.fromAddress,toAddress:eo.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(eo.weiValue),data:(0,util_2$1.hexStringFromBuffer)(eo.data,!0),nonce:eo.nonce,gasPriceInWei:eo.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(eo.gasPriceInWei):null,maxFeePerGas:eo.maxFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(eo.maxFeePerGas):null,maxPriorityFeePerGas:eo.maxPriorityFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(eo.maxPriorityFeePerGas):null,gasLimit:eo.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(eo.gasLimit):null,chainId:eo.chainId,shouldSubmit:!0}})}submitEthereumTransaction(eo,to){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:(0,util_2$1.hexStringFromBuffer)(eo,!0),chainId:to}})}scanQRCode(eo){return this.sendRequest({method:"scanQRCode",params:{regExp:eo}})}getWalletLinkSession(){return this._session}genericRequest(eo,to){return this.sendRequest({method:"generic",params:{action:to,data:eo}})}sendGenericMessage(eo){return this.sendRequest(eo)}sendRequest(eo){let to=null;const ro=(0,util_2$1.randomBytesHex)(8),no=io=>{this.publishWeb3RequestCanceledEvent(ro),this.handleErrorResponse(ro,eo.method,io),to==null||to()};return new Promise((io,oo)=>{to=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:no,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(ro,ao=>{if(to==null||to(),(0,Web3Response_1$1.isErrorResponse)(ao))return oo(new Error(ao.errorMessage));io(ao)}),this.publishWeb3RequestEvent(ro,eo)})}setAccountsCallback(eo){this.accountsCallback=eo}setChainCallback(eo){this.chainCallback=eo}setDappDefaultChainCallback(eo){this.dappDefaultChain=eo}publishWeb3RequestEvent(eo,to){const ro={type:"WEB3_REQUEST",id:eo,request:to};this.publishEvent("Web3Request",ro,!0).then(no=>{}).catch(no=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:ro.id,response:{method:to.method,errorMessage:no.message}})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(to.method)}openCoinbaseWalletDeeplink(eo){if(this.ui instanceof WLMobileRelayUI_1.WLMobileRelayUI)switch(eo){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(eo){const to={type:"WEB3_REQUEST_CANCELED",id:eo};this.publishEvent("Web3RequestCanceled",to,!1).then()}publishEvent(eo,to,ro){return this.connection.publishEvent(eo,to,ro)}handleWeb3ResponseMessage(eo){const{response:to}=eo;if(to.method==="requestEthereumAccounts"){WalletLinkRelay.accountRequestCallbackIds.forEach(ro=>this.invokeCallback(Object.assign(Object.assign({},eo),{id:ro}))),WalletLinkRelay.accountRequestCallbackIds.clear();return}this.invokeCallback(eo)}handleErrorResponse(eo,to,ro){var no;const io=(no=ro==null?void 0:ro.message)!==null&&no!==void 0?no:"Unspecified error message.";this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:eo,response:{method:to,errorMessage:io}})}invokeCallback(eo){const to=this.relayEventManager.callbacks.get(eo.id);to&&(to(eo.response),this.relayEventManager.callbacks.delete(eo.id))}requestEthereumAccounts(){const eo={method:"requestEthereumAccounts",params:{appName:this.appName,appLogoUrl:this.appLogoUrl||null}},to=(0,util_2$1.randomBytesHex)(8);return new Promise((ro,no)=>{this.relayEventManager.callbacks.set(to,io=>{if((0,Web3Response_1$1.isErrorResponse)(io))return no(new Error(io.errorMessage));ro(io)}),WalletLinkRelay.accountRequestCallbackIds.add(to),this.publishWeb3RequestEvent(to,eo)})}watchAsset(eo,to,ro,no,io,oo){const ao={method:"watchAsset",params:{type:eo,options:{address:to,symbol:ro,decimals:no,image:io},chainId:oo}};let so=null;const co=(0,util_2$1.randomBytesHex)(8),lo=fo=>{this.publishWeb3RequestCanceledEvent(co),this.handleErrorResponse(co,ao.method,fo),so==null||so()};return so=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:lo,onResetConnection:this.resetAndReload}),new Promise((fo,ho)=>{this.relayEventManager.callbacks.set(co,go=>{if(so==null||so(),(0,Web3Response_1$1.isErrorResponse)(go))return ho(new Error(go.errorMessage));fo(go)}),this.publishWeb3RequestEvent(co,ao)})}addEthereumChain(eo,to,ro,no,io,oo){const ao={method:"addEthereumChain",params:{chainId:eo,rpcUrls:to,blockExplorerUrls:no,chainName:io,iconUrls:ro,nativeCurrency:oo}};let so=null;const co=(0,util_2$1.randomBytesHex)(8),lo=fo=>{this.publishWeb3RequestCanceledEvent(co),this.handleErrorResponse(co,ao.method,fo),so==null||so()};return so=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:lo,onResetConnection:this.resetAndReload}),new Promise((fo,ho)=>{this.relayEventManager.callbacks.set(co,go=>{if(so==null||so(),(0,Web3Response_1$1.isErrorResponse)(go))return ho(new Error(go.errorMessage));fo(go)}),this.publishWeb3RequestEvent(co,ao)})}switchEthereumChain(eo,to){const ro={method:"switchEthereumChain",params:Object.assign({chainId:eo},{address:to})},no=(0,util_2$1.randomBytesHex)(8);return new Promise((io,oo)=>{this.relayEventManager.callbacks.set(no,ao=>{if((0,Web3Response_1$1.isErrorResponse)(ao)&&ao.errorCode)return oo(error_1$6.standardErrors.provider.custom({code:ao.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if((0,Web3Response_1$1.isErrorResponse)(ao))return oo(new Error(ao.errorMessage));io(ao)}),this.publishWeb3RequestEvent(no,ro)})}}WalletLinkRelay$1.WalletLinkRelay=WalletLinkRelay;WalletLinkRelay.accountRequestCallbackIds=new Set;var __importDefault$2=commonjsGlobal&&commonjsGlobal.__importDefault||function(Xr){return Xr&&Xr.__esModule?Xr:{default:Xr}};Object.defineProperty(WalletLinkSigner$1,"__esModule",{value:!0});WalletLinkSigner$1.WalletLinkSigner=void 0;const eth_eip712_util_1=__importDefault$2(ethEip712Util),constants_1$1=constants$4,RelayEventManager_1=RelayEventManager$1,Web3Response_1=Web3Response,WalletLinkRelay_1=WalletLinkRelay$1,constants_2=constants$3,error_1$5=error$2,util_1$3=util$6,ScopedLocalStorage_1$3=ScopedLocalStorage$1,DEFAULT_CHAIN_ID_KEY="DefaultChainId",DEFAULT_JSON_RPC_URL="DefaultJsonRpcUrl";class WalletLinkSigner{constructor(eo){var to,ro;this._relay=null,this._addresses=[],this.hasMadeFirstChainChangedEmission=!1;const{appName:no,appLogoUrl:io}=eo.metadata;this._appName=no,this._appLogoUrl=io,this._storage=new ScopedLocalStorage_1$3.ScopedLocalStorage("walletlink",constants_2.WALLETLINK_URL),this.updateListener=eo.updateListener,this._relayEventManager=new RelayEventManager_1.RelayEventManager,this._jsonRpcUrlFromOpts="";const oo=this._storage.getItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY);if(oo){const so=oo.split(" ");so[0]!==""&&(this._addresses=so.map(co=>(0,util_1$3.ensureAddressString)(co)),(to=this.updateListener)===null||to===void 0||to.onAccountsUpdate({accounts:this._addresses,source:"storage"}))}this._storage.getItem(DEFAULT_CHAIN_ID_KEY)&&((ro=this.updateListener)===null||ro===void 0||ro.onChainUpdate({chain:{id:this.getChainId(),rpcUrl:this.jsonRpcUrl},source:"storage"}),this.hasMadeFirstChainChangedEmission=!0),this.initializeRelay()}getSession(){const eo=this.initializeRelay(),{id:to,secret:ro}=eo.getWalletLinkSession();return{id:to,secret:ro}}async handshake(){return await this.request({method:"eth_requestAccounts"})}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var eo;return(eo=this._storage.getItem(DEFAULT_JSON_RPC_URL))!==null&&eo!==void 0?eo:this._jsonRpcUrlFromOpts}set jsonRpcUrl(eo){this._storage.setItem(DEFAULT_JSON_RPC_URL,eo)}updateProviderInfo(eo,to){var ro;this.jsonRpcUrl=eo;const no=this.getChainId();this._storage.setItem(DEFAULT_CHAIN_ID_KEY,to.toString(10)),((0,util_1$3.ensureIntNumber)(to)!==no||!this.hasMadeFirstChainChangedEmission)&&((ro=this.updateListener)===null||ro===void 0||ro.onChainUpdate({chain:{id:to,rpcUrl:eo},source:"wallet"}),this.hasMadeFirstChainChangedEmission=!0)}async watchAsset(eo,to,ro,no,io,oo){const so=await this.initializeRelay().watchAsset(eo,to,ro,no,io,oo==null?void 0:oo.toString());return(0,Web3Response_1.isErrorResponse)(so)?!1:!!so.result}async addEthereumChain(eo,to,ro,no,io,oo){var ao,so;if((0,util_1$3.ensureIntNumber)(eo)===this.getChainId())return!1;const co=this.initializeRelay();this._isAuthorized()||await co.requestEthereumAccounts();const lo=await co.addEthereumChain(eo.toString(),to,io,ro,no,oo);return(0,Web3Response_1.isErrorResponse)(lo)?!1:(((ao=lo.result)===null||ao===void 0?void 0:ao.isApproved)===!0&&this.updateProviderInfo(to[0],eo),((so=lo.result)===null||so===void 0?void 0:so.isApproved)===!0)}async switchEthereumChain(eo){const ro=await this.initializeRelay().switchEthereumChain(eo.toString(10),this.selectedAddress||void 0);if((0,Web3Response_1.isErrorResponse)(ro)){if(!ro.errorCode)return;throw ro.errorCode===error_1$5.standardErrorCodes.provider.unsupportedChain?error_1$5.standardErrors.provider.unsupportedChain():error_1$5.standardErrors.provider.custom({message:ro.errorMessage,code:ro.errorCode})}const no=ro.result;no.isApproved&&no.rpcUrl.length>0&&this.updateProviderInfo(no.rpcUrl,eo)}async disconnect(){this._relay&&this._relay.resetAndReload(),this._storage.clear()}async request(eo){try{return this._request(eo).catch(to=>{throw to})}catch(to){return Promise.reject(to)}}async _request(eo){if(!eo||typeof eo!="object"||Array.isArray(eo))throw error_1$5.standardErrors.rpc.invalidRequest({message:"Expected a single, non-array, object argument.",data:eo});const{method:to,params:ro}=eo;if(typeof to!="string"||to.length===0)throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.method' must be a non-empty string.",data:eo});if(ro!==void 0&&!Array.isArray(ro)&&(typeof ro!="object"||ro===null))throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.params' must be an object or array if provided.",data:eo});const no=ro===void 0?[]:ro,io=this._relayEventManager.makeRequestId();return(await this._sendRequestAsync({method:to,params:no,jsonrpc:"2.0",id:io})).result}_setAddresses(eo,to){var ro;if(!Array.isArray(eo))throw new Error("addresses is not an array");const no=eo.map(io=>(0,util_1$3.ensureAddressString)(io));JSON.stringify(no)!==JSON.stringify(this._addresses)&&(this._addresses=no,(ro=this.updateListener)===null||ro===void 0||ro.onAccountsUpdate({accounts:no,source:"wallet"}),this._storage.setItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY,no.join(" ")))}_sendRequestAsync(eo){return new Promise((to,ro)=>{try{const no=this._handleSynchronousMethods(eo);if(no!==void 0)return to({jsonrpc:"2.0",id:eo.id,result:no})}catch(no){return ro(no)}this._handleAsynchronousMethods(eo).then(no=>no&&to(Object.assign(Object.assign({},no),{id:eo.id}))).catch(no=>ro(no))})}_handleSynchronousMethods(eo){const{method:to}=eo;switch(to){case"eth_accounts":return this._eth_accounts();case"eth_coinbase":return this._eth_coinbase();case"net_version":return this._net_version();case"eth_chainId":return this._eth_chainId();default:return}}async _handleAsynchronousMethods(eo){const{method:to}=eo,ro=eo.params||[];switch(to){case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_sign":return this._eth_sign(ro);case"eth_ecRecover":return this._eth_ecRecover(ro);case"personal_sign":return this._personal_sign(ro);case"personal_ecRecover":return this._personal_ecRecover(ro);case"eth_signTransaction":return this._eth_signTransaction(ro);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(ro);case"eth_sendTransaction":return this._eth_sendTransaction(ro);case"eth_signTypedData_v1":return this._eth_signTypedData_v1(ro);case"eth_signTypedData_v2":return this._throwUnsupportedMethodError();case"eth_signTypedData_v3":return this._eth_signTypedData_v3(ro);case"eth_signTypedData_v4":case"eth_signTypedData":return this._eth_signTypedData_v4(ro);case"wallet_addEthereumChain":return this._wallet_addEthereumChain(ro);case"wallet_switchEthereumChain":return this._wallet_switchEthereumChain(ro);case"wallet_watchAsset":return this._wallet_watchAsset(ro);default:return this._throwUnsupportedMethodError()}}_isKnownAddress(eo){try{const to=(0,util_1$3.ensureAddressString)(eo);return this._addresses.map(no=>(0,util_1$3.ensureAddressString)(no)).includes(to)}catch{}return!1}_ensureKnownAddress(eo){if(!this._isKnownAddress(eo))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(eo){const to=eo.from?(0,util_1$3.ensureAddressString)(eo.from):this.selectedAddress;if(!to)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(to);const ro=eo.to?(0,util_1$3.ensureAddressString)(eo.to):null,no=eo.value!=null?(0,util_1$3.ensureBigInt)(eo.value):BigInt(0),io=eo.data?(0,util_1$3.ensureBuffer)(eo.data):Buffer$3.alloc(0),oo=eo.nonce!=null?(0,util_1$3.ensureIntNumber)(eo.nonce):null,ao=eo.gasPrice!=null?(0,util_1$3.ensureBigInt)(eo.gasPrice):null,so=eo.maxFeePerGas!=null?(0,util_1$3.ensureBigInt)(eo.maxFeePerGas):null,co=eo.maxPriorityFeePerGas!=null?(0,util_1$3.ensureBigInt)(eo.maxPriorityFeePerGas):null,lo=eo.gas!=null?(0,util_1$3.ensureBigInt)(eo.gas):null,fo=eo.chainId?(0,util_1$3.ensureIntNumber)(eo.chainId):this.getChainId();return{fromAddress:to,toAddress:ro,weiValue:no,data:io,nonce:oo,gasPriceInWei:ao,maxFeePerGas:so,maxPriorityFeePerGas:co,gasLimit:lo,chainId:fo}}_isAuthorized(){return this._addresses.length>0}_requireAuthorization(){if(!this._isAuthorized())throw error_1$5.standardErrors.provider.unauthorized({})}_throwUnsupportedMethodError(){throw error_1$5.standardErrors.provider.unsupportedMethod({})}async _signEthereumMessage(eo,to,ro,no){this._ensureKnownAddress(to);try{const oo=await this.initializeRelay().signEthereumMessage(eo,to,ro,no);if((0,Web3Response_1.isErrorResponse)(oo))throw new Error(oo.errorMessage);return{jsonrpc:"2.0",id:0,result:oo.result}}catch(io){throw typeof io.message=="string"&&io.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied message signature"):io}}async _ethereumAddressFromSignedMessage(eo,to,ro){const io=await this.initializeRelay().ethereumAddressFromSignedMessage(eo,to,ro);if((0,Web3Response_1.isErrorResponse)(io))throw new Error(io.errorMessage);return{jsonrpc:"2.0",id:0,result:io.result}}_eth_accounts(){return[...this._addresses]}_eth_coinbase(){return this.selectedAddress||null}_net_version(){return this.getChainId().toString(10)}_eth_chainId(){return(0,util_1$3.hexStringFromIntNumber)(this.getChainId())}getChainId(){const eo=this._storage.getItem(DEFAULT_CHAIN_ID_KEY);if(!eo)return(0,util_1$3.ensureIntNumber)(1);const to=parseInt(eo,10);return(0,util_1$3.ensureIntNumber)(to)}async _eth_requestAccounts(){if(this._isAuthorized())return Promise.resolve({jsonrpc:"2.0",id:0,result:this._addresses});let eo;try{if(eo=await this.initializeRelay().requestEthereumAccounts(),(0,Web3Response_1.isErrorResponse)(eo))throw new Error(eo.errorMessage)}catch(to){throw typeof to.message=="string"&&to.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied account authorization"):to}if(!eo.result)throw new Error("accounts received is empty");return this._setAddresses(eo.result),{jsonrpc:"2.0",id:0,result:this._addresses}}_eth_sign(eo){this._requireAuthorization();const to=(0,util_1$3.ensureAddressString)(eo[0]),ro=(0,util_1$3.ensureBuffer)(eo[1]);return this._signEthereumMessage(ro,to,!1)}_eth_ecRecover(eo){const to=(0,util_1$3.ensureBuffer)(eo[0]),ro=(0,util_1$3.ensureBuffer)(eo[1]);return this._ethereumAddressFromSignedMessage(to,ro,!1)}_personal_sign(eo){this._requireAuthorization();const to=(0,util_1$3.ensureBuffer)(eo[0]),ro=(0,util_1$3.ensureAddressString)(eo[1]);return this._signEthereumMessage(to,ro,!0)}_personal_ecRecover(eo){const to=(0,util_1$3.ensureBuffer)(eo[0]),ro=(0,util_1$3.ensureBuffer)(eo[1]);return this._ethereumAddressFromSignedMessage(to,ro,!0)}async _eth_signTransaction(eo){this._requireAuthorization();const to=this._prepareTransactionParams(eo[0]||{});try{const no=await this.initializeRelay().signEthereumTransaction(to);if((0,Web3Response_1.isErrorResponse)(no))throw new Error(no.errorMessage);return{jsonrpc:"2.0",id:0,result:no.result}}catch(ro){throw typeof ro.message=="string"&&ro.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):ro}}async _eth_sendRawTransaction(eo){const to=(0,util_1$3.ensureBuffer)(eo[0]),no=await this.initializeRelay().submitEthereumTransaction(to,this.getChainId());if((0,Web3Response_1.isErrorResponse)(no))throw new Error(no.errorMessage);return{jsonrpc:"2.0",id:0,result:no.result}}async _eth_sendTransaction(eo){this._requireAuthorization();const to=this._prepareTransactionParams(eo[0]||{});try{const no=await this.initializeRelay().signAndSubmitEthereumTransaction(to);if((0,Web3Response_1.isErrorResponse)(no))throw new Error(no.errorMessage);return{jsonrpc:"2.0",id:0,result:no.result}}catch(ro){throw typeof ro.message=="string"&&ro.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):ro}}async _eth_signTypedData_v1(eo){this._requireAuthorization();const to=(0,util_1$3.ensureParsedJSONObject)(eo[0]),ro=(0,util_1$3.ensureAddressString)(eo[1]);this._ensureKnownAddress(ro);const no=eth_eip712_util_1.default.hashForSignTypedDataLegacy({data:to}),io=JSON.stringify(to,null,2);return this._signEthereumMessage(no,ro,!1,io)}async _eth_signTypedData_v3(eo){this._requireAuthorization();const to=(0,util_1$3.ensureAddressString)(eo[0]),ro=(0,util_1$3.ensureParsedJSONObject)(eo[1]);this._ensureKnownAddress(to);const no=eth_eip712_util_1.default.hashForSignTypedData_v3({data:ro}),io=JSON.stringify(ro,null,2);return this._signEthereumMessage(no,to,!1,io)}async _eth_signTypedData_v4(eo){this._requireAuthorization();const to=(0,util_1$3.ensureAddressString)(eo[0]),ro=(0,util_1$3.ensureParsedJSONObject)(eo[1]);this._ensureKnownAddress(to);const no=eth_eip712_util_1.default.hashForSignTypedData_v4({data:ro}),io=JSON.stringify(ro,null,2);return this._signEthereumMessage(no,to,!1,io)}async _wallet_addEthereumChain(eo){var to,ro,no,io;const oo=eo[0];if(((to=oo.rpcUrls)===null||to===void 0?void 0:to.length)===0)return{jsonrpc:"2.0",id:0,error:{code:2,message:"please pass in at least 1 rpcUrl"}};if(!oo.chainName||oo.chainName.trim()==="")throw error_1$5.standardErrors.rpc.invalidParams("chainName is a required field");if(!oo.nativeCurrency)throw error_1$5.standardErrors.rpc.invalidParams("nativeCurrency is a required field");const ao=parseInt(oo.chainId,16);return await this.addEthereumChain(ao,(ro=oo.rpcUrls)!==null&&ro!==void 0?ro:[],(no=oo.blockExplorerUrls)!==null&&no!==void 0?no:[],oo.chainName,(io=oo.iconUrls)!==null&&io!==void 0?io:[],oo.nativeCurrency)?{jsonrpc:"2.0",id:0,result:null}:{jsonrpc:"2.0",id:0,error:{code:2,message:"unable to add ethereum chain"}}}async _wallet_switchEthereumChain(eo){const to=eo[0];return await this.switchEthereumChain(parseInt(to.chainId,16)),{jsonrpc:"2.0",id:0,result:null}}async _wallet_watchAsset(eo){const to=Array.isArray(eo)?eo[0]:eo;if(!to.type)throw error_1$5.standardErrors.rpc.invalidParams("Type is required");if((to==null?void 0:to.type)!=="ERC20")throw error_1$5.standardErrors.rpc.invalidParams(`Asset of type '${to.type}' is not supported`);if(!(to!=null&&to.options))throw error_1$5.standardErrors.rpc.invalidParams("Options are required");if(!(to!=null&&to.options.address))throw error_1$5.standardErrors.rpc.invalidParams("Address is required");const ro=this.getChainId(),{address:no,symbol:io,image:oo,decimals:ao}=to.options;return{jsonrpc:"2.0",id:0,result:await this.watchAsset(to.type,no,io,ao,oo,ro)}}initializeRelay(){if(!this._relay){const eo=new WalletLinkRelay_1.WalletLinkRelay({linkAPIUrl:constants_2.WALLETLINK_URL,storage:this._storage});eo.setAppInfo(this._appName,this._appLogoUrl),eo.attachUI(),eo.setAccountsCallback((to,ro)=>this._setAddresses(to,ro)),eo.setChainCallback((to,ro)=>{this.updateProviderInfo(ro,parseInt(to,10))}),this._relay=eo}return this._relay}}WalletLinkSigner$1.WalletLinkSigner=WalletLinkSigner;var provider={};Object.defineProperty(provider,"__esModule",{value:!0});provider.checkErrorForInvalidRequestArgs=provider.getCoinbaseInjectedProvider=provider.getCoinbaseInjectedSigner=provider.fetchRPCRequest=void 0;const version_1$2=version$b,error_1$4=error$2;async function fetchRPCRequest(Xr,eo){if(!eo.rpcUrl)throw error_1$4.standardErrors.rpc.internal("No RPC URL set for chain");const to=Object.assign(Object.assign({},Xr),{jsonrpc:"2.0",id:crypto.randomUUID()});return(await(await window.fetch(eo.rpcUrl,{method:"POST",body:JSON.stringify(to),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":version_1$2.LIB_VERSION}})).json()).result}provider.fetchRPCRequest=fetchRPCRequest;function getCoinbaseInjectedSigner(){return globalThis.coinbaseWalletSigner}provider.getCoinbaseInjectedSigner=getCoinbaseInjectedSigner;function getCoinbaseInjectedLegacyProvider(){return globalThis.coinbaseWalletExtension}function getInjectedEthereum(){var Xr,eo;try{const to=globalThis;return(Xr=to.ethereum)!==null&&Xr!==void 0?Xr:(eo=to.top)===null||eo===void 0?void 0:eo.ethereum}catch{return}}function getCoinbaseInjectedProvider({metadata:Xr,preference:eo}){var to;if(eo.options!=="smartWalletOnly"){if(getCoinbaseInjectedSigner())return;const io=getCoinbaseInjectedLegacyProvider();if(io){const{appName:oo,appLogoUrl:ao,appChainIds:so}=Xr;return(to=io.setAppInfo)===null||to===void 0||to.call(io,oo,ao,so),io}}const ro=getInjectedEthereum();if(ro!=null&&ro.isCoinbaseBrowser)return ro}provider.getCoinbaseInjectedProvider=getCoinbaseInjectedProvider;function checkErrorForInvalidRequestArgs(Xr){if(!Xr||typeof Xr!="object"||Array.isArray(Xr))return error_1$4.standardErrors.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:Xr});const{method:eo,params:to}=Xr;if(typeof eo!="string"||eo.length===0)return error_1$4.standardErrors.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:Xr});if(to!==void 0&&!Array.isArray(to)&&(typeof to!="object"||to===null))return error_1$4.standardErrors.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:Xr})}provider.checkErrorForInvalidRequestArgs=checkErrorForInvalidRequestArgs;Object.defineProperty(util$5,"__esModule",{value:!0});util$5.createSigner=util$5.fetchSignerType=util$5.storeSignerType=util$5.loadSignerType=void 0;const SCWSigner_1=SCWSigner$1,WalletLinkSigner_1=WalletLinkSigner$1,error_1$3=error$2,provider_1$2=provider,ScopedLocalStorage_1$2=ScopedLocalStorage$1,SIGNER_TYPE_KEY="SignerType",storage$1=new ScopedLocalStorage_1$2.ScopedLocalStorage("CBWSDK","SignerConfigurator");function loadSignerType(){return storage$1.getItem(SIGNER_TYPE_KEY)}util$5.loadSignerType=loadSignerType;function storeSignerType(Xr){storage$1.setItem(SIGNER_TYPE_KEY,Xr)}util$5.storeSignerType=storeSignerType;async function fetchSignerType(Xr){const{communicator:eo,metadata:to}=Xr;listenForWalletLinkSessionRequest(eo,to).catch(()=>{});const ro={id:crypto.randomUUID(),event:"selectSignerType",data:Xr.preference},{data:no}=await eo.postRequestAndWaitForResponse(ro);return no}util$5.fetchSignerType=fetchSignerType;function createSigner(Xr){const{signerType:eo,metadata:to,communicator:ro,updateListener:no}=Xr;switch(eo){case"scw":return new SCWSigner_1.SCWSigner({metadata:to,updateListener:no,communicator:ro});case"walletlink":return new WalletLinkSigner_1.WalletLinkSigner({metadata:to,updateListener:no});case"extension":{const io=(0,provider_1$2.getCoinbaseInjectedSigner)();if(!io)throw error_1$3.standardErrors.rpc.internal("injected signer not found");return io}}}util$5.createSigner=createSigner;async function listenForWalletLinkSessionRequest(Xr,eo){await Xr.onMessage(({event:ro})=>ro==="WalletLinkSessionRequest");const to=new WalletLinkSigner_1.WalletLinkSigner({metadata:eo});Xr.postMessage({event:"WalletLinkUpdate",data:{session:to.getSession()}}),await to.handshake(),Xr.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}var Communicator$1={},util={};Object.defineProperty(util,"__esModule",{value:!0});util.closePopup=util.openPopup=void 0;const error_1$2=error$2,POPUP_WIDTH=420,POPUP_HEIGHT=540;function openPopup(Xr){const eo=(window.innerWidth-POPUP_WIDTH)/2+window.screenX,to=(window.innerHeight-POPUP_HEIGHT)/2+window.screenY,ro=window.open(Xr,"Smart Wallet",`width=${POPUP_WIDTH}, height=${POPUP_HEIGHT}, left=${eo}, top=${to}`);if(ro==null||ro.focus(),!ro)throw error_1$2.standardErrors.rpc.internal("Pop up window failed to open");return ro}util.openPopup=openPopup;function closePopup(Xr){Xr&&!Xr.closed&&Xr.close()}util.closePopup=closePopup;Object.defineProperty(Communicator$1,"__esModule",{value:!0});Communicator$1.Communicator=void 0;const version_1$1=version$b,util_1$2=util,constants_1=constants$3,error_1$1=error$2;class Communicator{constructor(eo=constants_1.CB_KEYS_URL){this.popup=null,this.listeners=new Map,this.postMessage=async to=>{(await this.waitForPopupLoaded()).postMessage(to,this.url.origin)},this.postRequestAndWaitForResponse=async to=>{const ro=this.onMessage(({requestId:no})=>no===to.id);return this.postMessage(to),await ro},this.onMessage=async to=>new Promise((ro,no)=>{const io=oo=>{if(oo.origin!==this.url.origin)return;const ao=oo.data;to(ao)&&(ro(ao),window.removeEventListener("message",io),this.listeners.delete(io))};window.addEventListener("message",io),this.listeners.set(io,{reject:no})}),this.disconnect=()=>{(0,util_1$2.closePopup)(this.popup),this.popup=null,this.listeners.forEach(({reject:to},ro)=>{to(error_1$1.standardErrors.provider.userRejectedRequest("Request rejected")),window.removeEventListener("message",ro)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(this.popup=(0,util_1$2.openPopup)(this.url),this.onMessage(({event:to})=>to==="PopupUnload").then(this.disconnect).catch(()=>{}),this.onMessage(({event:to})=>to==="PopupLoaded").then(to=>{this.postMessage({requestId:to.id,data:{version:version_1$1.LIB_VERSION}})}).then(()=>{if(!this.popup)throw error_1$1.standardErrors.rpc.internal();return this.popup})),this.url=new URL(eo)}}Communicator$1.Communicator=Communicator;var method={};Object.defineProperty(method,"__esModule",{value:!0});method.determineMethodCategory=void 0;const mapping={handshake:["eth_requestAccounts"],sign:["eth_ecRecover","personal_sign","personal_ecRecover","eth_signTransaction","eth_sendTransaction","eth_signTypedData_v1","eth_signTypedData_v3","eth_signTypedData_v4","eth_signTypedData","wallet_addEthereumChain","wallet_switchEthereumChain","wallet_watchAsset","wallet_getCapabilities","wallet_sendCalls","wallet_showCallsStatus"],state:["eth_chainId","eth_accounts","eth_coinbase","net_version"],deprecated:["eth_sign","eth_signTypedData_v2"],unsupported:["eth_subscribe","eth_unsubscribe"],fetch:[]};function determineMethodCategory(Xr){for(const eo in mapping){const to=eo;if(mapping[to].includes(Xr))return to}}method.determineMethodCategory=determineMethodCategory;var __rest$2=commonjsGlobal&&commonjsGlobal.__rest||function(Xr,eo){var to={};for(var ro in Xr)Object.prototype.hasOwnProperty.call(Xr,ro)&&eo.indexOf(ro)<0&&(to[ro]=Xr[ro]);if(Xr!=null&&typeof Object.getOwnPropertySymbols=="function")for(var no=0,ro=Object.getOwnPropertySymbols(Xr);no{try{if(this.connected)return this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),this.accounts;const lo=await this.requestSignerSelection(),fo=this.initSigner(lo),ho=await fo.handshake();return this.signer=fo,(0,util_2.storeSignerType)(lo),this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),ho}catch(lo){throw this.handleUnauthorizedError(lo),lo}},sign:async co=>{if(!this.connected||!this.signer)throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods");try{return await this.signer.request(co)}catch(lo){throw this.handleUnauthorizedError(lo),lo}},fetch:co=>(0,provider_1$1.fetchRPCRequest)(co,this.chain),state:co=>{const lo=()=>{if(this.connected)return this.accounts;throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods")};switch(co.method){case"eth_chainId":return(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id));case"net_version":return this.chain.id;case"eth_accounts":return lo();case"eth_coinbase":return lo()[0];default:return this.handlers.unsupported(co)}},deprecated:({method:co})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${co} is deprecated.`)},unsupported:({method:co})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${co} is not supported.`)}},this.isCoinbaseWallet=!0,this.updateListener={onAccountsUpdate:({accounts:co,source:lo})=>{(0,util_1$1.areAddressArraysEqual)(this.accounts,co)||(this.accounts=co,lo!=="storage"&&this.emit("accountsChanged",this.accounts))},onChainUpdate:({chain:co,source:lo})=>{co.id===this.chain.id&&co.rpcUrl===this.chain.rpcUrl||(this.chain=co,lo!=="storage"&&this.emit("chainChanged",(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(co.id))))}},this.metadata=no,this.preference=ao,this.communicator=new Communicator_1.Communicator(oo),this.chain={id:(ro=(to=no.appChainIds)===null||to===void 0?void 0:to[0])!==null&&ro!==void 0?ro:1};const so=(0,util_2.loadSignerType)();this.signer=so?this.initSigner(so):null}get connected(){return this.accounts.length>0}async request(eo){var to;try{const ro=(0,provider_1$1.checkErrorForInvalidRequestArgs)(eo);if(ro)throw ro;const no=(to=(0,method_1.determineMethodCategory)(eo.method))!==null&&to!==void 0?to:"fetch";return this.handlers[no](eo)}catch(ro){return Promise.reject((0,serialize_1$1.serializeError)(ro,eo.method))}}handleUnauthorizedError(eo){eo.code===error_1.standardErrorCodes.provider.unauthorized&&this.disconnect()}async enable(){return console.warn('.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.'),await this.request({method:"eth_requestAccounts"})}async disconnect(){this.accounts=[],this.chain={id:1},ScopedLocalStorage_1$1.ScopedLocalStorage.clearAll(),this.emit("disconnect",error_1.standardErrors.provider.disconnected("User initiated disconnection"))}requestSignerSelection(){return(0,util_2.fetchSignerType)({communicator:this.communicator,preference:this.preference,metadata:this.metadata})}initSigner(eo){return(0,util_2.createSigner)({signerType:eo,metadata:this.metadata,communicator:this.communicator,updateListener:this.updateListener})}}CoinbaseWalletProvider$1.CoinbaseWalletProvider=CoinbaseWalletProvider;Object.defineProperty(CoinbaseWalletSDK$1,"__esModule",{value:!0});CoinbaseWalletSDK$1.CoinbaseWalletSDK=void 0;const wallet_logo_1=walletLogo$1,CoinbaseWalletProvider_1=CoinbaseWalletProvider$1,ScopedLocalStorage_1=ScopedLocalStorage$1,version_1=version$b,util_1=util$6,provider_1=provider;class CoinbaseWalletSDK{constructor(eo){this.metadata={appName:eo.appName||"Dapp",appLogoUrl:eo.appLogoUrl||(0,util_1.getFavicon)(),appChainIds:eo.appChainIds||[]},this.storeLatestVersion()}makeWeb3Provider(eo={options:"all"}){var to;const ro={metadata:this.metadata,preference:eo};return(to=(0,provider_1.getCoinbaseInjectedProvider)(ro))!==null&&to!==void 0?to:new CoinbaseWalletProvider_1.CoinbaseWalletProvider(ro)}getCoinbaseWalletLogo(eo,to=240){return(0,wallet_logo_1.walletLogo)(eo,to)}storeLatestVersion(){new ScopedLocalStorage_1.ScopedLocalStorage("CBWSDK").setItem("VERSION",version_1.LIB_VERSION)}}CoinbaseWalletSDK$1.CoinbaseWalletSDK=CoinbaseWalletSDK;(function(Xr){Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.CoinbaseWalletSDK=void 0;const eo=CoinbaseWalletSDK$1;Xr.default=eo.CoinbaseWalletSDK;var to=CoinbaseWalletSDK$1;Object.defineProperty(Xr,"CoinbaseWalletSDK",{enumerable:!0,get:function(){return to.CoinbaseWalletSDK}})})(dist);let coinbaseProvider;const baseSepolia=84532,baseMainnet=8453,getCoinbaseProvider=({appLogoUrl:Xr,appName:eo,evmNetworks:to,walletPreference:ro}={})=>{const no=to==null?void 0:to.map(ao=>Number(ao.chainId));return(to==null?void 0:to.some(ao=>ao.chainId===baseSepolia))&&(no==null||no.sort((ao,so)=>ao===baseSepolia?-1:so===baseSepolia?1:0)),(to==null?void 0:to.some(ao=>ao.chainId===baseMainnet))&&(no==null||no.sort((ao,so)=>ao===baseMainnet?-1:so===baseMainnet?1:0)),coinbaseProvider||(coinbaseProvider=new dist.CoinbaseWalletSDK({appChainIds:no,appLogoUrl:Xr,appName:eo}).makeWeb3Provider({options:ro??"all"})),coinbaseProvider};class Coinbase extends EthWalletConnector{constructor(eo){var{appName:to,appLogoUrl:ro,evmNetworks:no,coinbaseWalletPreference:io}=eo,oo=__rest$6(eo,["appName","appLogoUrl","evmNetworks","coinbaseWalletPreference"]);super(Object.assign({evmNetworks:no},oo)),this.name="Coinbase",this.overrideKey="coinbase",this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.canConnectViaQrCode=!1,this.canConnectViaCustodialService=!this.isInstalledOnBrowser(),this.coinbaseProviderOpts={appLogoUrl:ro,appName:to,evmNetworks:no,walletPreference:io}}get coinbaseProvider(){return getCoinbaseProvider(this.coinbaseProviderOpts)}getConnectedAccounts(){return __awaiter$a(this,void 0,void 0,function*(){try{const eo=yield this.coinbaseProvider.request({method:"eth_accounts"});return eo[0]&&this.setActiveAccount(eo[0]),eo}catch{return[]}})}isInstalledOnBrowser(){var eo;return!!(!((eo=window==null?void 0:window.coinbaseWalletExtension)===null||eo===void 0)&&eo.isCoinbaseWallet)}getAddress(){return __awaiter$a(this,void 0,void 0,function*(){const[eo]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});return this.setActiveAccount(eo),eo})}signMessage(eo){return __awaiter$a(this,void 0,void 0,function*(){const[to]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});try{return yield this.coinbaseProvider.request({method:"personal_sign",params:[toHex$1(toBytes$1(eo)),to.toLowerCase()]})}catch{return}})}setupEventListeners(){const{handleAccountChange:eo,handleChainChange:to,handleDisconnect:ro}=eventListenerHandlers(this);this.coinbaseProvider.on("accountsChanged",eo),this.coinbaseProvider.on("chainChanged",to),this.coinbaseProvider.on("disconnect",ro),this.teardownEventListeners=()=>{this.coinbaseProvider.removeListener("accountsChanged",eo),this.coinbaseProvider.removeListener("chainChanged",to),this.coinbaseProvider.removeListener("disconnect",ro)}}getWalletClient(eo){return createWalletClient({account:this.getActiveAccount(),chain:eo?chainsMap[eo]:void 0,transport:custom$1(this.coinbaseProvider)})}}assertPackageVersion("@dynamic-labs/ethereum",version$c);const EthereumWalletConnectors=Xr=>[...injectedWalletOverrides$1,...fetchInjectedWalletConnector(Xr),...fetchWalletConnectWallets(Xr),...TurnkeyEVMWalletConnectors(Xr),Coinbase,UnknownInjected$1,FallbackEvmConnector,getWalletConnectConnector()];var version$a="3.4.4";function __awaiter$6(Xr,eo,to,ro){function no(io){return io instanceof to?io:new to(function(oo){oo(io)})}return new(to||(to=Promise))(function(io,oo){function ao(lo){try{co(ro.next(lo))}catch(fo){oo(fo)}}function so(lo){try{co(ro.throw(lo))}catch(fo){oo(fo)}}function co(lo){lo.done?io(lo.value):no(lo.value).then(ao,so)}co((ro=ro.apply(Xr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;let config$1=null;const setConfig=Xr=>{config$1=Xr};let LEVELS=function(Xr){return Xr[Xr.debug=5]="debug",Xr[Xr.info=4]="info",Xr[Xr.log=3]="log",Xr[Xr.warn=2]="warn",Xr[Xr.error=1]="error",Xr}({});const buildLoggerMessageArgs=Xr=>{const{title:eo,message:to}=Xr;return[` %c${eo} ============================ @@ -2569,7 +2569,7 @@ const result = await caller.call('myProcedure', input); d="M18.316 8H13.684C13.5292 8 13.4052 8.1272 13.4018 8.28531C13.3082 12.7296 11.0323 16.9477 7.11513 19.9355C6.99077 20.0303 6.96243 20.2085 7.05335 20.3369L9.76349 24.1654C9.85569 24.2957 10.0353 24.3251 10.1618 24.2294C12.6111 22.3734 14.5812 20.1345 16 17.6529C17.4187 20.1345 19.389 22.3734 21.8383 24.2294C21.9646 24.3251 22.1443 24.2957 22.2366 24.1654L24.9467 20.3369C25.0375 20.2085 25.0092 20.0303 24.885 19.9355C20.9676 16.9477 18.6918 12.7296 18.5983 8.28531C18.5949 8.1272 18.4708 8 18.316 8Z" fill="white" /> - `,R$1=()=>Object.keys(localStorage).some(Xr=>Xr==="walletconnect"||Xr.startsWith("wc@2:")),_$1=()=>{if(R$1()){delete localStorage.walletconnect;for(const Xr in localStorage)Xr.startsWith("wc@2:")&&delete localStorage[Xr]}},j$2=()=>{var Xr;return window!=null&&window.starknet_argentX?(Xr=window==null?void 0:window.starknet_argentX)==null?void 0:Xr.isInAppBrowser:!1};let O$1=class extends T$2{constructor(eo={}){super(),l$1(this,"_wallet",null),l$1(this,"_options"),this._options=eo}available(){return!0}async ready(){return await this.ensureWallet(),this._wallet?this._wallet.isPreauthorized():!1}get id(){return"argentMobile"}get name(){return"Argent (mobile)"}get icon(){return{dark:u,light:u}}get wallet(){if(!this._wallet)throw new P$1;return this._wallet}async connect(){if(await this.ensureWallet(),!this._wallet)throw new U$2;const eo=this._wallet.account,to=await this.chainId();return{account:eo.address,chainId:to}}async disconnect(){var eo;if(await this._wallet.disable(),_$1(),!this.available()&&!this._wallet)throw new U$2;if(!((eo=this._wallet)!=null&&eo.isConnected))throw new S$1;this._wallet=null}async account(){if(!this._wallet||!this._wallet.account)throw new P$1;return this._wallet.account}async chainId(){if(!this._wallet||!this.wallet.account||!this._wallet.provider)throw new P$1;const eo=await this._wallet.provider.getChainId();return BigInt(eo)}async initEventListener(eo){if(!this._wallet)throw new P$1;this._wallet.on("accountsChanged",eo)}async removeEventListener(eo){if(!this._wallet)throw new P$1;this._wallet.off("accountsChanged",eo),this._wallet=null}async ensureWallet(){const{getStarknetWindowObject:eo}=await __vitePreload(async()=>{const{getStarknetWindowObject:vo}=await import("./index-8e228000-DPntdE7M.js");return{getStarknetWindowObject:vo}},[]),{chainId:to,projectId:ro,dappName:no,description:io,url:oo,icons:ao,provider:so,rpcUrl:co}=this._options,lo=s(),fo=co??(!to||to===constants_exports.NetworkName.SN_MAIN?lo.mainnet:lo.testnet),ho={chainId:to??constants_exports.NetworkName.SN_MAIN,name:no,projectId:ro??d$1,description:io,url:oo,icons:ao,provider:so,rpcUrl:fo};ro===d$1&&(console.log("========= NOTICE ========="),console.log("While your application will continue to function, we highly recommended"),console.log("signing up for your own API keys."),console.log("Go to WalletConnect Cloud (https://cloud.walletconnect.com) and create a new account."),console.log("Once your account is created, create a new project and collect the Project ID"),console.log("=========================="));const go=await eo(ho);if(!go)throw new A$2;this._wallet=go;const yo=this._wallet;await yo.enable(),yo.client.on("session_delete",()=>{_$1(),this._wallet=null,q$2(),document.dispatchEvent(new Event("wallet_disconnected"))})}};var g=Object.defineProperty,j$1=(Xr,eo,to)=>eo in Xr?g(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,N$1=(Xr,eo,to)=>(j$1(Xr,typeof eo!="symbol"?eo+"":eo,to),to);const d="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIiByeD0iOCIgZmlsbD0iYmxhY2siLz4KPHBhdGggZD0iTTE4LjQwMTggNy41NTU1NkgxMy41OTgyQzEzLjQzNzcgNy41NTU1NiAxMy4zMDkxIDcuNjg3NDcgMTMuMzA1NiA3Ljg1MTQzQzEzLjIwODUgMTIuNDYwMyAxMC44NDg0IDE2LjgzNDcgNi43ODYwOCAxOS45MzMxQzYuNjU3MTEgMjAuMDMxNCA2LjYyNzczIDIwLjIxNjIgNi43MjIwMiAyMC4zNDkzTDkuNTMyNTMgMjQuMzE5NkM5LjYyODE1IDI0LjQ1NDggOS44MTQ0NCAyNC40ODUzIDkuOTQ1NTggMjQuMzg2QzEyLjQ4NTYgMjIuNDYxMyAxNC41Mjg3IDIwLjEzOTUgMTYgMTcuNTY2QzE3LjQ3MTMgMjAuMTM5NSAxOS41MTQ1IDIyLjQ2MTMgMjIuMDU0NSAyNC4zODZDMjIuMTg1NiAyNC40ODUzIDIyLjM3MTkgMjQuNDU0OCAyMi40Njc2IDI0LjMxOTZMMjUuMjc4MSAyMC4zNDkzQzI1LjM3MjMgMjAuMjE2MiAyNS4zNDI5IDIwLjAzMTQgMjUuMjE0IDE5LjkzMzFDMjEuMTUxNiAxNi44MzQ3IDE4Ljc5MTUgMTIuNDYwMyAxOC42OTQ2IDcuODUxNDNDMTguNjkxMSA3LjY4NzQ3IDE4LjU2MjMgNy41NTU1NiAxOC40MDE4IDcuNTU1NTZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNMjQuNzIzNiAxMC40OTJMMjQuMjIzMSA4LjkyNDM5QzI0LjEyMTMgOC42MDYxNCAyMy44NzM0IDguMzU4MjQgMjMuNTU3NyA4LjI2MDIzTDIyLjAwMzkgNy43NzU5NUMyMS43ODk1IDcuNzA5MDYgMjEuNzg3MyA3LjQwMTc3IDIyLjAwMTEgNy4zMzIwMUwyMy41NDY5IDYuODI0NjZDMjMuODYwOSA2LjcyMTQ2IDI0LjEwNiA2LjQ2OTUyIDI0LjIwMjcgNi4xNTAxMUwyNC42Nzk4IDQuNTc1MDJDMjQuNzQ1OCA0LjM1NzA5IDI1LjA0ODkgNC4zNTQ3NyAyNS4xMTgzIDQuNTcxNTZMMjUuNjE4OCA2LjEzOTE1QzI1LjcyMDYgNi40NTc0IDI1Ljk2ODYgNi43MDUzMSAyNi4yODQyIDYuODAzOUwyNy44MzggNy4yODc2MUMyOC4wNTI0IDcuMzU0NSAyOC4wNTQ3IDcuNjYxNzkgMjcuODQwOCA3LjczMjEzTDI2LjI5NSA4LjIzOTQ4QzI1Ljk4MTEgOC4zNDIxIDI1LjczNiA4LjU5NDA0IDI1LjYzOTMgOC45MTQwMkwyNS4xNjIxIDEwLjQ4ODVDMjUuMDk2MSAxMC43MDY1IDI0Ljc5MyAxMC43MDg4IDI0LjcyMzYgMTAuNDkyWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",l="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlLXdpZHRoPSIxLjUiIHN0cm9rZT0iYmxhY2siPgogIDxwYXRoIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTkuODc5IDcuNTE5YzEuMTcxLTEuMDI1IDMuMDcxLTEuMDI1IDQuMjQyIDAgMS4xNzIgMS4wMjUgMS4xNzIgMi42ODcgMCAzLjcxMi0uMjAzLjE3OS0uNDMuMzI2LS42Ny40NDItLjc0NS4zNjEtMS40NS45OTktMS40NSAxLjgyN3YuNzVNMjEgMTJhOSA5IDAgMTEtMTggMCA5IDkgMCAwMTE4IDB6bS05IDUuMjVoLjAwOHYuMDA4SDEydi0uMDA4eiIgLz4KPC9zdmc+",h="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlLXdpZHRoPSIxLjUiIHN0cm9rZT0id2hpdGUiPgogIDxwYXRoIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTkuODc5IDcuNTE5YzEuMTcxLTEuMDI1IDMuMDcxLTEuMDI1IDQuMjQyIDAgMS4xNzIgMS4wMjUgMS4xNzIgMi42ODcgMCAzLjcxMi0uMjAzLjE3OS0uNDMuMzI2LS42Ny40NDItLjc0NS4zNjEtMS40NS45OTktMS40NSAxLjgyN3YuNzVNMjEgMTJhOSA5IDAgMTEtMTggMCA5IDkgMCAwMTE4IDB6bS05IDUuMjVoLjAwOHYuMDA4SDEydi0uMDA4eiIgLz4KPC9zdmc+Cg==";let L$1=class extends T$2{constructor({options:eo}){super(),N$1(this,"_wallet"),N$1(this,"_options"),this._options=eo}available(){return this.ensureWallet(),this._wallet!==void 0}async ready(){return this.ensureWallet(),this._wallet?await this._wallet.isPreauthorized():!1}async chainId(){if(this.ensureWallet(),!this._wallet)throw new P$1;const eo=await this._wallet.provider.getChainId();return BigInt(eo)}async onAccountsChanged(eo){let to;if(typeof eo=="string"?to=eo:to=eo[0],to){const ro=await this.chainId();this.emit("change",{account:to,chainId:ro})}else this.emit("disconnect")}onNetworkChanged(eo){switch(eo){case"SN_MAIN":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_MAIN)});break;case"SN_GOERLI":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_GOERLI)});break;case"mainnet-alpha":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_MAIN)});break;case"goerli-alpha":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_GOERLI)});break;default:this.emit("change",{});break}}async connect(){if(this.ensureWallet(),!this._wallet)throw new U$2;let eo;try{eo=await this._wallet.enable({starknetVersion:"v5"})}catch{throw new A$2}if(!this._wallet.isConnected||!eo)throw new A$2;this._wallet.on("accountsChanged",async no=>{await this.onAccountsChanged(no)}),this._wallet.on("networkChanged",no=>{this.onNetworkChanged(no)}),await this.onAccountsChanged(eo);const to=this._wallet.account.address,ro=await this.chainId();return this.emit("connect",{account:to,chainId:ro}),{account:to,chainId:ro}}async disconnect(){var eo;if(this.ensureWallet(),q$2(),!this.available())throw new U$2;if(!((eo=this._wallet)!=null&&eo.isConnected))throw new S$1}async account(){if(this.ensureWallet(),!this._wallet||!this._wallet.account)throw new P$1;return this._wallet.account}get id(){return this._options.id}get name(){if(!this._wallet)throw new P$1;return this._wallet.name}get icon(){var eo;return this._options.icon?this._options.icon:(eo=this._wallet)!=null&&eo.icon?{dark:this._wallet.icon,light:this._wallet.icon}:{dark:h,light:l}}get wallet(){if(!this._wallet)throw new P$1;return this._wallet}ensureWallet(){const eo=z$1(globalThis).filter(to=>to.id===this._options.id)[0];if(eo){const{provider:to}=this._options;to&&Object.assign(eo,{provider:to}),this._wallet=eo}}};function z$1(Xr){return Object.values(Object.getOwnPropertyNames(Xr).reduce((eo,to)=>{if(to.startsWith("starknet")){const ro=Xr[to];y$1(ro)&&!eo[ro.id]&&(eo[ro.id]=ro)}return eo},{}))}function y$1(Xr){try{return Xr&&["request","isConnected","provider","enable","isPreauthorized","on","off","version","id","name","icon"].every(eo=>eo in Xr)}catch{}return!1}var He=Object.defineProperty,qe=(Xr,eo,to)=>eo in Xr?He(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,ae=(Xr,eo,to)=>(qe(Xr,typeof eo!="symbol"?eo+"":eo,to),to),rt=Object.defineProperty,nt=(Xr,eo,to)=>eo in Xr?rt(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,it=(Xr,eo,to)=>(nt(Xr,eo+"",to),to),pe=(Xr,eo,to)=>{if(!eo.has(Xr))throw TypeError("Cannot "+to)},z=(Xr,eo,to)=>(pe(Xr,eo,"read from private field"),to?to.call(Xr):eo.get(Xr)),V=(Xr,eo,to)=>{if(eo.has(Xr))throw TypeError("Cannot add the same private member more than once");eo instanceof WeakSet?eo.add(Xr):eo.set(Xr,to)},ie=(Xr,eo,to,ro)=>(pe(Xr,eo,"write to private field"),eo.set(Xr,to),to),$=(Xr,eo,to)=>(pe(Xr,eo,"access private method"),to);const ot=[{id:"argentX",name:"Argent X",icon:"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjQwIiBoZWlnaHQ9IjM2IiB2aWV3Qm94PSIwIDAgNDAgMzYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGQ9Ik0yNC43NTgyIC0zLjk3MzY0ZS0wN0gxNC42MjM4QzE0LjI4NTEgLTMuOTczNjRlLTA3IDE0LjAxMzggMC4yODExNzggMTQuMDA2NCAwLjYzMDY4M0MxMy44MDE3IDEwLjQ1NDkgOC44MjIzNCAxOS43NzkyIDAuMjUxODkzIDI2LjM4MzdDLTAuMDIwMjA0NiAyNi41OTMzIC0wLjA4MjE5NDYgMjYuOTg3MiAwLjExNjczNCAyNy4yNzA5TDYuMDQ2MjMgMzUuNzM0QzYuMjQ3OTYgMzYuMDIyIDYuNjQwOTkgMzYuMDg3IDYuOTE3NjYgMzUuODc1NEMxMi4yNzY1IDMxLjc3MjggMTYuNTg2OSAyNi44MjM2IDE5LjY5MSAyMS4zMzhDMjIuNzk1MSAyNi44MjM2IDI3LjEwNTcgMzEuNzcyOCAzMi40NjQ2IDM1Ljg3NTRDMzIuNzQxIDM2LjA4NyAzMy4xMzQxIDM2LjAyMiAzMy4zMzYxIDM1LjczNEwzOS4yNjU2IDI3LjI3MDlDMzkuNDY0MiAyNi45ODcyIDM5LjQwMjIgMjYuNTkzMyAzOS4xMzA0IDI2LjM4MzdDMzAuNTU5NyAxOS43NzkyIDI1LjU4MDQgMTAuNDU0OSAyNS4zNzU5IDAuNjMwNjgzQzI1LjM2ODUgMC4yODExNzggMjUuMDk2OSAtMy45NzM2NGUtMDcgMjQuNzU4MiAtMy45NzM2NGUtMDdaIiBmaWxsPSIjRkY4NzVCIi8+Cjwvc3ZnPgo=",downloads:{chrome:"https://chrome.google.com/webstore/detail/argent-x-starknet-wallet/dlcobpjiigpikoobohmabehhmhfoodbb",firefox:"https://addons.mozilla.org/en-US/firefox/addon/argent-x"}},{id:"braavos",name:"Braavos",icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgdmlld0JveD0iMCAwIDEwMCAxMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgICA8cGF0aAogICAgICAgIGQ9Ik02Mi43MDUgMTMuOTExNkM2Mi44MzU5IDE0LjEzMzMgNjIuNjYyMSAxNC40MDcgNjIuNDAzOSAxNC40MDdDNTcuMTgwNyAxNC40MDcgNTIuOTM0OCAxOC41NDI3IDUyLjgzNTEgMjMuNjgxN0M1MS4wNDY1IDIzLjM0NzcgNDkuMTkzMyAyMy4zMjI2IDQ3LjM2MjYgMjMuNjMxMUM0Ny4yMzYxIDE4LjUxNTYgNDMuMDAwOSAxNC40MDcgMzcuNzk0OCAxNC40MDdDMzcuNTM2NSAxNC40MDcgMzcuMzYyNSAxNC4xMzMxIDM3LjQ5MzUgMTMuOTExMkM0MC4wMjE3IDkuNjI4MDkgNDQuNzIwNCA2Ljc1IDUwLjA5OTEgNi43NUM1NS40NzgxIDYuNzUgNjAuMTc2OSA5LjYyODI2IDYyLjcwNSAxMy45MTE2WiIKICAgICAgICBmaWxsPSJ1cmwoI3BhaW50MF9saW5lYXJfMzcyXzQwMjU5KSIgLz4KICAgIDxwYXRoCiAgICAgICAgZD0iTTc4Ljc2MDYgNDUuODcxOEM4MC4yNzI1IDQ2LjMyOTcgODEuNzAyNSA0NS4wMDU1IDgxLjE3MTQgNDMuNTIyMkM3Ni40MTM3IDMwLjIzMzQgNjEuMzkxMSAyNC44MDM5IDUwLjAyNzcgMjQuODAzOUMzOC42NDQyIDI0LjgwMzkgMjMuMjg2OCAzMC40MDcgMTguODc1NCA0My41OTEyQzE4LjM4MjQgNDUuMDY0NSAxOS44MDgzIDQ2LjM0NDYgMjEuMjk3OCA0NS44ODgxTDQ4Ljg3MiAzNy40MzgxQzQ5LjUzMzEgMzcuMjM1NSA1MC4yMzk5IDM3LjIzNDQgNTAuOTAxNyAzNy40MzQ4TDc4Ljc2MDYgNDUuODcxOFoiCiAgICAgICAgZmlsbD0idXJsKCNwYWludDFfbGluZWFyXzM3Ml80MDI1OSkiIC8+CiAgICA8cGF0aAogICAgICAgIGQ9Ik0xOC44MTMyIDQ4LjE3MDdMNDguODkzNSAzOS4wNDcyQzQ5LjU1MDYgMzguODQ3OCA1MC4yNTI0IDM4Ljg0NzMgNTAuOTA5OCAzOS4wNDU2TDgxLjE3ODEgNDguMTc1MkM4My42OTEyIDQ4LjkzMzIgODUuNDExIDUxLjI0ODMgODUuNDExIDUzLjg3MzVWODEuMjIzM0M4NS4yOTQ0IDg3Ljg5OTEgNzkuMjk3NyA5My4yNSA3Mi42MjQ1IDkzLjI1SDYxLjU0MDZDNjAuNDQ0OSA5My4yNSA1OS41NTc3IDkyLjM2MzcgNTkuNTU3NyA5MS4yNjhWODEuNjc4OUM1OS41NTc3IDc3LjkwMzEgNjEuNzkyMSA3NC40ODU1IDY1LjI0OTggNzIuOTcyOUM2OS44ODQ5IDcwLjk0NTQgNzUuMzY4MSA2OC4yMDI4IDc2LjM5OTQgNjIuNjk5MkM3Ni43MzIzIDYwLjkyMjkgNzUuNTc0MSA1OS4yMDk0IDczLjgwMjQgNTguODU3M0M2OS4zMjI2IDU3Ljk2NjcgNjQuMzU2MiA1OC4zMTA3IDYwLjE1NjQgNjAuMTg5M0M1NS4zODg3IDYyLjMyMTkgNTQuMTQxNSA2NS44Njk0IDUzLjY3OTcgNzAuNjMzN0w1My4xMjAxIDc1Ljc2NjJDNTIuOTQ5MSA3Ny4zMzQ5IDUxLjQ3ODUgNzguNTM2NiA0OS45MDE0IDc4LjUzNjZDNDguMjY5OSA3OC41MzY2IDQ3LjA0NjUgNzcuMjk0IDQ2Ljg2OTYgNzUuNjcxMkw0Ni4zMjA0IDcwLjYzMzdDNDUuOTI0OSA2Ni41NTI5IDQ1LjIwNzkgNjIuNTg4NyA0MC45ODk1IDYwLjcwMThDMzYuMTc3NiA1OC41NDk0IDMxLjM0MTkgNTcuODM0NyAyNi4xOTc2IDU4Ljg1NzNDMjQuNDI2IDU5LjIwOTQgMjMuMjY3OCA2MC45MjI5IDIzLjYwMDcgNjIuNjk5MkMyNC42NDEgNjguMjUwNyAzMC4wODEyIDcwLjkzMDUgMzQuNzUwMyA3Mi45NzI5QzM4LjIwOCA3NC40ODU1IDQwLjQ0MjQgNzcuOTAzMSA0MC40NDI0IDgxLjY3ODlWOTEuMjY2M0M0MC40NDI0IDkyLjM2MiAzOS41NTU1IDkzLjI1IDM4LjQ1OTkgOTMuMjVIMjcuMzc1NkMyMC43MDI0IDkzLjI1IDE0LjcwNTcgODcuODk5MSAxNC41ODkxIDgxLjIyMzNWNTMuODY2M0MxNC41ODkxIDUxLjI0NDYgMTYuMzA0NSA0OC45MzE2IDE4LjgxMzIgNDguMTcwN1oiCiAgICAgICAgZmlsbD0idXJsKCNwYWludDJfbGluZWFyXzM3Ml80MDI1OSkiIC8+CiAgICA8ZGVmcz4KICAgICAgICA8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfMzcyXzQwMjU5IiB4MT0iNDkuMzA1NyIgeTE9IjIuMDc5IiB4Mj0iODAuMzYyNyIgeTI9IjkzLjY1OTciCiAgICAgICAgICAgIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KICAgICAgICAgICAgPHN0b3Agc3RvcC1jb2xvcj0iI0Y1RDQ1RSIgLz4KICAgICAgICAgICAgPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjRkY5NjAwIiAvPgogICAgICAgIDwvbGluZWFyR3JhZGllbnQ+CiAgICAgICAgPGxpbmVhckdyYWRpZW50IGlkPSJwYWludDFfbGluZWFyXzM3Ml80MDI1OSIgeDE9IjQ5LjMwNTciIHkxPSIyLjA3OSIgeDI9IjgwLjM2MjciIHkyPSI5My42NTk3IgogICAgICAgICAgICBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CiAgICAgICAgICAgIDxzdG9wIHN0b3AtY29sb3I9IiNGNUQ0NUUiIC8+CiAgICAgICAgICAgIDxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0ZGOTYwMCIgLz4KICAgICAgICA8L2xpbmVhckdyYWRpZW50PgogICAgICAgIDxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQyX2xpbmVhcl8zNzJfNDAyNTkiIHgxPSI0OS4zMDU3IiB5MT0iMi4wNzkiIHgyPSI4MC4zNjI3IiB5Mj0iOTMuNjU5NyIKICAgICAgICAgICAgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICAgICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjRjVENDVFIiAvPgogICAgICAgICAgICA8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGRjk2MDAiIC8+CiAgICAgICAgPC9saW5lYXJHcmFkaWVudD4KICAgIDwvZGVmcz4KPC9zdmc+",downloads:{chrome:"https://chrome.google.com/webstore/detail/braavos-wallet/jnlgamecbpmbajjfhmmmlhejkemejdma",firefox:"https://addons.mozilla.org/en-US/firefox/addon/braavos-wallet",edge:"https://microsoftedge.microsoft.com/addons/detail/braavos-wallet/hkkpjehhcnhgefhbdcgfkeegglpjchdc"}}],st=()=>`${Date.now()}-${Math.floor(Math.random()*(9e12-1))+1e12}`,ye=Xr=>{for(let eo=Xr.length-1;eo>0;eo--){const to=Math.floor(Math.random()*(eo+1));[Xr[eo],Xr[to]]=[Xr[to],Xr[eo]]}return Xr};function ce(...Xr){return eo=>Xr.reduce((to,ro)=>to.then(ro),Promise.resolve(eo))}var W,S,H,we,_e,X,te;class at{constructor(eo){V(this,we),V(this,X),V(this,W,!1),V(this,S,void 0),V(this,H,void 0),it(this,"value"),ie(this,H,eo),$(this,X,te).call(this)}set(eo){return!z(this,W)&&!$(this,X,te).call(this)?!1:(this.delete(),this.value=eo,eo&&(ie(this,S,`${z(this,H)}-${st()}`),localStorage.setItem(z(this,S),eo)),!0)}get(){return $(this,we,_e).call(this),this.value}delete(){return!z(this,W)&&!$(this,X,te).call(this)?!1:(this.value=null,z(this,S)&&localStorage.removeItem(z(this,S)),!0)}}W=new WeakMap,S=new WeakMap,H=new WeakMap,we=new WeakSet,_e=function(){this.value&&this.set(this.value)},X=new WeakSet,te=function(){try{!z(this,W)&&typeof window<"u"&&(ie(this,S,Object.keys(localStorage).find(Xr=>Xr.startsWith(z(this,H)))),ie(this,W,!0),z(this,S)&&this.set(localStorage.getItem(z(this,S))))}catch(Xr){console.warn(Xr)}return z(this,W)};function le(Xr,eo){var to,ro;if((to=eo==null?void 0:eo.include)!=null&&to.length){const no=new Set(eo.include);return Xr.filter(io=>no.has(io.id))}if((ro=eo==null?void 0:eo.exclude)!=null&&ro.length){const no=new Set(eo.exclude);return Xr.filter(io=>!no.has(io.id))}return Xr}const ve=async Xr=>{const eo=await Promise.all(Xr.map(to=>to.isPreauthorized().catch(()=>!1)));return Xr.filter((to,ro)=>eo[ro])},ct=Xr=>{try{return Xr&&["request","isConnected","provider","enable","isPreauthorized","on","off","version","id","name","icon"].every(eo=>eo in Xr)}catch{}return!1};function de(Xr,eo){return Object.values(Object.getOwnPropertyNames(Xr).reduce((to,ro)=>{if(ro.startsWith("starknet")){const no=Xr[ro];eo(no)&&!to[no.id]&&(to[no.id]=no)}return to},{}))}const ue=(Xr,eo)=>{if(eo&&Array.isArray(eo)){Xr.sort((ro,no)=>eo.indexOf(ro.id)-eo.indexOf(no.id));const to=Xr.length-eo.length;return[...Xr.slice(to),...ye(Xr.slice(0,to))]}else return ye(Xr)},lt=typeof window<"u"?window:{},dt={windowObject:lt,isWalletObject:ct,storageFactoryImplementation:Xr=>new at(Xr)};function ut(Xr={}){const{storageFactoryImplementation:eo,windowObject:to,isWalletObject:ro}={...dt,...Xr},no=eo("gsw-last");return{getAvailableWallets:async(io={})=>{const oo=de(to,ro);return ce(ao=>le(ao,io),ao=>ue(ao,io.sort))(oo)},getPreAuthorizedWallets:async(io={})=>{const oo=de(to,ro);return ce(ao=>ve(ao),ao=>le(ao,io),ao=>ue(ao,io.sort))(oo)},getDiscoveryWallets:async(io={})=>ce(oo=>le(oo,io),oo=>ue(oo,io.sort))(ot),getLastConnectedWallet:async()=>{const io=no.get(),oo=de(to,ro).find(so=>so.id===io),[ao]=await ve(oo?[oo]:[]);return ao||(no.delete(),null)},enable:async(io,oo)=>{if(await io.enable(oo??{starknetVersion:"v5"}),!io.isConnected)throw new Error("Failed to connect to wallet");return no.set(io.id),io},disconnect:async({clearLastWallet:io}={})=>{io&&no.delete()}}}const re=ut(),gt={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},Le={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},N={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},j={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},L={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class o{static getFirstMatch(eo,to){const ro=to.match(eo);return ro&&ro.length>0&&ro[1]||""}static getSecondMatch(eo,to){const ro=to.match(eo);return ro&&ro.length>1&&ro[2]||""}static matchAndReturnConst(eo,to,ro){if(eo.test(to))return ro}static getWindowsVersionName(eo){switch(eo){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(eo){const to=eo.split(".").splice(0,2).map(ro=>parseInt(ro,10)||0);if(to.push(0),to[0]===10)switch(to[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(eo){const to=eo.split(".").splice(0,2).map(ro=>parseInt(ro,10)||0);if(to.push(0),!(to[0]===1&&to[1]<5)){if(to[0]===1&&to[1]<6)return"Cupcake";if(to[0]===1&&to[1]>=6)return"Donut";if(to[0]===2&&to[1]<2)return"Eclair";if(to[0]===2&&to[1]===2)return"Froyo";if(to[0]===2&&to[1]>2)return"Gingerbread";if(to[0]===3)return"Honeycomb";if(to[0]===4&&to[1]<1)return"Ice Cream Sandwich";if(to[0]===4&&to[1]<4)return"Jelly Bean";if(to[0]===4&&to[1]>=4)return"KitKat";if(to[0]===5)return"Lollipop";if(to[0]===6)return"Marshmallow";if(to[0]===7)return"Nougat";if(to[0]===8)return"Oreo";if(to[0]===9)return"Pie"}}static getVersionPrecision(eo){return eo.split(".").length}static compareVersions(eo,to,ro=!1){const no=o.getVersionPrecision(eo),io=o.getVersionPrecision(to);let oo=Math.max(no,io),ao=0;const so=o.map([eo,to],co=>{const lo=oo-o.getVersionPrecision(co),fo=co+new Array(lo+1).join(".0");return o.map(fo.split("."),ho=>new Array(20-ho.length).join("0")+ho).reverse()});for(ro&&(ao=oo-Math.min(no,io)),oo-=1;oo>=ao;){if(so[0][oo]>so[1][oo])return 1;if(so[0][oo]===so[1][oo]){if(oo===ao)return 0;oo-=1}else if(so[0][oo]{ro[ao]=oo[ao]})}return eo}static getBrowserAlias(eo){return gt[eo]}static getBrowserTypeByAlias(eo){return Le[eo]||""}}const M=/version\/(\d+(\.?_?\d+)+)/i,ft=[{test:[/googlebot/i],describe(Xr){const eo={name:"Googlebot"},to=o.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/opera/i],describe(Xr){const eo={name:"Opera"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/opr\/|opios/i],describe(Xr){const eo={name:"Opera"},to=o.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/SamsungBrowser/i],describe(Xr){const eo={name:"Samsung Internet for Android"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/Whale/i],describe(Xr){const eo={name:"NAVER Whale Browser"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/MZBrowser/i],describe(Xr){const eo={name:"MZ Browser"},to=o.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/focus/i],describe(Xr){const eo={name:"Focus"},to=o.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/swing/i],describe(Xr){const eo={name:"Swing"},to=o.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/coast/i],describe(Xr){const eo={name:"Opera Coast"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(Xr){const eo={name:"Opera Touch"},to=o.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/yabrowser/i],describe(Xr){const eo={name:"Yandex Browser"},to=o.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/ucbrowser/i],describe(Xr){const eo={name:"UC Browser"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/Maxthon|mxios/i],describe(Xr){const eo={name:"Maxthon"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/epiphany/i],describe(Xr){const eo={name:"Epiphany"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/puffin/i],describe(Xr){const eo={name:"Puffin"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/sleipnir/i],describe(Xr){const eo={name:"Sleipnir"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/k-meleon/i],describe(Xr){const eo={name:"K-Meleon"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/micromessenger/i],describe(Xr){const eo={name:"WeChat"},to=o.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/qqbrowser/i],describe(Xr){const eo={name:/qqbrowserlite/i.test(Xr)?"QQ Browser Lite":"QQ Browser"},to=o.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/msie|trident/i],describe(Xr){const eo={name:"Internet Explorer"},to=o.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/\sedg\//i],describe(Xr){const eo={name:"Microsoft Edge"},to=o.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/edg([ea]|ios)/i],describe(Xr){const eo={name:"Microsoft Edge"},to=o.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/vivaldi/i],describe(Xr){const eo={name:"Vivaldi"},to=o.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/seamonkey/i],describe(Xr){const eo={name:"SeaMonkey"},to=o.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/sailfish/i],describe(Xr){const eo={name:"Sailfish"},to=o.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,Xr);return to&&(eo.version=to),eo}},{test:[/silk/i],describe(Xr){const eo={name:"Amazon Silk"},to=o.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/phantom/i],describe(Xr){const eo={name:"PhantomJS"},to=o.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/slimerjs/i],describe(Xr){const eo={name:"SlimerJS"},to=o.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(Xr){const eo={name:"BlackBerry"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/(web|hpw)[o0]s/i],describe(Xr){const eo={name:"WebOS Browser"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/bada/i],describe(Xr){const eo={name:"Bada"},to=o.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/tizen/i],describe(Xr){const eo={name:"Tizen"},to=o.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/qupzilla/i],describe(Xr){const eo={name:"QupZilla"},to=o.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/firefox|iceweasel|fxios/i],describe(Xr){const eo={name:"Firefox"},to=o.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/electron/i],describe(Xr){const eo={name:"Electron"},to=o.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/MiuiBrowser/i],describe(Xr){const eo={name:"Miui"},to=o.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/chromium/i],describe(Xr){const eo={name:"Chromium"},to=o.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/chrome|crios|crmo/i],describe(Xr){const eo={name:"Chrome"},to=o.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/GSA/i],describe(Xr){const eo={name:"Google Search"},to=o.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test(Xr){const eo=!Xr.test(/like android/i),to=Xr.test(/android/i);return eo&&to},describe(Xr){const eo={name:"Android Browser"},to=o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/playstation 4/i],describe(Xr){const eo={name:"PlayStation 4"},to=o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/safari|applewebkit/i],describe(Xr){const eo={name:"Safari"},to=o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/.*/i],describe(Xr){const eo=/^(.*)\/(.*) /,to=/^(.*)\/(.*)[ \t]\((.*)/,ro=Xr.search("\\(")!==-1?to:eo;return{name:o.getFirstMatch(ro,Xr),version:o.getSecondMatch(ro,Xr)}}}],wt=[{test:[/Roku\/DVP/],describe(Xr){const eo=o.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,Xr);return{name:j.Roku,version:eo}}},{test:[/windows phone/i],describe(Xr){const eo=o.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,Xr);return{name:j.WindowsPhone,version:eo}}},{test:[/windows /i],describe(Xr){const eo=o.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,Xr),to=o.getWindowsVersionName(eo);return{name:j.Windows,version:eo,versionName:to}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(Xr){const eo={name:j.iOS},to=o.getSecondMatch(/(Version\/)(\d[\d.]+)/,Xr);return to&&(eo.version=to),eo}},{test:[/macintosh/i],describe(Xr){const eo=o.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,Xr).replace(/[_\s]/g,"."),to=o.getMacOSVersionName(eo),ro={name:j.MacOS,version:eo};return to&&(ro.versionName=to),ro}},{test:[/(ipod|iphone|ipad)/i],describe(Xr){const eo=o.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,Xr).replace(/[_\s]/g,".");return{name:j.iOS,version:eo}}},{test(Xr){const eo=!Xr.test(/like android/i),to=Xr.test(/android/i);return eo&&to},describe(Xr){const eo=o.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,Xr),to=o.getAndroidVersionName(eo),ro={name:j.Android,version:eo};return to&&(ro.versionName=to),ro}},{test:[/(web|hpw)[o0]s/i],describe(Xr){const eo=o.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,Xr),to={name:j.WebOS};return eo&&eo.length&&(to.version=eo),to}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(Xr){const eo=o.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,Xr)||o.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,Xr)||o.getFirstMatch(/\bbb(\d+)/i,Xr);return{name:j.BlackBerry,version:eo}}},{test:[/bada/i],describe(Xr){const eo=o.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,Xr);return{name:j.Bada,version:eo}}},{test:[/tizen/i],describe(Xr){const eo=o.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,Xr);return{name:j.Tizen,version:eo}}},{test:[/linux/i],describe(){return{name:j.Linux}}},{test:[/CrOS/],describe(){return{name:j.ChromeOS}}},{test:[/PlayStation 4/],describe(Xr){const eo=o.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,Xr);return{name:j.PlayStation4,version:eo}}}],ht=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(Xr){const eo=o.getFirstMatch(/(can-l01)/i,Xr)&&"Nova",to={type:N.mobile,vendor:"Huawei"};return eo&&(to.model=eo),to}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:N.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:N.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:N.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:N.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:N.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:N.tablet}}},{test(Xr){const eo=Xr.test(/ipod|iphone/i),to=Xr.test(/like (ipod|iphone)/i);return eo&&!to},describe(Xr){const eo=o.getFirstMatch(/(ipod|iphone)/i,Xr);return{type:N.mobile,vendor:"Apple",model:eo}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:N.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:N.mobile}}},{test(Xr){return Xr.getBrowserName(!0)==="blackberry"},describe(){return{type:N.mobile,vendor:"BlackBerry"}}},{test(Xr){return Xr.getBrowserName(!0)==="bada"},describe(){return{type:N.mobile}}},{test(Xr){return Xr.getBrowserName()==="windows phone"},describe(){return{type:N.mobile,vendor:"Microsoft"}}},{test(Xr){const eo=Number(String(Xr.getOSVersion()).split(".")[0]);return Xr.getOSName(!0)==="android"&&eo>=3},describe(){return{type:N.tablet}}},{test(Xr){return Xr.getOSName(!0)==="android"},describe(){return{type:N.mobile}}},{test(Xr){return Xr.getOSName(!0)==="macos"},describe(){return{type:N.desktop,vendor:"Apple"}}},{test(Xr){return Xr.getOSName(!0)==="windows"},describe(){return{type:N.desktop}}},{test(Xr){return Xr.getOSName(!0)==="linux"},describe(){return{type:N.desktop}}},{test(Xr){return Xr.getOSName(!0)==="playstation 4"},describe(){return{type:N.tv}}},{test(Xr){return Xr.getOSName(!0)==="roku"},describe(){return{type:N.tv}}}],bt=[{test(Xr){return Xr.getBrowserName(!0)==="microsoft edge"},describe(Xr){if(/\sedg\//i.test(Xr))return{name:L.Blink};const eo=o.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,Xr);return{name:L.EdgeHTML,version:eo}}},{test:[/trident/i],describe(Xr){const eo={name:L.Trident},to=o.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test(Xr){return Xr.test(/presto/i)},describe(Xr){const eo={name:L.Presto},to=o.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test(Xr){const eo=Xr.test(/gecko/i),to=Xr.test(/like gecko/i);return eo&&!to},describe(Xr){const eo={name:L.Gecko},to=o.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:L.Blink}}},{test:[/(apple)?webkit/i],describe(Xr){const eo={name:L.WebKit},to=o.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}}];class ke{constructor(eo,to=!1){if(eo==null||eo==="")throw new Error("UserAgent parameter can't be empty");this._ua=eo,this.parsedResult={},to!==!0&&this.parse()}getUA(){return this._ua}test(eo){return eo.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const eo=o.find(ft,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.browser=eo.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(eo){return eo?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const eo=o.find(wt,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.os=eo.describe(this.getUA())),this.parsedResult.os}getOSName(eo){const{name:to}=this.getOS();return eo?String(to).toLowerCase()||"":to||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(eo=!1){const{type:to}=this.getPlatform();return eo?String(to).toLowerCase()||"":to||""}parsePlatform(){this.parsedResult.platform={};const eo=o.find(ht,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.platform=eo.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(eo){return eo?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const eo=o.find(bt,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.engine=eo.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return o.assign({},this.parsedResult)}satisfies(eo){const to={};let ro=0;const no={};let io=0;if(Object.keys(eo).forEach(oo=>{const ao=eo[oo];typeof ao=="string"?(no[oo]=ao,io+=1):typeof ao=="object"&&(to[oo]=ao,ro+=1)}),ro>0){const oo=Object.keys(to),ao=o.find(oo,co=>this.isOS(co));if(ao){const co=this.satisfies(to[ao]);if(co!==void 0)return co}const so=o.find(oo,co=>this.isPlatform(co));if(so){const co=this.satisfies(to[so]);if(co!==void 0)return co}}if(io>0){const oo=Object.keys(no),ao=o.find(oo,so=>this.isBrowser(so,!0));if(ao!==void 0)return this.compareVersion(no[ao])}}isBrowser(eo,to=!1){const ro=this.getBrowserName().toLowerCase();let no=eo.toLowerCase();const io=o.getBrowserTypeByAlias(no);return to&&io&&(no=io.toLowerCase()),no===ro}compareVersion(eo){let to=[0],ro=eo,no=!1;const io=this.getBrowserVersion();if(typeof io=="string")return eo[0]===">"||eo[0]==="<"?(ro=eo.substr(1),eo[1]==="="?(no=!0,ro=eo.substr(2)):to=[],eo[0]===">"?to.push(1):to.push(-1)):eo[0]==="="?ro=eo.substr(1):eo[0]==="~"&&(no=!0,ro=eo.substr(1)),to.indexOf(o.compareVersions(io,ro,no))>-1}isOS(eo){return this.getOSName(!0)===String(eo).toLowerCase()}isPlatform(eo){return this.getPlatformType(!0)===String(eo).toLowerCase()}isEngine(eo){return this.getEngineName(!0)===String(eo).toLowerCase()}is(eo,to=!1){return this.isBrowser(eo,to)||this.isOS(eo)||this.isPlatform(eo)}some(eo=[]){return eo.some(to=>this.is(to))}}/*! + `,R$1=()=>Object.keys(localStorage).some(Xr=>Xr==="walletconnect"||Xr.startsWith("wc@2:")),_$1=()=>{if(R$1()){delete localStorage.walletconnect;for(const Xr in localStorage)Xr.startsWith("wc@2:")&&delete localStorage[Xr]}},j$2=()=>{var Xr;return window!=null&&window.starknet_argentX?(Xr=window==null?void 0:window.starknet_argentX)==null?void 0:Xr.isInAppBrowser:!1};let O$1=class extends T$2{constructor(eo={}){super(),l$1(this,"_wallet",null),l$1(this,"_options"),this._options=eo}available(){return!0}async ready(){return await this.ensureWallet(),this._wallet?this._wallet.isPreauthorized():!1}get id(){return"argentMobile"}get name(){return"Argent (mobile)"}get icon(){return{dark:u,light:u}}get wallet(){if(!this._wallet)throw new P$1;return this._wallet}async connect(){if(await this.ensureWallet(),!this._wallet)throw new U$2;const eo=this._wallet.account,to=await this.chainId();return{account:eo.address,chainId:to}}async disconnect(){var eo;if(await this._wallet.disable(),_$1(),!this.available()&&!this._wallet)throw new U$2;if(!((eo=this._wallet)!=null&&eo.isConnected))throw new S$1;this._wallet=null}async account(){if(!this._wallet||!this._wallet.account)throw new P$1;return this._wallet.account}async chainId(){if(!this._wallet||!this.wallet.account||!this._wallet.provider)throw new P$1;const eo=await this._wallet.provider.getChainId();return BigInt(eo)}async initEventListener(eo){if(!this._wallet)throw new P$1;this._wallet.on("accountsChanged",eo)}async removeEventListener(eo){if(!this._wallet)throw new P$1;this._wallet.off("accountsChanged",eo),this._wallet=null}async ensureWallet(){const{getStarknetWindowObject:eo}=await __vitePreload(async()=>{const{getStarknetWindowObject:vo}=await import("./index-8e228000-BM2OJ2QW.js");return{getStarknetWindowObject:vo}},[]),{chainId:to,projectId:ro,dappName:no,description:io,url:oo,icons:ao,provider:so,rpcUrl:co}=this._options,lo=s(),fo=co??(!to||to===constants_exports.NetworkName.SN_MAIN?lo.mainnet:lo.testnet),ho={chainId:to??constants_exports.NetworkName.SN_MAIN,name:no,projectId:ro??d$1,description:io,url:oo,icons:ao,provider:so,rpcUrl:fo};ro===d$1&&(console.log("========= NOTICE ========="),console.log("While your application will continue to function, we highly recommended"),console.log("signing up for your own API keys."),console.log("Go to WalletConnect Cloud (https://cloud.walletconnect.com) and create a new account."),console.log("Once your account is created, create a new project and collect the Project ID"),console.log("=========================="));const go=await eo(ho);if(!go)throw new A$2;this._wallet=go;const yo=this._wallet;await yo.enable(),yo.client.on("session_delete",()=>{_$1(),this._wallet=null,q$2(),document.dispatchEvent(new Event("wallet_disconnected"))})}};var g=Object.defineProperty,j$1=(Xr,eo,to)=>eo in Xr?g(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,N$1=(Xr,eo,to)=>(j$1(Xr,typeof eo!="symbol"?eo+"":eo,to),to);const d="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIiByeD0iOCIgZmlsbD0iYmxhY2siLz4KPHBhdGggZD0iTTE4LjQwMTggNy41NTU1NkgxMy41OTgyQzEzLjQzNzcgNy41NTU1NiAxMy4zMDkxIDcuNjg3NDcgMTMuMzA1NiA3Ljg1MTQzQzEzLjIwODUgMTIuNDYwMyAxMC44NDg0IDE2LjgzNDcgNi43ODYwOCAxOS45MzMxQzYuNjU3MTEgMjAuMDMxNCA2LjYyNzczIDIwLjIxNjIgNi43MjIwMiAyMC4zNDkzTDkuNTMyNTMgMjQuMzE5NkM5LjYyODE1IDI0LjQ1NDggOS44MTQ0NCAyNC40ODUzIDkuOTQ1NTggMjQuMzg2QzEyLjQ4NTYgMjIuNDYxMyAxNC41Mjg3IDIwLjEzOTUgMTYgMTcuNTY2QzE3LjQ3MTMgMjAuMTM5NSAxOS41MTQ1IDIyLjQ2MTMgMjIuMDU0NSAyNC4zODZDMjIuMTg1NiAyNC40ODUzIDIyLjM3MTkgMjQuNDU0OCAyMi40Njc2IDI0LjMxOTZMMjUuMjc4MSAyMC4zNDkzQzI1LjM3MjMgMjAuMjE2MiAyNS4zNDI5IDIwLjAzMTQgMjUuMjE0IDE5LjkzMzFDMjEuMTUxNiAxNi44MzQ3IDE4Ljc5MTUgMTIuNDYwMyAxOC42OTQ2IDcuODUxNDNDMTguNjkxMSA3LjY4NzQ3IDE4LjU2MjMgNy41NTU1NiAxOC40MDE4IDcuNTU1NTZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNMjQuNzIzNiAxMC40OTJMMjQuMjIzMSA4LjkyNDM5QzI0LjEyMTMgOC42MDYxNCAyMy44NzM0IDguMzU4MjQgMjMuNTU3NyA4LjI2MDIzTDIyLjAwMzkgNy43NzU5NUMyMS43ODk1IDcuNzA5MDYgMjEuNzg3MyA3LjQwMTc3IDIyLjAwMTEgNy4zMzIwMUwyMy41NDY5IDYuODI0NjZDMjMuODYwOSA2LjcyMTQ2IDI0LjEwNiA2LjQ2OTUyIDI0LjIwMjcgNi4xNTAxMUwyNC42Nzk4IDQuNTc1MDJDMjQuNzQ1OCA0LjM1NzA5IDI1LjA0ODkgNC4zNTQ3NyAyNS4xMTgzIDQuNTcxNTZMMjUuNjE4OCA2LjEzOTE1QzI1LjcyMDYgNi40NTc0IDI1Ljk2ODYgNi43MDUzMSAyNi4yODQyIDYuODAzOUwyNy44MzggNy4yODc2MUMyOC4wNTI0IDcuMzU0NSAyOC4wNTQ3IDcuNjYxNzkgMjcuODQwOCA3LjczMjEzTDI2LjI5NSA4LjIzOTQ4QzI1Ljk4MTEgOC4zNDIxIDI1LjczNiA4LjU5NDA0IDI1LjYzOTMgOC45MTQwMkwyNS4xNjIxIDEwLjQ4ODVDMjUuMDk2MSAxMC43MDY1IDI0Ljc5MyAxMC43MDg4IDI0LjcyMzYgMTAuNDkyWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",l="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlLXdpZHRoPSIxLjUiIHN0cm9rZT0iYmxhY2siPgogIDxwYXRoIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTkuODc5IDcuNTE5YzEuMTcxLTEuMDI1IDMuMDcxLTEuMDI1IDQuMjQyIDAgMS4xNzIgMS4wMjUgMS4xNzIgMi42ODcgMCAzLjcxMi0uMjAzLjE3OS0uNDMuMzI2LS42Ny40NDItLjc0NS4zNjEtMS40NS45OTktMS40NSAxLjgyN3YuNzVNMjEgMTJhOSA5IDAgMTEtMTggMCA5IDkgMCAwMTE4IDB6bS05IDUuMjVoLjAwOHYuMDA4SDEydi0uMDA4eiIgLz4KPC9zdmc+",h="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlLXdpZHRoPSIxLjUiIHN0cm9rZT0id2hpdGUiPgogIDxwYXRoIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTkuODc5IDcuNTE5YzEuMTcxLTEuMDI1IDMuMDcxLTEuMDI1IDQuMjQyIDAgMS4xNzIgMS4wMjUgMS4xNzIgMi42ODcgMCAzLjcxMi0uMjAzLjE3OS0uNDMuMzI2LS42Ny40NDItLjc0NS4zNjEtMS40NS45OTktMS40NSAxLjgyN3YuNzVNMjEgMTJhOSA5IDAgMTEtMTggMCA5IDkgMCAwMTE4IDB6bS05IDUuMjVoLjAwOHYuMDA4SDEydi0uMDA4eiIgLz4KPC9zdmc+Cg==";let L$1=class extends T$2{constructor({options:eo}){super(),N$1(this,"_wallet"),N$1(this,"_options"),this._options=eo}available(){return this.ensureWallet(),this._wallet!==void 0}async ready(){return this.ensureWallet(),this._wallet?await this._wallet.isPreauthorized():!1}async chainId(){if(this.ensureWallet(),!this._wallet)throw new P$1;const eo=await this._wallet.provider.getChainId();return BigInt(eo)}async onAccountsChanged(eo){let to;if(typeof eo=="string"?to=eo:to=eo[0],to){const ro=await this.chainId();this.emit("change",{account:to,chainId:ro})}else this.emit("disconnect")}onNetworkChanged(eo){switch(eo){case"SN_MAIN":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_MAIN)});break;case"SN_GOERLI":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_GOERLI)});break;case"mainnet-alpha":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_MAIN)});break;case"goerli-alpha":this.emit("change",{chainId:BigInt(constants_exports.StarknetChainId.SN_GOERLI)});break;default:this.emit("change",{});break}}async connect(){if(this.ensureWallet(),!this._wallet)throw new U$2;let eo;try{eo=await this._wallet.enable({starknetVersion:"v5"})}catch{throw new A$2}if(!this._wallet.isConnected||!eo)throw new A$2;this._wallet.on("accountsChanged",async no=>{await this.onAccountsChanged(no)}),this._wallet.on("networkChanged",no=>{this.onNetworkChanged(no)}),await this.onAccountsChanged(eo);const to=this._wallet.account.address,ro=await this.chainId();return this.emit("connect",{account:to,chainId:ro}),{account:to,chainId:ro}}async disconnect(){var eo;if(this.ensureWallet(),q$2(),!this.available())throw new U$2;if(!((eo=this._wallet)!=null&&eo.isConnected))throw new S$1}async account(){if(this.ensureWallet(),!this._wallet||!this._wallet.account)throw new P$1;return this._wallet.account}get id(){return this._options.id}get name(){if(!this._wallet)throw new P$1;return this._wallet.name}get icon(){var eo;return this._options.icon?this._options.icon:(eo=this._wallet)!=null&&eo.icon?{dark:this._wallet.icon,light:this._wallet.icon}:{dark:h,light:l}}get wallet(){if(!this._wallet)throw new P$1;return this._wallet}ensureWallet(){const eo=z$1(globalThis).filter(to=>to.id===this._options.id)[0];if(eo){const{provider:to}=this._options;to&&Object.assign(eo,{provider:to}),this._wallet=eo}}};function z$1(Xr){return Object.values(Object.getOwnPropertyNames(Xr).reduce((eo,to)=>{if(to.startsWith("starknet")){const ro=Xr[to];y$1(ro)&&!eo[ro.id]&&(eo[ro.id]=ro)}return eo},{}))}function y$1(Xr){try{return Xr&&["request","isConnected","provider","enable","isPreauthorized","on","off","version","id","name","icon"].every(eo=>eo in Xr)}catch{}return!1}var He=Object.defineProperty,qe=(Xr,eo,to)=>eo in Xr?He(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,ae=(Xr,eo,to)=>(qe(Xr,typeof eo!="symbol"?eo+"":eo,to),to),rt=Object.defineProperty,nt=(Xr,eo,to)=>eo in Xr?rt(Xr,eo,{enumerable:!0,configurable:!0,writable:!0,value:to}):Xr[eo]=to,it=(Xr,eo,to)=>(nt(Xr,eo+"",to),to),pe=(Xr,eo,to)=>{if(!eo.has(Xr))throw TypeError("Cannot "+to)},z=(Xr,eo,to)=>(pe(Xr,eo,"read from private field"),to?to.call(Xr):eo.get(Xr)),V=(Xr,eo,to)=>{if(eo.has(Xr))throw TypeError("Cannot add the same private member more than once");eo instanceof WeakSet?eo.add(Xr):eo.set(Xr,to)},ie=(Xr,eo,to,ro)=>(pe(Xr,eo,"write to private field"),eo.set(Xr,to),to),$=(Xr,eo,to)=>(pe(Xr,eo,"access private method"),to);const ot=[{id:"argentX",name:"Argent X",icon:"data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjQwIiBoZWlnaHQ9IjM2IiB2aWV3Qm94PSIwIDAgNDAgMzYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGQ9Ik0yNC43NTgyIC0zLjk3MzY0ZS0wN0gxNC42MjM4QzE0LjI4NTEgLTMuOTczNjRlLTA3IDE0LjAxMzggMC4yODExNzggMTQuMDA2NCAwLjYzMDY4M0MxMy44MDE3IDEwLjQ1NDkgOC44MjIzNCAxOS43NzkyIDAuMjUxODkzIDI2LjM4MzdDLTAuMDIwMjA0NiAyNi41OTMzIC0wLjA4MjE5NDYgMjYuOTg3MiAwLjExNjczNCAyNy4yNzA5TDYuMDQ2MjMgMzUuNzM0QzYuMjQ3OTYgMzYuMDIyIDYuNjQwOTkgMzYuMDg3IDYuOTE3NjYgMzUuODc1NEMxMi4yNzY1IDMxLjc3MjggMTYuNTg2OSAyNi44MjM2IDE5LjY5MSAyMS4zMzhDMjIuNzk1MSAyNi44MjM2IDI3LjEwNTcgMzEuNzcyOCAzMi40NjQ2IDM1Ljg3NTRDMzIuNzQxIDM2LjA4NyAzMy4xMzQxIDM2LjAyMiAzMy4zMzYxIDM1LjczNEwzOS4yNjU2IDI3LjI3MDlDMzkuNDY0MiAyNi45ODcyIDM5LjQwMjIgMjYuNTkzMyAzOS4xMzA0IDI2LjM4MzdDMzAuNTU5NyAxOS43NzkyIDI1LjU4MDQgMTAuNDU0OSAyNS4zNzU5IDAuNjMwNjgzQzI1LjM2ODUgMC4yODExNzggMjUuMDk2OSAtMy45NzM2NGUtMDcgMjQuNzU4MiAtMy45NzM2NGUtMDdaIiBmaWxsPSIjRkY4NzVCIi8+Cjwvc3ZnPgo=",downloads:{chrome:"https://chrome.google.com/webstore/detail/argent-x-starknet-wallet/dlcobpjiigpikoobohmabehhmhfoodbb",firefox:"https://addons.mozilla.org/en-US/firefox/addon/argent-x"}},{id:"braavos",name:"Braavos",icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgdmlld0JveD0iMCAwIDEwMCAxMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgICA8cGF0aAogICAgICAgIGQ9Ik02Mi43MDUgMTMuOTExNkM2Mi44MzU5IDE0LjEzMzMgNjIuNjYyMSAxNC40MDcgNjIuNDAzOSAxNC40MDdDNTcuMTgwNyAxNC40MDcgNTIuOTM0OCAxOC41NDI3IDUyLjgzNTEgMjMuNjgxN0M1MS4wNDY1IDIzLjM0NzcgNDkuMTkzMyAyMy4zMjI2IDQ3LjM2MjYgMjMuNjMxMUM0Ny4yMzYxIDE4LjUxNTYgNDMuMDAwOSAxNC40MDcgMzcuNzk0OCAxNC40MDdDMzcuNTM2NSAxNC40MDcgMzcuMzYyNSAxNC4xMzMxIDM3LjQ5MzUgMTMuOTExMkM0MC4wMjE3IDkuNjI4MDkgNDQuNzIwNCA2Ljc1IDUwLjA5OTEgNi43NUM1NS40NzgxIDYuNzUgNjAuMTc2OSA5LjYyODI2IDYyLjcwNSAxMy45MTE2WiIKICAgICAgICBmaWxsPSJ1cmwoI3BhaW50MF9saW5lYXJfMzcyXzQwMjU5KSIgLz4KICAgIDxwYXRoCiAgICAgICAgZD0iTTc4Ljc2MDYgNDUuODcxOEM4MC4yNzI1IDQ2LjMyOTcgODEuNzAyNSA0NS4wMDU1IDgxLjE3MTQgNDMuNTIyMkM3Ni40MTM3IDMwLjIzMzQgNjEuMzkxMSAyNC44MDM5IDUwLjAyNzcgMjQuODAzOUMzOC42NDQyIDI0LjgwMzkgMjMuMjg2OCAzMC40MDcgMTguODc1NCA0My41OTEyQzE4LjM4MjQgNDUuMDY0NSAxOS44MDgzIDQ2LjM0NDYgMjEuMjk3OCA0NS44ODgxTDQ4Ljg3MiAzNy40MzgxQzQ5LjUzMzEgMzcuMjM1NSA1MC4yMzk5IDM3LjIzNDQgNTAuOTAxNyAzNy40MzQ4TDc4Ljc2MDYgNDUuODcxOFoiCiAgICAgICAgZmlsbD0idXJsKCNwYWludDFfbGluZWFyXzM3Ml80MDI1OSkiIC8+CiAgICA8cGF0aAogICAgICAgIGQ9Ik0xOC44MTMyIDQ4LjE3MDdMNDguODkzNSAzOS4wNDcyQzQ5LjU1MDYgMzguODQ3OCA1MC4yNTI0IDM4Ljg0NzMgNTAuOTA5OCAzOS4wNDU2TDgxLjE3ODEgNDguMTc1MkM4My42OTEyIDQ4LjkzMzIgODUuNDExIDUxLjI0ODMgODUuNDExIDUzLjg3MzVWODEuMjIzM0M4NS4yOTQ0IDg3Ljg5OTEgNzkuMjk3NyA5My4yNSA3Mi42MjQ1IDkzLjI1SDYxLjU0MDZDNjAuNDQ0OSA5My4yNSA1OS41NTc3IDkyLjM2MzcgNTkuNTU3NyA5MS4yNjhWODEuNjc4OUM1OS41NTc3IDc3LjkwMzEgNjEuNzkyMSA3NC40ODU1IDY1LjI0OTggNzIuOTcyOUM2OS44ODQ5IDcwLjk0NTQgNzUuMzY4MSA2OC4yMDI4IDc2LjM5OTQgNjIuNjk5MkM3Ni43MzIzIDYwLjkyMjkgNzUuNTc0MSA1OS4yMDk0IDczLjgwMjQgNTguODU3M0M2OS4zMjI2IDU3Ljk2NjcgNjQuMzU2MiA1OC4zMTA3IDYwLjE1NjQgNjAuMTg5M0M1NS4zODg3IDYyLjMyMTkgNTQuMTQxNSA2NS44Njk0IDUzLjY3OTcgNzAuNjMzN0w1My4xMjAxIDc1Ljc2NjJDNTIuOTQ5MSA3Ny4zMzQ5IDUxLjQ3ODUgNzguNTM2NiA0OS45MDE0IDc4LjUzNjZDNDguMjY5OSA3OC41MzY2IDQ3LjA0NjUgNzcuMjk0IDQ2Ljg2OTYgNzUuNjcxMkw0Ni4zMjA0IDcwLjYzMzdDNDUuOTI0OSA2Ni41NTI5IDQ1LjIwNzkgNjIuNTg4NyA0MC45ODk1IDYwLjcwMThDMzYuMTc3NiA1OC41NDk0IDMxLjM0MTkgNTcuODM0NyAyNi4xOTc2IDU4Ljg1NzNDMjQuNDI2IDU5LjIwOTQgMjMuMjY3OCA2MC45MjI5IDIzLjYwMDcgNjIuNjk5MkMyNC42NDEgNjguMjUwNyAzMC4wODEyIDcwLjkzMDUgMzQuNzUwMyA3Mi45NzI5QzM4LjIwOCA3NC40ODU1IDQwLjQ0MjQgNzcuOTAzMSA0MC40NDI0IDgxLjY3ODlWOTEuMjY2M0M0MC40NDI0IDkyLjM2MiAzOS41NTU1IDkzLjI1IDM4LjQ1OTkgOTMuMjVIMjcuMzc1NkMyMC43MDI0IDkzLjI1IDE0LjcwNTcgODcuODk5MSAxNC41ODkxIDgxLjIyMzNWNTMuODY2M0MxNC41ODkxIDUxLjI0NDYgMTYuMzA0NSA0OC45MzE2IDE4LjgxMzIgNDguMTcwN1oiCiAgICAgICAgZmlsbD0idXJsKCNwYWludDJfbGluZWFyXzM3Ml80MDI1OSkiIC8+CiAgICA8ZGVmcz4KICAgICAgICA8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfMzcyXzQwMjU5IiB4MT0iNDkuMzA1NyIgeTE9IjIuMDc5IiB4Mj0iODAuMzYyNyIgeTI9IjkzLjY1OTciCiAgICAgICAgICAgIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KICAgICAgICAgICAgPHN0b3Agc3RvcC1jb2xvcj0iI0Y1RDQ1RSIgLz4KICAgICAgICAgICAgPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjRkY5NjAwIiAvPgogICAgICAgIDwvbGluZWFyR3JhZGllbnQ+CiAgICAgICAgPGxpbmVhckdyYWRpZW50IGlkPSJwYWludDFfbGluZWFyXzM3Ml80MDI1OSIgeDE9IjQ5LjMwNTciIHkxPSIyLjA3OSIgeDI9IjgwLjM2MjciIHkyPSI5My42NTk3IgogICAgICAgICAgICBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CiAgICAgICAgICAgIDxzdG9wIHN0b3AtY29sb3I9IiNGNUQ0NUUiIC8+CiAgICAgICAgICAgIDxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0ZGOTYwMCIgLz4KICAgICAgICA8L2xpbmVhckdyYWRpZW50PgogICAgICAgIDxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQyX2xpbmVhcl8zNzJfNDAyNTkiIHgxPSI0OS4zMDU3IiB5MT0iMi4wNzkiIHgyPSI4MC4zNjI3IiB5Mj0iOTMuNjU5NyIKICAgICAgICAgICAgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICAgICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjRjVENDVFIiAvPgogICAgICAgICAgICA8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGRjk2MDAiIC8+CiAgICAgICAgPC9saW5lYXJHcmFkaWVudD4KICAgIDwvZGVmcz4KPC9zdmc+",downloads:{chrome:"https://chrome.google.com/webstore/detail/braavos-wallet/jnlgamecbpmbajjfhmmmlhejkemejdma",firefox:"https://addons.mozilla.org/en-US/firefox/addon/braavos-wallet",edge:"https://microsoftedge.microsoft.com/addons/detail/braavos-wallet/hkkpjehhcnhgefhbdcgfkeegglpjchdc"}}],st=()=>`${Date.now()}-${Math.floor(Math.random()*(9e12-1))+1e12}`,ye=Xr=>{for(let eo=Xr.length-1;eo>0;eo--){const to=Math.floor(Math.random()*(eo+1));[Xr[eo],Xr[to]]=[Xr[to],Xr[eo]]}return Xr};function ce(...Xr){return eo=>Xr.reduce((to,ro)=>to.then(ro),Promise.resolve(eo))}var W,S,H,we,_e,X,te;class at{constructor(eo){V(this,we),V(this,X),V(this,W,!1),V(this,S,void 0),V(this,H,void 0),it(this,"value"),ie(this,H,eo),$(this,X,te).call(this)}set(eo){return!z(this,W)&&!$(this,X,te).call(this)?!1:(this.delete(),this.value=eo,eo&&(ie(this,S,`${z(this,H)}-${st()}`),localStorage.setItem(z(this,S),eo)),!0)}get(){return $(this,we,_e).call(this),this.value}delete(){return!z(this,W)&&!$(this,X,te).call(this)?!1:(this.value=null,z(this,S)&&localStorage.removeItem(z(this,S)),!0)}}W=new WeakMap,S=new WeakMap,H=new WeakMap,we=new WeakSet,_e=function(){this.value&&this.set(this.value)},X=new WeakSet,te=function(){try{!z(this,W)&&typeof window<"u"&&(ie(this,S,Object.keys(localStorage).find(Xr=>Xr.startsWith(z(this,H)))),ie(this,W,!0),z(this,S)&&this.set(localStorage.getItem(z(this,S))))}catch(Xr){console.warn(Xr)}return z(this,W)};function le(Xr,eo){var to,ro;if((to=eo==null?void 0:eo.include)!=null&&to.length){const no=new Set(eo.include);return Xr.filter(io=>no.has(io.id))}if((ro=eo==null?void 0:eo.exclude)!=null&&ro.length){const no=new Set(eo.exclude);return Xr.filter(io=>!no.has(io.id))}return Xr}const ve=async Xr=>{const eo=await Promise.all(Xr.map(to=>to.isPreauthorized().catch(()=>!1)));return Xr.filter((to,ro)=>eo[ro])},ct=Xr=>{try{return Xr&&["request","isConnected","provider","enable","isPreauthorized","on","off","version","id","name","icon"].every(eo=>eo in Xr)}catch{}return!1};function de(Xr,eo){return Object.values(Object.getOwnPropertyNames(Xr).reduce((to,ro)=>{if(ro.startsWith("starknet")){const no=Xr[ro];eo(no)&&!to[no.id]&&(to[no.id]=no)}return to},{}))}const ue=(Xr,eo)=>{if(eo&&Array.isArray(eo)){Xr.sort((ro,no)=>eo.indexOf(ro.id)-eo.indexOf(no.id));const to=Xr.length-eo.length;return[...Xr.slice(to),...ye(Xr.slice(0,to))]}else return ye(Xr)},lt=typeof window<"u"?window:{},dt={windowObject:lt,isWalletObject:ct,storageFactoryImplementation:Xr=>new at(Xr)};function ut(Xr={}){const{storageFactoryImplementation:eo,windowObject:to,isWalletObject:ro}={...dt,...Xr},no=eo("gsw-last");return{getAvailableWallets:async(io={})=>{const oo=de(to,ro);return ce(ao=>le(ao,io),ao=>ue(ao,io.sort))(oo)},getPreAuthorizedWallets:async(io={})=>{const oo=de(to,ro);return ce(ao=>ve(ao),ao=>le(ao,io),ao=>ue(ao,io.sort))(oo)},getDiscoveryWallets:async(io={})=>ce(oo=>le(oo,io),oo=>ue(oo,io.sort))(ot),getLastConnectedWallet:async()=>{const io=no.get(),oo=de(to,ro).find(so=>so.id===io),[ao]=await ve(oo?[oo]:[]);return ao||(no.delete(),null)},enable:async(io,oo)=>{if(await io.enable(oo??{starknetVersion:"v5"}),!io.isConnected)throw new Error("Failed to connect to wallet");return no.set(io.id),io},disconnect:async({clearLastWallet:io}={})=>{io&&no.delete()}}}const re=ut(),gt={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},Le={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},N={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},j={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},L={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class o{static getFirstMatch(eo,to){const ro=to.match(eo);return ro&&ro.length>0&&ro[1]||""}static getSecondMatch(eo,to){const ro=to.match(eo);return ro&&ro.length>1&&ro[2]||""}static matchAndReturnConst(eo,to,ro){if(eo.test(to))return ro}static getWindowsVersionName(eo){switch(eo){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(eo){const to=eo.split(".").splice(0,2).map(ro=>parseInt(ro,10)||0);if(to.push(0),to[0]===10)switch(to[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(eo){const to=eo.split(".").splice(0,2).map(ro=>parseInt(ro,10)||0);if(to.push(0),!(to[0]===1&&to[1]<5)){if(to[0]===1&&to[1]<6)return"Cupcake";if(to[0]===1&&to[1]>=6)return"Donut";if(to[0]===2&&to[1]<2)return"Eclair";if(to[0]===2&&to[1]===2)return"Froyo";if(to[0]===2&&to[1]>2)return"Gingerbread";if(to[0]===3)return"Honeycomb";if(to[0]===4&&to[1]<1)return"Ice Cream Sandwich";if(to[0]===4&&to[1]<4)return"Jelly Bean";if(to[0]===4&&to[1]>=4)return"KitKat";if(to[0]===5)return"Lollipop";if(to[0]===6)return"Marshmallow";if(to[0]===7)return"Nougat";if(to[0]===8)return"Oreo";if(to[0]===9)return"Pie"}}static getVersionPrecision(eo){return eo.split(".").length}static compareVersions(eo,to,ro=!1){const no=o.getVersionPrecision(eo),io=o.getVersionPrecision(to);let oo=Math.max(no,io),ao=0;const so=o.map([eo,to],co=>{const lo=oo-o.getVersionPrecision(co),fo=co+new Array(lo+1).join(".0");return o.map(fo.split("."),ho=>new Array(20-ho.length).join("0")+ho).reverse()});for(ro&&(ao=oo-Math.min(no,io)),oo-=1;oo>=ao;){if(so[0][oo]>so[1][oo])return 1;if(so[0][oo]===so[1][oo]){if(oo===ao)return 0;oo-=1}else if(so[0][oo]{ro[ao]=oo[ao]})}return eo}static getBrowserAlias(eo){return gt[eo]}static getBrowserTypeByAlias(eo){return Le[eo]||""}}const M=/version\/(\d+(\.?_?\d+)+)/i,ft=[{test:[/googlebot/i],describe(Xr){const eo={name:"Googlebot"},to=o.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/opera/i],describe(Xr){const eo={name:"Opera"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/opr\/|opios/i],describe(Xr){const eo={name:"Opera"},to=o.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/SamsungBrowser/i],describe(Xr){const eo={name:"Samsung Internet for Android"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/Whale/i],describe(Xr){const eo={name:"NAVER Whale Browser"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/MZBrowser/i],describe(Xr){const eo={name:"MZ Browser"},to=o.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/focus/i],describe(Xr){const eo={name:"Focus"},to=o.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/swing/i],describe(Xr){const eo={name:"Swing"},to=o.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/coast/i],describe(Xr){const eo={name:"Opera Coast"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(Xr){const eo={name:"Opera Touch"},to=o.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/yabrowser/i],describe(Xr){const eo={name:"Yandex Browser"},to=o.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/ucbrowser/i],describe(Xr){const eo={name:"UC Browser"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/Maxthon|mxios/i],describe(Xr){const eo={name:"Maxthon"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/epiphany/i],describe(Xr){const eo={name:"Epiphany"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/puffin/i],describe(Xr){const eo={name:"Puffin"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/sleipnir/i],describe(Xr){const eo={name:"Sleipnir"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/k-meleon/i],describe(Xr){const eo={name:"K-Meleon"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/micromessenger/i],describe(Xr){const eo={name:"WeChat"},to=o.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/qqbrowser/i],describe(Xr){const eo={name:/qqbrowserlite/i.test(Xr)?"QQ Browser Lite":"QQ Browser"},to=o.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/msie|trident/i],describe(Xr){const eo={name:"Internet Explorer"},to=o.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/\sedg\//i],describe(Xr){const eo={name:"Microsoft Edge"},to=o.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/edg([ea]|ios)/i],describe(Xr){const eo={name:"Microsoft Edge"},to=o.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/vivaldi/i],describe(Xr){const eo={name:"Vivaldi"},to=o.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/seamonkey/i],describe(Xr){const eo={name:"SeaMonkey"},to=o.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/sailfish/i],describe(Xr){const eo={name:"Sailfish"},to=o.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,Xr);return to&&(eo.version=to),eo}},{test:[/silk/i],describe(Xr){const eo={name:"Amazon Silk"},to=o.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/phantom/i],describe(Xr){const eo={name:"PhantomJS"},to=o.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/slimerjs/i],describe(Xr){const eo={name:"SlimerJS"},to=o.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(Xr){const eo={name:"BlackBerry"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/(web|hpw)[o0]s/i],describe(Xr){const eo={name:"WebOS Browser"},to=o.getFirstMatch(M,Xr)||o.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/bada/i],describe(Xr){const eo={name:"Bada"},to=o.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/tizen/i],describe(Xr){const eo={name:"Tizen"},to=o.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/qupzilla/i],describe(Xr){const eo={name:"QupZilla"},to=o.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/firefox|iceweasel|fxios/i],describe(Xr){const eo={name:"Firefox"},to=o.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/electron/i],describe(Xr){const eo={name:"Electron"},to=o.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/MiuiBrowser/i],describe(Xr){const eo={name:"Miui"},to=o.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/chromium/i],describe(Xr){const eo={name:"Chromium"},to=o.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,Xr)||o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/chrome|crios|crmo/i],describe(Xr){const eo={name:"Chrome"},to=o.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/GSA/i],describe(Xr){const eo={name:"Google Search"},to=o.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test(Xr){const eo=!Xr.test(/like android/i),to=Xr.test(/android/i);return eo&&to},describe(Xr){const eo={name:"Android Browser"},to=o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/playstation 4/i],describe(Xr){const eo={name:"PlayStation 4"},to=o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/safari|applewebkit/i],describe(Xr){const eo={name:"Safari"},to=o.getFirstMatch(M,Xr);return to&&(eo.version=to),eo}},{test:[/.*/i],describe(Xr){const eo=/^(.*)\/(.*) /,to=/^(.*)\/(.*)[ \t]\((.*)/,ro=Xr.search("\\(")!==-1?to:eo;return{name:o.getFirstMatch(ro,Xr),version:o.getSecondMatch(ro,Xr)}}}],wt=[{test:[/Roku\/DVP/],describe(Xr){const eo=o.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,Xr);return{name:j.Roku,version:eo}}},{test:[/windows phone/i],describe(Xr){const eo=o.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,Xr);return{name:j.WindowsPhone,version:eo}}},{test:[/windows /i],describe(Xr){const eo=o.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,Xr),to=o.getWindowsVersionName(eo);return{name:j.Windows,version:eo,versionName:to}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(Xr){const eo={name:j.iOS},to=o.getSecondMatch(/(Version\/)(\d[\d.]+)/,Xr);return to&&(eo.version=to),eo}},{test:[/macintosh/i],describe(Xr){const eo=o.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,Xr).replace(/[_\s]/g,"."),to=o.getMacOSVersionName(eo),ro={name:j.MacOS,version:eo};return to&&(ro.versionName=to),ro}},{test:[/(ipod|iphone|ipad)/i],describe(Xr){const eo=o.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,Xr).replace(/[_\s]/g,".");return{name:j.iOS,version:eo}}},{test(Xr){const eo=!Xr.test(/like android/i),to=Xr.test(/android/i);return eo&&to},describe(Xr){const eo=o.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,Xr),to=o.getAndroidVersionName(eo),ro={name:j.Android,version:eo};return to&&(ro.versionName=to),ro}},{test:[/(web|hpw)[o0]s/i],describe(Xr){const eo=o.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,Xr),to={name:j.WebOS};return eo&&eo.length&&(to.version=eo),to}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(Xr){const eo=o.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,Xr)||o.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,Xr)||o.getFirstMatch(/\bbb(\d+)/i,Xr);return{name:j.BlackBerry,version:eo}}},{test:[/bada/i],describe(Xr){const eo=o.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,Xr);return{name:j.Bada,version:eo}}},{test:[/tizen/i],describe(Xr){const eo=o.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,Xr);return{name:j.Tizen,version:eo}}},{test:[/linux/i],describe(){return{name:j.Linux}}},{test:[/CrOS/],describe(){return{name:j.ChromeOS}}},{test:[/PlayStation 4/],describe(Xr){const eo=o.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,Xr);return{name:j.PlayStation4,version:eo}}}],ht=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(Xr){const eo=o.getFirstMatch(/(can-l01)/i,Xr)&&"Nova",to={type:N.mobile,vendor:"Huawei"};return eo&&(to.model=eo),to}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:N.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:N.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:N.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:N.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:N.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:N.tablet}}},{test(Xr){const eo=Xr.test(/ipod|iphone/i),to=Xr.test(/like (ipod|iphone)/i);return eo&&!to},describe(Xr){const eo=o.getFirstMatch(/(ipod|iphone)/i,Xr);return{type:N.mobile,vendor:"Apple",model:eo}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:N.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:N.mobile}}},{test(Xr){return Xr.getBrowserName(!0)==="blackberry"},describe(){return{type:N.mobile,vendor:"BlackBerry"}}},{test(Xr){return Xr.getBrowserName(!0)==="bada"},describe(){return{type:N.mobile}}},{test(Xr){return Xr.getBrowserName()==="windows phone"},describe(){return{type:N.mobile,vendor:"Microsoft"}}},{test(Xr){const eo=Number(String(Xr.getOSVersion()).split(".")[0]);return Xr.getOSName(!0)==="android"&&eo>=3},describe(){return{type:N.tablet}}},{test(Xr){return Xr.getOSName(!0)==="android"},describe(){return{type:N.mobile}}},{test(Xr){return Xr.getOSName(!0)==="macos"},describe(){return{type:N.desktop,vendor:"Apple"}}},{test(Xr){return Xr.getOSName(!0)==="windows"},describe(){return{type:N.desktop}}},{test(Xr){return Xr.getOSName(!0)==="linux"},describe(){return{type:N.desktop}}},{test(Xr){return Xr.getOSName(!0)==="playstation 4"},describe(){return{type:N.tv}}},{test(Xr){return Xr.getOSName(!0)==="roku"},describe(){return{type:N.tv}}}],bt=[{test(Xr){return Xr.getBrowserName(!0)==="microsoft edge"},describe(Xr){if(/\sedg\//i.test(Xr))return{name:L.Blink};const eo=o.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,Xr);return{name:L.EdgeHTML,version:eo}}},{test:[/trident/i],describe(Xr){const eo={name:L.Trident},to=o.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test(Xr){return Xr.test(/presto/i)},describe(Xr){const eo={name:L.Presto},to=o.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test(Xr){const eo=Xr.test(/gecko/i),to=Xr.test(/like gecko/i);return eo&&!to},describe(Xr){const eo={name:L.Gecko},to=o.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:L.Blink}}},{test:[/(apple)?webkit/i],describe(Xr){const eo={name:L.WebKit},to=o.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,Xr);return to&&(eo.version=to),eo}}];class ke{constructor(eo,to=!1){if(eo==null||eo==="")throw new Error("UserAgent parameter can't be empty");this._ua=eo,this.parsedResult={},to!==!0&&this.parse()}getUA(){return this._ua}test(eo){return eo.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const eo=o.find(ft,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.browser=eo.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(eo){return eo?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const eo=o.find(wt,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.os=eo.describe(this.getUA())),this.parsedResult.os}getOSName(eo){const{name:to}=this.getOS();return eo?String(to).toLowerCase()||"":to||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(eo=!1){const{type:to}=this.getPlatform();return eo?String(to).toLowerCase()||"":to||""}parsePlatform(){this.parsedResult.platform={};const eo=o.find(ht,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.platform=eo.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(eo){return eo?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const eo=o.find(bt,to=>{if(typeof to.test=="function")return to.test(this);if(to.test instanceof Array)return to.test.some(ro=>this.test(ro));throw new Error("Browser's test function is not valid")});return eo&&(this.parsedResult.engine=eo.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return o.assign({},this.parsedResult)}satisfies(eo){const to={};let ro=0;const no={};let io=0;if(Object.keys(eo).forEach(oo=>{const ao=eo[oo];typeof ao=="string"?(no[oo]=ao,io+=1):typeof ao=="object"&&(to[oo]=ao,ro+=1)}),ro>0){const oo=Object.keys(to),ao=o.find(oo,co=>this.isOS(co));if(ao){const co=this.satisfies(to[ao]);if(co!==void 0)return co}const so=o.find(oo,co=>this.isPlatform(co));if(so){const co=this.satisfies(to[so]);if(co!==void 0)return co}}if(io>0){const oo=Object.keys(no),ao=o.find(oo,so=>this.isBrowser(so,!0));if(ao!==void 0)return this.compareVersion(no[ao])}}isBrowser(eo,to=!1){const ro=this.getBrowserName().toLowerCase();let no=eo.toLowerCase();const io=o.getBrowserTypeByAlias(no);return to&&io&&(no=io.toLowerCase()),no===ro}compareVersion(eo){let to=[0],ro=eo,no=!1;const io=this.getBrowserVersion();if(typeof io=="string")return eo[0]===">"||eo[0]==="<"?(ro=eo.substr(1),eo[1]==="="?(no=!0,ro=eo.substr(2)):to=[],eo[0]===">"?to.push(1):to.push(-1)):eo[0]==="="?ro=eo.substr(1):eo[0]==="~"&&(no=!0,ro=eo.substr(1)),to.indexOf(o.compareVersions(io,ro,no))>-1}isOS(eo){return this.getOSName(!0)===String(eo).toLowerCase()}isPlatform(eo){return this.getPlatformType(!0)===String(eo).toLowerCase()}isEngine(eo){return this.getEngineName(!0)===String(eo).toLowerCase()}is(eo,to=!1){return this.isBrowser(eo,to)||this.isOS(eo)||this.isPlatform(eo)}some(eo=[]){return eo.some(to=>this.is(to))}}/*! * Bowser - a browser detector * https://github.com/lancedikson/bowser * MIT License | (c) Dustin Diaz 2012-2015 diff --git a/assets/nodecrypto-Co9-WRDE.js b/assets/nodecrypto-BXD6e4iz.js similarity index 64% rename from assets/nodecrypto-Co9-WRDE.js rename to assets/nodecrypto-BXD6e4iz.js index 56aeab2..e5b4481 100644 --- a/assets/nodecrypto-Co9-WRDE.js +++ b/assets/nodecrypto-BXD6e4iz.js @@ -1 +1 @@ -import{r as n,B as y}from"./index-CiyH7SV9.js";import{c as p}from"./utils-D-KHXRuV.js";var r=n();const m=async t=>{const{content:o,publicKey:i,privateKey:s}=t,c=r.createPrivateKey({key:p({uncompressedPrivateKeyHex:s,compressedPublicKeyHex:i}),format:"jwk"}),e=r.createSign("SHA256");return e.write(y.from(o)),e.end(),e.sign(c,"hex")};export{m as signWithApiKey}; +import{r as n,B as y}from"./index-CqoM6a8-.js";import{c as p}from"./utils-C3TScgcd.js";var r=n();const m=async t=>{const{content:o,publicKey:i,privateKey:s}=t,c=r.createPrivateKey({key:p({uncompressedPrivateKeyHex:s,compressedPublicKeyHex:i}),format:"jwk"}),e=r.createSign("SHA256");return e.write(y.from(o)),e.end(),e.sign(c,"hex")};export{m as signWithApiKey}; diff --git a/assets/purejs-IJPcfd_M.js b/assets/purejs-BONB21cl.js similarity index 92% rename from assets/purejs-IJPcfd_M.js rename to assets/purejs-BONB21cl.js index 1eb6c84..15678a6 100644 --- a/assets/purejs-IJPcfd_M.js +++ b/assets/purejs-BONB21cl.js @@ -1 +1 @@ -import{F as n,c as s,s as i,u as r,b as o}from"./index-CiyH7SV9.js";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=n(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),g=t.create(BigInt("-3")),d=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),c=s({a:g,b:d,Fp:t,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},i),u=async f=>{const a=c.getPublicKey(f.privateKey,!0),e=r(a);if(e!=f.publicKey)throw new Error(`Bad API key. Expected to get public key ${f.publicKey}, got ${e}`);const b=o().update(f.content).digest();return c.sign(b,f.privateKey).toDERHex()};export{u as signWithApiKey}; +import{F as n,c as s,s as i,u as r,b as o}from"./index-CqoM6a8-.js";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=n(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),g=t.create(BigInt("-3")),d=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),c=s({a:g,b:d,Fp:t,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},i),u=async f=>{const a=c.getPublicKey(f.privateKey,!0),e=r(a);if(e!=f.publicKey)throw new Error(`Bad API key. Expected to get public key ${f.publicKey}, got ${e}`);const b=o().update(f.content).digest();return c.sign(b,f.privateKey).toDERHex()};export{u as signWithApiKey}; diff --git a/assets/utils-D-KHXRuV.js b/assets/utils-C3TScgcd.js similarity index 98% rename from assets/utils-D-KHXRuV.js rename to assets/utils-C3TScgcd.js index 1bce8d5..660ffa2 100644 --- a/assets/utils-D-KHXRuV.js +++ b/assets/utils-C3TScgcd.js @@ -1,4 +1,4 @@ -import{a as d,h as B,D as w}from"./index-CiyH7SV9.js";/** +import{a as d,h as B,D as w}from"./index-CqoM6a8-.js";/** * Code modified from https://github.com/google/tink/blob/6f74b99a2bfe6677e3670799116a57268fd067fa/javascript/subtle/bytes.ts * * @license diff --git a/assets/webcrypto-3I5ubJVL.js b/assets/webcrypto-6IU6aAco.js similarity index 90% rename from assets/webcrypto-3I5ubJVL.js rename to assets/webcrypto-6IU6aAco.js index 79361fb..a217c97 100644 --- a/assets/webcrypto-3I5ubJVL.js +++ b/assets/webcrypto-6IU6aAco.js @@ -1 +1 @@ -import{c}from"./utils-D-KHXRuV.js";import{u as i}from"./index-CiyH7SV9.js";const p=async n=>{const{content:e,publicKey:s,privateKey:t}=n,o=await g({uncompressedPrivateKeyHex:t,compressedPublicKeyHex:s});return await l({key:o,content:e})};async function g(n){const{uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s}=n,t=c({uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s});return await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}async function l(n){const{key:e,content:s}=n,t=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,new TextEncoder().encode(s)),o=u(new Uint8Array(t));return i(o)}function u(n){if(n.length%2!=0||n.length==0||n.length>132)throw new Error("Invalid IEEE P1363 signature encoding. Length: "+n.length);const e=a(n.subarray(0,n.length/2)),s=a(n.subarray(n.length/2,n.length));let t=0;const o=2+e.length+1+1+s.length;let r;return o>=128?(r=new Uint8Array(o+3),r[t++]=48,r[t++]=129,r[t++]=o):(r=new Uint8Array(o+2),r[t++]=48,r[t++]=o),r[t++]=2,r[t++]=e.length,r.set(e,t),t+=e.length,r[t++]=2,r[t++]=s.length,r.set(s,t),r}function a(n){let e=0;for(;e{const{content:e,publicKey:s,privateKey:t}=n,o=await g({uncompressedPrivateKeyHex:t,compressedPublicKeyHex:s});return await l({key:o,content:e})};async function g(n){const{uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s}=n,t=c({uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s});return await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}async function l(n){const{key:e,content:s}=n,t=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,new TextEncoder().encode(s)),o=u(new Uint8Array(t));return i(o)}function u(n){if(n.length%2!=0||n.length==0||n.length>132)throw new Error("Invalid IEEE P1363 signature encoding. Length: "+n.length);const e=a(n.subarray(0,n.length/2)),s=a(n.subarray(n.length/2,n.length));let t=0;const o=2+e.length+1+1+s.length;let r;return o>=128?(r=new Uint8Array(o+3),r[t++]=48,r[t++]=129,r[t++]=o):(r=new Uint8Array(o+2),r[t++]=48,r[t++]=o),r[t++]=2,r[t++]=e.length,r.set(e,t),t+=e.length,r[t++]=2,r[t++]=s.length,r.set(s,t),r}function a(n){let e=0;for(;e - + Push Wallet - - + +