@babylonlabs-io/wallet-connector 4.0.1 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var Vt=Object.defineProperty;var Yt=(t,e,n)=>e in t?Vt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var L=(t,e,n)=>Yt(t,typeof e!="symbol"?e+"":e,n);const xe=require("viem"),H=require("wagmi/actions"),Et=require("wagmi/connectors"),$t=require("@reown/appkit-adapter-wagmi"),Qe=require("@reown/appkit/react"),Je=require("wagmi"),h=require("react"),u=require("react/jsx-runtime"),R=require("@babylonlabs-io/core-ui"),$=require("tailwind-merge");function Zt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var pt={exports:{}},M=pt.exports={},z,V;function Me(){throw new Error("setTimeout has not been defined")}function Be(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?z=setTimeout:z=Me}catch{z=Me}try{typeof clearTimeout=="function"?V=clearTimeout:V=Be}catch{V=Be}})();function mt(t){if(z===setTimeout)return setTimeout(t,0);if((z===Me||!z)&&setTimeout)return z=setTimeout,setTimeout(t,0);try{return z(t,0)}catch{try{return z.call(null,t,0)}catch{return z.call(this,t,0)}}}function Xt(t){if(V===clearTimeout)return clearTimeout(t);if((V===Be||!V)&&clearTimeout)return V=clearTimeout,clearTimeout(t);try{return V(t)}catch{try{return V.call(null,t)}catch{return V.call(this,t)}}}var Z=[],se=!1,ne,ve=-1;function qt(){!se||!ne||(se=!1,ne.length?Z=ne.concat(Z):ve=-1,Z.length&&gt())}function gt(){if(!se){var t=mt(qt);se=!0;for(var e=Z.length;e;){for(ne=Z,Z=[];++ve<e;)ne&&ne[ve].run();ve=-1,e=Z.length}ne=null,se=!1,Xt(t)}}M.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];Z.push(new Ct(t,e)),Z.length===1&&!se&&mt(gt)};function Ct(t,e){this.fun=t,this.array=e}Ct.prototype.run=function(){this.fun.apply(null,this.array)};M.title="browser";M.browser=!0;M.env={};M.argv=[];M.version="";M.versions={};function q(){}M.on=q;M.addListener=q;M.once=q;M.off=q;M.removeListener=q;M.removeAllListeners=q;M.emit=q;M.prependListener=q;M.prependOnceListener=q;M.listeners=function(t){return[]};M.binding=function(t){throw new Error("process.binding is not supported")};M.cwd=function(){return"/"};M.chdir=function(t){throw new Error("process.chdir is not supported")};M.umask=function(){return 0};var Qt=pt.exports;const It=Zt(Qt),ke=["accountChanged","accountsChanged"];function Jt(t){return ke.includes(t)}const Ue="networkChanged",en="chainChanged",Ge="disconnect";function tn(t,e){if(typeof t.on!="function")return!1;try{t.on("accountsChanged",e)}catch{return!1}return[...ke.filter(i=>i!=="accountsChanged"),Ue,en,Ge].forEach(i=>{var r;try{(r=t.on)==null||r.call(t,i,e)}catch{}}),!0}const Se="babylon-wallet#modal-open",nn=["keplr_keystorechange","leap_keystorechange","okx_keystorechange"];function rn(t,e,n){typeof t.removeListener=="function"?t.removeListener(e,n):typeof t.off=="function"&&t.off(e,n)}const on=3600*1e3;class De{constructor({id:e,origin:n,name:i,icon:r,iconBackground:o,docs:c,networks:s,provider:l,label:p,hardware:m,connectGuide:a}){L(this,"id");L(this,"origin");L(this,"name");L(this,"icon");L(this,"iconBackground");L(this,"docs");L(this,"networks");L(this,"provider",null);L(this,"hardware");L(this,"connectGuide");L(this,"_label");L(this,"account",null);this.id=e,this.origin=n,this.name=i,this.icon=r,this.iconBackground=o,this.docs=c,this.networks=s,this.provider=l,this._label=p,this.hardware=m??!1,this.connectGuide=a}get installed(){return!!this.provider}get label(){return this._label??(this.installed?"Installed":"")}async connect(e){if(!this.provider)throw Error("Provider not found");await this.provider.connectWallet(e);const[n,i]=await Promise.all([this.provider.getAddress(),this.provider.getPublicKeyHex()]);return this.account={address:n,publicKeyHex:i},this}clone(){return new De({id:this.id,origin:this.origin,name:this.name,icon:this.icon,iconBackground:this.iconBackground,docs:this.docs,networks:this.networks,provider:this.provider})}}let sn=()=>({emit(t,...e){for(let n=this.events[t]||[],i=0,r=n.length;i<r;i++)n[i](...e)},events:{},on(t,e){var n;return((n=this.events)[t]||(n[t]=[])).push(e),()=>{var i;this.events[t]=(i=this.events[t])==null?void 0:i.filter(r=>e!==r)}}});const J={UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_PARAMS:"INVALID_PARAMS",CONNECTION_FAILED:"CONNECTION_FAILED",METHOD_NOT_IMPLEMENTED:"METHOD_NOT_IMPLEMENTED",MAX_ITERATION_EXCEEDED:"MAX_ITERATION_EXCEEDED",EXTENSION_NOT_FOUND:"EXTENSION_NOT_FOUND",EXTENSION_CONTEXT_INVALIDATED:"EXTENSION_CONTEXT_INVALIDATED",CONNECTION_REJECTED:"CONNECTION_REJECTED",CONNECTION_CANCELED:"CONNECTION_CANCELED",CHAIN_ID_NOT_INITIALIZED:"CHAIN_ID_NOT_INITIALIZED",RPC_URL_NOT_INITIALIZED:"RPC_URL_NOT_INITIALIZED",FAILED_TO_ADD_CHAIN:"FAILED_TO_ADD_CHAIN",FAILED_TO_GET_KEY:"FAILED_TO_GET_KEY",WALLET_INITIALIZATION_FAILED:"WALLET_INITIALIZATION_FAILED",WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",INCOMPATIBLE_WALLET_VERSION:"INCOMPATIBLE_WALLET_VERSION",WALLET_METHOD_NOT_SUPPORTED:"WALLET_METHOD_NOT_SUPPORTED",WALLET_ACCOUNT_NOT_SUPPORTED:"WALLET_ACCOUNT_NOT_SUPPORTED",WALLET_ACCOUNT_CHANGED:"WALLET_ACCOUNT_CHANGED",NETWORK_NOT_ENABLED_IN_WALLET:"NETWORK_NOT_ENABLED_IN_WALLET",WALLET_CONFIG_REQUIRED:"WALLET_CONFIG_REQUIRED",SHARED_SESSION_DISCONNECT_REFUSED:"SHARED_SESSION_DISCONNECT_REFUSED",INVALID_PUBLIC_KEY:"INVALID_PUBLIC_KEY",ADDRESS_GENERATION_FAILED:"ADDRESS_GENERATION_FAILED",UNSUPPORTED_NETWORK:"UNSUPPORTED_NETWORK",INVALID_ADDRESS_PREFIX:"INVALID_ADDRESS_PREFIX",MISSING_PSBT_HEX:"MISSING_PSBT_HEX",PSBT_HEX_REQUIRED:"PSBT_HEX_REQUIRED",PSBTS_HEXES_REQUIRED:"PSBTS_HEXES_REQUIRED",SIGNATURE_EXTRACT_ERROR:"SIGNATURE_EXTRACT_ERROR",GENERATION_ERROR:"GENERATION_ERROR",ADDRESS_NOT_FOUND:"ADDRESS_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",EMPTY_WITNESS_STACK:"EMPTY_WITNESS_STACK",QR_READ_ERROR:"QR_READ_ERROR",QR_SCAN_ERROR:"QR_SCAN_ERROR",DEVICE_CEREMONY_INVALID:"DEVICE_CEREMONY_INVALID",DEVICE_LOCKED:"DEVICE_LOCKED",DEVICE_WRONG_APP:"DEVICE_WRONG_APP",DEVICE_DISCONNECTED:"DEVICE_DISCONNECTED",INSCRIPTIONS_UNSUPPORTED_NETWORK:"INSCRIPTIONS_UNSUPPORTED_NETWORK",INSCRIPTION_FETCH_ERROR:"INSCRIPTION_FETCH_ERROR"};class ae extends Error{constructor({code:n,message:i,wallet:r,version:o,chainId:c},s){super(i,s);L(this,"code");L(this,"wallet");L(this,"version");L(this,"chainId");this.code=n,this.wallet=r,this.version=o,this.chainId=c}}function cn(t){if(!t)return!1;const e=t.toLowerCase();return e.includes("user rejected")||e.includes("user denied")||e.includes("user cancelled")||e.includes("user canceled")}function he(t){return t instanceof ae&&t.code===J.SHARED_SESSION_DISCONNECT_REFUSED}class ze{constructor(e,n,i,r,o){L(this,"_connectedWallet",null);L(this,"_connectionGeneration",0);L(this,"_ee",sn());this.id=e,this.name=n,this.icon=i,this.wallets=r,this.config=o}get connectedWallet(){return this._connectedWallet}async connect(e){try{const n=typeof e=="string"?this.wallets.find(r=>r.id===e):e;if(!n)throw new ae({code:J.EXTENSION_NOT_FOUND,message:"Wallet not found"});this._ee.emit("connecting",`Connecting ${n.name}`);const i=(r,o)=>this._ee.emit("connecting",r,o);return await n.connect(i),this._connectedWallet=n,this._connectionGeneration+=1,this._ee.emit("connect",this._connectedWallet),this.connectedWallet}catch(n){return this._ee.emit("error",n),null}}async disconnect(e="chain"){const n=this._connectedWallet,i=this._connectionGeneration;if(!n)return;const r=n.provider;if(r!=null&&r.disconnect)try{await r.disconnect(e)}catch(o){if(e==="chain"&&he(o)||(this._ee.emit("error",o instanceof Error?o:new Error(String(o))),e==="chain"))throw o}this._connectedWallet!==n||this._connectionGeneration!==i||(this._connectedWallet=null,this._ee.emit("disconnect",n))}clone(){return new ze(this.id,this.name,this.icon,this.wallets,this.config)}on(e,n){return this._ee.on(e,n)}}var G=(t=>(t.MAINNET="mainnet",t.TESTNET="testnet",t.SIGNET="signet",t))(G||{});const an=t=>e=>e[t],ln=async({metadata:t,context:e,config:n})=>{const{id:i,wallet:r,name:o,icon:c,iconBackground:s,docs:l="",networks:p=[],createProvider:m,label:a,hardware:d,connectGuide:f}=t,E={id:i,name:"",icon:"",iconBackground:s,origin:null,provider:null,docs:l,networks:p,label:a,hardware:d,connectGuide:f==null?void 0:f(n)};if(r){const C=typeof r=="string"?an(r):r;E.origin=await C(e,n)??null,E.provider=E.origin?m(E.origin,n):null}else E.origin=null,E.provider=m(null,n);return typeof o=="string"?E.name=o??"":E.name=E.origin?await o(E.origin,n):"",typeof c=="string"?E.icon=c??"":E.icon=E.origin?await c(E.origin,n):"",new De(E)},Nt=({id:t,name:e,icon:n,provider:i})=>new De({id:t,origin:null,name:e,icon:n,docs:"",networks:[G.MAINNET,G.SIGNET],provider:i}),wt=async({persistent:t,metadata:e,context:n,config:i,accountStorage:r,disabledWallets:o})=>{const c=[],s=t?r.get(e.chain):void 0;for(const d of e.wallets)o!=null&&o.includes(d.id)||c.push(await ln({metadata:d,context:n,config:i}));const l=c.find(d=>d.id==="injectable"&&d.installed),p=c.filter(d=>d.name.toLowerCase()!==(l==null?void 0:l.name.toLowerCase())||d.id==="injectable"),m=new ze(e.chain,e.name,e.icon,p,i);return e.chain!=="ETH"&&s&&c.some(d=>d.id===s&&d.installed)&&m.connect(s).catch(d=>{console.error("Auto-reconnect failed:",d instanceof Error?d.message:"Unknown error")}),m};function dn({connectors:t,storage:e,allowReconnect:n,persistent:i,eligibleChainIds:r}){if(!n||!i)return[];const o=[];for(const c of t){if(!r.has(c.id)||c.connectedWallet)continue;const s=e.get(c.id);s&&c.wallets.some(l=>l.id===s&&l.installed)&&o.push({connector:c,walletId:s})}return o}const et="unisat#initialized",un=3e3;function fn({connectors:t,setConnectors:e,config:n,context:i,storage:r,disabledWallets:o,persistent:c,metadata:s}){const l=h.useRef(t);l.current=t;const p=Object.values(t).some(Boolean);h.useEffect(()=>{if(!p)return;let m=!1,a=!1;const d=new Set,f=new Set,E=async N=>{if(!(m||a)){m=!0;try{await C(N)}finally{m=!1}}},C=async N=>{const W=Object.values(l.current).filter(Boolean).filter(S=>!!s[S.id]&&!S.connectedWallet&&S.wallets.some(K=>K.id!=="injectable"&&!K.installed));let B=[];if(W.length>0){const S=await Promise.all(W.map(b=>{var w;return wt({persistent:!1,metadata:s[b.id],context:i,config:(w=n.find(_=>_.chain===b.id))==null?void 0:w.config,accountStorage:r,disabledWallets:o}).catch(()=>null)}));if(a)return;const K=S.filter(b=>{if(!b)return!1;const w=l.current[b.id];if(!w||w.connectedWallet)return!1;const _=new Set(w.wallets.filter(A=>A.installed).map(A=>A.id));return b.wallets.some(A=>A.installed&&!_.has(A.id))});for(const b of K)f.add(b.id);const k=l.current;B=K.filter(b=>{var w;return!((w=k[b.id])!=null&&w.connectedWallet)}),B.length>0&&e(b=>{var _;const w={};for(const A of B)(_=b[A.id])!=null&&_.connectedWallet||(w[A.id]=A);return Object.keys(w).length>0?{...b,...w}:b})}if(!N||!c||f.size===0)return;const D={};for(const S of Object.values(l.current))S&&(D[S.id]=S);for(const S of B)D[S.id]=S;const O=dn({connectors:Object.values(D),storage:r,allowReconnect:N,persistent:c,eligibleChainIds:f});for(const{connector:S,walletId:K}of O)d.has(S.id)||(d.add(S.id),S.connect(K).then(k=>{d.delete(S.id),k&&f.delete(S.id)}).catch(()=>d.delete(S.id)))},T=()=>void E(!0),g=()=>void E(!1),I=setTimeout(T,un),y=typeof window<"u";return y&&(window.addEventListener(et,T,{once:!0}),window.addEventListener(Se,g)),()=>{a=!0,clearTimeout(I),y&&(window.removeEventListener(et,T),window.removeEventListener(Se,g))}},[p,n,i,r,o,e,c,s])}function hn(t,e,n){function i(){const c=n;if(typeof e>"u")return c;const s=e.getItem(t);return(s?JSON.parse(s):null)??c}const[r,o]=h.useState(i);return h.useEffect(function(){e.setItem(t,JSON.stringify(r??""))},[t,e,r]),[r,o]}const Tt=h.createContext({lockInscriptions:!0});function En({children:t,context:e}){const[n,i]=hn("bwc-inscription-modal-lock",e.localStorage,!0),r=h.useMemo(()=>({lockInscriptions:n,toggleLockInscriptions:i}),[n,i]);return u.jsx(Tt.Provider,{value:r,children:t})}const pn=()=>h.useContext(Tt),Y="__babylon-wallet-confirmation-v1__",At=2,mn={BTC:["accountsChanged",Ue,Ge],BBN:["accountChanged"],ETH:["accountsChanged","chainChanged"]};function Ee(t,e){return t[e]}function be(t,e,n){var o;const i=(o=Ee(t,e))==null?void 0:o.config,r=(n==null?void 0:n[e])??(e==="BTC"?i==null?void 0:i.network:i==null?void 0:i.chainId);return r===void 0?"":String(r)}function ie(t,e){return t.toLowerCase()===e.toLowerCase()}function gn(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const e=t;return typeof e.chain=="string"&&typeof e.walletId=="string"&&typeof e.address=="string"&&typeof e.publicKeyHex=="string"&&typeof e.network=="string"}function pe(t){if(t)try{const e=JSON.parse(t);return(e==null?void 0:e.version)!==At||!Array.isArray(e.entries)||!e.entries.every(gn)?void 0:e}catch{return}}function de(t,e,n){const i=t.filter(r=>r.account&&Ee(e,r.chain)).map(r=>({chain:r.chain,walletId:r.wallet.id,address:r.account.address,publicKeyHex:r.account.publicKeyHex,network:be(e,r.chain,n)})).sort((r,o)=>r.chain.localeCompare(o.chain));return JSON.stringify({version:At,entries:i})}function Cn(t,e,n){var r;const i=(r=pe(t))==null?void 0:r.entries;return i?e.every(o=>{var m;const c=o,s=(m=Ee(n,c))==null?void 0:m.connectedWallet,l=s==null?void 0:s.account,p=i.find(a=>a.chain===c);return!!(s&&l&&p&&p.walletId===s.id&&ie(p.address,l.address)&&ie(p.publicKeyHex,l.publicKeyHex)&&p.network===be(n,c))}):!1}function In(t,e,n){var r;const i=(r=pe(t))==null?void 0:r.entries;return i?e.every(o=>{var p;const c=o,s=(p=Ee(n,c))==null?void 0:p.connectedWallet,l=i.find(m=>m.chain===c);return!!(s&&l&&l.walletId===s.id&&l.network===be(n,c))}):!1}async function Nn(t,e,n){var o;const i=(o=pe(t))==null?void 0:o.entries;return i?(await Promise.all(e.map(async c=>{var d,f;const s=c,l=Ee(n,s),p=l==null?void 0:l.connectedWallet,m=p==null?void 0:p.provider,a=i.find(E=>E.chain===s);if(!p||!m||!a||a.walletId!==p.id)return!1;try{if(((d=m.isIdentityCurrent)==null?void 0:d.call(m))===!1)return!1;const[E,C,T]=await Promise.all([m.getAddress(),m.getPublicKeyHex(),s==="ETH"?m.getChainId():s==="BTC"?m.getNetwork():be(n,s)]);return((f=m.isIdentityCurrent)==null?void 0:f.call(m))===!1?!1:ie(a.address,E)&&ie(a.publicKeyHex,C)&&a.network===String(T)}catch{return!1}}))).every(Boolean):!1}function _t(t,e,n,i){var c;const r=(c=pe(t))==null?void 0:c.entries;if(!r)return()=>{};const o=[];return e.forEach(s=>{var m,a,d;const l=s,p=(a=(m=n[l])==null?void 0:m.connectedWallet)==null?void 0:a.provider;p!=null&&p.on&&((d=mn[l])==null||d.forEach(f=>{var C;const E=(...T)=>{const g=T[0],I=r.find(y=>y.chain===l);l==="ETH"&&f==="accountsChanged"&&Array.isArray(g)&&g.length===1&&typeof g[0]=="string"&&I&&ie(I.address,g[0])||i(l)};try{(C=p.on)==null||C.call(p,f,E),o.push({event:f,handler:E,provider:p})}catch{}}))}),()=>{o.forEach(({event:s,handler:l,provider:p})=>{var m;try{(m=p.off)==null||m.call(p,s,l)}catch{}})}}function yt(t){var e;return((e=pe(t))==null?void 0:e.entries.map(n=>n.chain))??[]}const He={confirmed:!1,visible:!1,screen:{type:"CHAINS"},chains:{},selectedWallets:{},requiredChainIds:[]},Ve=h.createContext(He);function wn(t,e){return Object.keys(t).reduce((n,i)=>(e.has(i)&&(n[i]=t[i]),n),{})}function vt({children:t,chains:e,requiredChainIds:n,storage:i}){const[r,o]=h.useState(()=>({...He,chains:e.reduce((a,d)=>({...a,[d.id]:d}),{}),requiredChainIds:[...n]})),c=n.some(a=>!r.requiredChainIds.includes(a)),s=h.useMemo(()=>({...r,confirmed:c?!1:r.confirmed,requiredChainIds:[...n]}),[n,c,r]),l=h.useRef(n);h.useInsertionEffect(()=>{l.current=n},[n]),h.useEffect(()=>{o(a=>{const d=e.reduce((T,g)=>({...T,[g.id]:g}),{}),f=new Set(e.map(T=>T.id)),E=wn(a.selectedWallets,f),C=n.some(T=>!a.requiredChainIds.includes(T));return{...a,confirmed:C?!1:a.confirmed,chains:d,selectedWallets:E,requiredChainIds:[...n]}})},[e,n]);const p=h.useMemo(()=>({open:()=>{typeof window<"u"&&window.dispatchEvent(new Event(Se)),o(a=>({...a,visible:!0}))},close:()=>{o(a=>({...a,visible:!1}))},reset:()=>{i==null||i.delete(Y),o(({chains:a,requiredChainIds:d})=>({...He,chains:a,requiredChainIds:d}))},displayLoader:(a="",d="")=>{o(f=>({...f,screen:{type:"LOADER",params:{message:a,description:d}}}))},displayChains:()=>{o(a=>({...a,screen:{type:"CHAINS"}}))},displayWallets:a=>{o(d=>({...d,screen:{type:"WALLETS",params:{chain:a}}}))},displayConnectGuide:(a,d)=>{o(f=>({...f,screen:{type:"CONNECT_GUIDE",params:{chain:a,wallet:d}}}))},displayError:a=>{o(d=>({...d,screen:{type:"ERROR",params:a}}))},selectWallet:(a,d)=>{o(f=>({...f,selectedWallets:{...f.selectedWallets,[a]:d}}))},removeWallet:a=>{const d=l.current.includes(a);d&&(i==null||i.delete(Y)),o(f=>({...f,confirmed:d?!1:f.confirmed,confirmationReceipt:d?void 0:f.confirmationReceipt,selectedWallets:{...f.selectedWallets,[a]:void 0}}))},confirm:a=>{o(d=>({...d,confirmed:!0,confirmationReceipt:a}))},unconfirm:(a=!1)=>{o(d=>({...d,confirmed:!1,confirmationReceipt:a?d.confirmationReceipt:void 0}))}}),[i]),m=h.useMemo(()=>({...s,...p}),[s,p]);return u.jsx(Ve.Provider,{value:m,children:t})}const Ke={BTC:null,BBN:null,ETH:null},Rt=h.createContext(Ke);function Tn({persistent:t,storage:e,children:n,context:i,config:r,onError:o,disabledWallets:c,requiredChains:s,metadata:l}){const[p,m]=h.useState(Ke),a=h.useCallback(async()=>{const C=r.filter(g=>l[g.chain]).map(async({chain:g,config:I})=>{const y=l[g];if(!y)return null;try{return await wt({persistent:t,metadata:y,context:i,config:I,accountStorage:e,disabledWallets:c})}catch(N){throw console.error("[ChainProvider] failed to create connector for chain:",g,N instanceof Error?N.message:"Unknown error"),N}});return(await Promise.all(C)).reduce((g,I)=>I?{...g,[I.id]:I}:g,{...Ke})},[t,r,i,e,c,l]);h.useEffect(()=>{a().then(E=>{m(E)}).catch(E=>{console.error("[ChainProvider] init failed with error:",E instanceof Error?E.message:"Unknown error"),o==null||o(E)})},[m,a,o]),fn({connectors:p,setConnectors:m,config:r,context:i,storage:e,disabledWallets:c,persistent:t,metadata:l}),h.useEffect(()=>{const E=Object.values(p).filter(Boolean);if(E.length===0)return;const C=()=>m(g=>({...g})),T=E.flatMap(g=>[g.on("connect",C),g.on("disconnect",C)]);return()=>T.forEach(g=>g())},[p]);const d=h.useMemo(()=>Object.values(p).filter(E=>!!E),[p]),f=h.useMemo(()=>s===void 0?r.filter(E=>l[E.chain]).map(E=>E.chain):[...s],[r,l,s]);return u.jsx(En,{context:i,children:u.jsx(vt,{chains:d,requiredChainIds:f,storage:e,children:u.jsx(Rt.Provider,{value:p,children:n})})})}const me=()=>h.useContext(Rt),xt=h.createContext({});function An({children:t,value:e}){const n=h.useMemo(()=>e??{},[e]);return u.jsx(xt.Provider,{value:n,children:t})}const St=()=>h.useContext(xt),ue="baby-connected-wallet-accounts";function _e(t,e){const n=e==null?void 0:e[t];return n?`${t}:${n}`:t}function ye(){const t=localStorage.getItem(ue);if(!t)return{};try{const e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?(localStorage.removeItem(ue),{}):e}catch(e){return console.error("[account-storage] Failed to parse accounts map, clearing corrupted entry:",e),localStorage.removeItem(ue),{}}}function tt(t){try{localStorage.setItem(ue,JSON.stringify(t))}catch(e){console.error("[account-storage] Failed to write accounts map, clearing entry:",e),localStorage.removeItem(ue)}}const _n=(t,e)=>{function n(r){const o=r._timestamps;return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}function i(r,o){const s=n(r)[o];if(typeof s!="number"||!Number.isFinite(s))return!0;const l=Date.now();return s<0||s>l+t?!0:l-s>t}return{get:r=>{const o=ye(),c=_e(r,e);if(!i(o,c))return o[c]},has:r=>{const o=ye(),c=_e(r,e);return i(o,c)?!1:!!o[c]},set:(r,o)=>{const c=ye(),s=_e(r,e),l=n(c);c[s]=o,c._timestamps={...l,[s]:Date.now()},tt(c)},delete:r=>{const o=ye(),c=_e(r,e),s=n(o),l=Reflect.deleteProperty(o,c);return delete s[c],o._timestamps=s,tt(o),l}}},Ot="#000000",yn="#1FE121",Lt="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20width='225px'%20height='224px'%20viewBox='0%200%20225%20224'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3ctitle%3eokx%3c/title%3e%3cg%20id='Page-1'%20stroke='none'%20strokeWidth='1'%20fill='none'%20fill-rule='evenodd'%3e%3cg%20id='okx'%20transform='translate(0.401000,%200.006000)'%20fill='%23FFFFFF'%20fill-rule='nonzero'%3e%3cpath%20d='M144.382,74.667%20L79.673,74.667%20C76.924,74.667%2074.695,76.895%2074.695,79.644%20L74.695,144.354%20C74.695,147.103%2076.924,149.332%2079.673,149.332%20L144.382,149.332%20C147.131,149.332%20149.36,147.103%20149.36,144.354%20L149.36,79.644%20C149.36,76.895%20147.131,74.667%20144.382,74.667%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,0%20L4.978,0%20C2.229,0%200,2.228%200,4.978%20L0,69.687%20C0,72.436%202.229,74.665%204.978,74.665%20L69.687,74.665%20C72.437,74.665%2074.665,72.436%2074.665,69.687%20L74.665,4.978%20C74.665,2.228%2072.437,0%2069.687,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,0%20L154.307,0%20C151.558,0%20149.329,2.228%20149.329,4.978%20L149.329,69.687%20C149.329,72.436%20151.558,74.665%20154.307,74.665%20L219.017,74.665%20C221.766,74.665%20223.994,72.436%20223.994,69.687%20L223.994,4.978%20C223.994,2.228%20221.766,0%20219.017,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,149.328%20L4.978,149.328%20C2.229,149.328%200,151.556%200,154.305%20L0,219.015%20C0,221.764%202.229,223.993%204.978,223.993%20L69.687,223.993%20C72.437,223.993%2074.665,221.764%2074.665,219.015%20L74.665,154.305%20C74.665,151.556%2072.437,149.328%2069.687,149.328%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,149.328%20L154.307,149.328%20C151.558,149.328%20149.329,151.556%20149.329,154.305%20L149.329,219.015%20C149.329,221.764%20151.558,223.993%20154.307,223.993%20L219.017,223.993%20C221.766,223.993%20223.994,221.764%20223.994,219.015%20L223.994,154.305%20C223.994,151.556%20221.766,149.328%20219.017,149.328%20Z'%20id='Path'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/svg%3e",fe="babylon:open-appkit",Ye="appkit-eth-connector",Dt="appkit-btc-connector",nt="bigint",it="function",vn="AppKit configuration cannot be serialized.",Rn=1,rt=new WeakMap;let xn=Rn;function Sn(t){const e=rt.get(t);if(e)return e;const n=xn++;return rt.set(t,n),n}function ot(t){const e=JSON.stringify(t,(n,i)=>typeof i===nt?{type:nt,value:i.toString()}:typeof i===it?{type:it,value:Sn(i)}:i&&typeof i=="object"&&!Array.isArray(i)?Object.fromEntries(Object.entries(i).sort(([r],[o])=>r<o?-1:r>o?1:0)):i);if(e===void 0)throw new TypeError(vn);return e}function bt({projectId:t,metadata:e,ethChain:n,btcNetwork:i}){return Object.freeze({projectId:t,metadataFingerprint:ot(e),ethFingerprint:n?ot(n):void 0,btcNetwork:i})}let X=null,Pt=null;const Oe=new Set;function F(t,e){throw new ae({code:J.WALLET_INITIALIZATION_FAILED,message:t,chainId:e})}function Pe(){return X}function Le(){return(X==null?void 0:X.modal)??Pt}function Wt(t,e){X&&F(`Cannot set a manual ${t} AppKit configuration after AppKit initialization. Use the canonical AppKit state.`),Oe.add(t),e&&(Pt=e)}function jt(t){return t?(Oe.size>0&&F(`Cannot initialize AppKit after a manual ${[...Oe].join(" and ")} configuration was set. Use only one initialization method.`),!0):(X&&F("AppKit is already initialized. A project ID is required to validate the requested configuration."),!1)}function Mt(t){return X&&F("AppKit is already initialized. Reuse the shared AppKit state instead of replacing it."),Oe.size>0&&F("Cannot publish AppKit state after a manual shared configuration was set."),X=Object.freeze({...t,btcConfig:t.btcConfig?Object.freeze({...t.btcConfig}):void 0}),X}function Bt(t,e){t.projectId!==e.projectId&&F("AppKit was already initialized with a different project ID. A page can use only one AppKit configuration."),t.metadataFingerprint!==e.metadataFingerprint&&F("AppKit was already initialized with different metadata. A page can use only one AppKit configuration."),e.ethFingerprint&&(t.ethFingerprint||F("AppKit was already initialized without Ethereum support. A page that needs Ethereum must initialize AppKit with Ethereum first.","ETH"),t.ethFingerprint!==e.ethFingerprint&&F("AppKit was already initialized with a different Ethereum chain configuration.","ETH")),e.btcNetwork&&(t.btcNetwork||F("AppKit was already initialized without Bitcoin support. A page that needs Bitcoin must initialize AppKit with Bitcoin first.","BTC"),t.btcNetwork!==e.btcNetwork&&F("AppKit was already initialized with a different Bitcoin network.","BTC"))}function st(t,e){if(typeof document>"u"){const l=setTimeout(t,e);return()=>clearTimeout(l)}let n=e,i=0,r;const o=()=>{i=Date.now(),r=setTimeout(()=>{document.removeEventListener("visibilitychange",s),t()},n)},c=()=>{clearTimeout(r),r=void 0,n=Math.max(0,n-(Date.now()-i))},s=()=>{document.visibilityState==="hidden"?r!==void 0&&c():r===void 0&&o()};return document.addEventListener("visibilitychange",s),document.visibilityState!=="hidden"&&o(),()=>{clearTimeout(r),document.removeEventListener("visibilitychange",s)}}const On="Ethereum",Ln="Shared wagmi config is being replaced. This might indicate multiple initializations.";let ce=null;function Dn(t){Wt(On),ce&&ce!==t&&console.warn(Ln),ce=t}function $e(){const t=Pe();if(t)return t.wagmiConfig||F("AppKit was initialized without Ethereum support. Initialize it with Ethereum support.","ETH"),t.wagmiConfig;if(!ce)throw new Error("Shared wagmi config not initialized. Initialize AppKit with Ethereum support, or use setSharedWagmiConfig() as an exclusive manual alternative.");return ce}function Re(){const t=Pe();return t?t.wagmiConfig!==void 0:ce!==null}function Ht(){var n;const t=Le();return(t==null?void 0:t.getProviderType("eip155"))==="WALLET_CONNECT"&&((n=t==null?void 0:t.getAccount("bip122"))==null?void 0:n.isConnected)===!0}const bn=1500,Pn=6e4,Wn=3e3,ct="Wallet not connected",jn="Ethereum Wallet",Mn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=";function Q(t){return t&&xe.isAddress(t,{strict:!1})?t:void 0}class Bn{constructor(e){L(this,"config");L(this,"address");L(this,"chainId");L(this,"eventHandlers",new Map);L(this,"unwatchFunctions",[]);L(this,"emptyAccountTimer");this.config=e,this.ensureEventWatchers()}ensureEventWatchers(){this.unwatchFunctions.length>0||Re()&&this.setupEventWatchers()}getWagmiConfig(){if(!Re())throw new Error("AppKit ETH not initialized. Ensure AppKit modal is initialized at application startup by calling initializeAppKitModal() with eth config in your app's entry point.");return $e()}setupEventWatchers(){const e=this.getWagmiConfig(),n=H.getAccount(e),i=Q(n.address);i&&n.status==="connected"&&(this.address=i,this.chainId=n.chainId,setTimeout(()=>{this.emit("accountsChanged",[i])},100));const r=H.watchAccount(e,{onChange:c=>{const s=this.address,l=Q(c.address);if(!l){if(!s){this.chainId=c.chainId;return}if(this.emptyAccountTimer!==void 0)return;this.emptyAccountTimer=setTimeout(()=>{this.emptyAccountTimer=void 0,this.address=void 0,this.chainId=void 0,this.emit("accountsChanged",[])},Wn);return}this.clearEmptyAccountTimer(),this.address=l,this.chainId=c.chainId,(s==null?void 0:s.toLowerCase())!==l.toLowerCase()&&this.emit("accountsChanged",[l])}}),o=H.watchChainId(e,{onChange:c=>{const s=this.chainId;this.chainId=c,s!==c&&this.emit("chainChanged",`0x${c.toString(16)}`)}});this.unwatchFunctions.push(r,o,()=>this.clearEmptyAccountTimer())}clearEmptyAccountTimer(){clearTimeout(this.emptyAccountTimer),this.emptyAccountTimer=void 0}emit(e,n){const i=this.eventHandlers.get(e);i&&i.forEach(r=>r(n))}async connectWallet(){try{const e=this.getWagmiConfig();this.ensureEventWatchers();const n=H.getAccount(e),i=Q(n.address);if(i){this.address=i,this.chainId=n.chainId;return}if(typeof window<"u"){await new Promise((l,p)=>{let m=!1,a;const d=()=>{f(),a==null||a(),E(),T==null||T()},f=st(()=>{d(),p(new Error("Connection timeout"))},Pn),E=H.watchAccount(e,{onChange:g=>{const I=Q(g.address);I&&(this.address=I,this.chainId=g.chainId,d(),l())}}),C=Le(),T=C==null?void 0:C.subscribeState(g=>{if(g.open)m=!0,a==null||a(),a=void 0;else if(m){const I=H.getAccount(e),y=Q(I.address);if(y){this.address=y,this.chainId=I.chainId,d(),l();return}if(a)return;a=st(()=>{const N=H.getAccount(e),W=Q(N.address);W?(this.address=W,this.chainId=N.chainId,d(),l()):(d(),p(new Error("Connection cancelled")))},bn)}});window.dispatchEvent(new CustomEvent(fe))});return}const r=It.env.NEXT_PUBLIC_REOWN_PROJECT_ID;if(!r)throw new Error("NEXT_PUBLIC_REOWN_PROJECT_ID environment variable is required");const o=Et.walletConnect({projectId:r,metadata:{name:"Babylon Vault",description:"",url:"",icons:[""]}}),c=await H.connect(e,{connector:o});this.address=Q(c.accounts[0]),this.chainId=c.chainId}catch(e){throw console.error("Failed to connect wallet:",e instanceof Error?e.message:"Unknown error"),new Error(`Failed to connect wallet: ${e instanceof Error?e.message:"Unknown error"}`)}}async disconnect(e){if(e==="chain"&&Ht())throw new ae({code:J.SHARED_SESSION_DISCONNECT_REFUSED,message:"Ethereum and Bitcoin share one wallet session. Disconnecting Ethereum alone would also disconnect Bitcoin. Disconnect all wallets instead.",wallet:"AppKit",chainId:"ETH"});e!=="local"&&await H.disconnect(this.getWagmiConfig()),this.clearEmptyAccountTimer(),this.address=void 0,this.chainId=void 0}async getAddress(){const e=this.getWagmiConfig(),n=H.getAccount(e),i=Q(n.address);if(i)return this.address=i,this.chainId=n.chainId,i;if(this.address)return this.address;throw new Error(ct)}async getPublicKeyHex(){return this.getAddress()}async signMessage(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.signMessage(n,{message:e,account:i})}catch(n){throw new Error(`Failed to sign message: ${n}`)}}async signTypedData(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.signTypedData(n,{account:i,domain:{...e.domain,salt:e.domain.salt,verifyingContract:e.domain.verifyingContract},types:e.types,primaryType:e.primaryType,message:e.message})}catch(n){throw new Error(`Failed to sign typed data: ${n}`)}}async sendTransaction(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.sendTransaction(n,{account:i,to:e.to,value:e.value?xe.parseEther(e.value):void 0,data:e.data,gas:e.gasLimit,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce})}catch(n){throw new Error(`Failed to send transaction: ${n}`)}}async estimateGas(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.estimateGas(n,{account:i,to:e.to,value:e.value?xe.parseEther(e.value):void 0,data:e.data})}catch(n){throw new Error(`Failed to estimate gas: ${n}`)}}async getChainId(){if(this.chainId)return this.chainId;const e=this.getWagmiConfig(),n=H.getAccount(e);if(n.chainId)return this.chainId=n.chainId,this.chainId;throw new Error(ct)}async switchChain(e){try{const n=this.getWagmiConfig();if(![1,11155111,31337].includes(e))throw new Error(`Unsupported chain ID: ${e}`);await H.switchChain(n,{chainId:e}),this.chainId=e}catch(n){throw new Error(`Failed to switch chain: ${n}`)}}async getBalance(){try{const e=this.getWagmiConfig(),n=await this.getAddress();return(await H.getBalance(e,{address:n})).value}catch(e){throw new Error(`Failed to get balance: ${e}`)}}async getNonce(){try{const e=this.getWagmiConfig(),n=await this.getAddress();return await H.getTransactionCount(e,{address:n})}catch(e){throw new Error(`Failed to get nonce: ${e}`)}}async getNetworkInfo(){const e=await this.getChainId();return{name:this.config.chainName||"Ethereum",chainId:e.toString()}}getActiveConnectorIdentity(){var n;const e=(n=Le())==null?void 0:n.getWalletInfo("eip155");if(e!=null&&e.name||e!=null&&e.icon)return{name:e.name,icon:e.icon};if(Re())try{const{connector:i}=H.getAccount(this.getWagmiConfig());return i?{name:i.name,icon:i.icon}:void 0}catch{return}}getWalletProviderName(){var n;const e=(n=this.getActiveConnectorIdentity())==null?void 0:n.name;return e!=null&&e.trim()?e:jn}getWalletProviderIcon(){var n;const e=(n=this.getActiveConnectorIdentity())==null?void 0:n.icon;return e!=null&&e.trim()?e:Mn}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(n)}off(e,n){const i=this.eventHandlers.get(e);i&&i.delete(n)}destroy(){this.unwatchFunctions.forEach(e=>e()),this.eventHandlers.clear()}}const Hn="AppKit",Kn={id:Ye,name:Hn,icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=",docs:"https://docs.reown.com/appkit/overview",wallet:void 0,createProvider:(t,e)=>new Bn(e),networks:[G.MAINNET,G.TESTNET,G.SIGNET],label:"Connect ETH Wallet"},Fn="data:image/svg+xml,%3csvg%20enable-background='new%200%200%201920%201920'%20viewBox='0%200%201920%201920'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='m959.8%2080.7-539.7%20895.6%20539.7-245.3z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%20731-539.7%20245.3%20539.7%20319.1z'%20fill='%2362688f'/%3e%3cpath%20d='m1499.6%20976.3-539.8-895.6v650.3z'%20fill='%2362688f'/%3e%3cpath%20d='m959.8%201295.4%20539.8-319.1-539.8-245.3z'%20fill='%23454a75'/%3e%3cpath%20d='m420.1%201078.7%20539.7%20760.6v-441.7z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%201397.6v441.7l540.1-760.6z'%20fill='%2362688f'/%3e%3c/svg%3e",kn={chain:"ETH",name:"Ethereum",icon:Fn,wallets:[Kn]};function Kt(t,e){const n=t.rpcUrls.default.http[0];return new $t.WagmiAdapter({networks:[t],projectId:e,ssr:!1,storage:Je.createStorage({storage:Je.cookieStorage}),connectors:[Et.baseAccount({preference:{telemetry:!1}})],transports:{[t.id]:xe.http(n)}})}function Un(t){if(!jt(t.projectId))return null;const{chain:e}=t.eth,n=bt({projectId:t.projectId,metadata:t.metadata,ethChain:e}),i=Pe();if(i)return Bt(i,n),{modal:i.modal,wagmiConfig:$e()};Qe.modal&&F("Reown AppKit was initialized outside this package. Use only this package to initialize it.");const r=Kt(e,t.projectId),o=Qe.createAppKit({adapters:[r],networks:[e],projectId:t.projectId,metadata:t.metadata,features:{email:!1,socials:!1}});return{modal:Mt({modal:o,...n,wagmiConfig:r.wagmiConfig}).modal,wagmiConfig:r.wagmiConfig}}const Gn=()=>{h.useEffect(()=>{const t=()=>{try{const e=Le();e&&e.open()}catch(e){console.warn("AppKit modal not available:",e)}};return window.addEventListener(fe,t),()=>window.removeEventListener(fe,t)},[])};function Ft(t){const e=me();return(e==null?void 0:e[t])??null}const zn=[{match:/okx/i,icon:Lt,iconBackground:Ot}];function Vn(t){return zn.find(({match:e})=>e.test(t))}const ee=()=>h.useContext(Ve);async function at(t){const e=t.provider;if(!(e!=null&&e.getWalletProviderName)||!(e!=null&&e.getWalletProviderIcon))return t;const[n,i]=await Promise.all([e.getWalletProviderName(),e.getWalletProviderIcon()]),r=Vn(n||t.name);return{id:t.id,name:n||t.name,icon:(r==null?void 0:r.icon)||i||t.icon,iconBackground:r==null?void 0:r.iconBackground,docs:t.docs,installed:t.installed,provider:t.provider,account:t.account,label:t.label,hardware:t.hardware}}const Yn=new Map([[J.INCOMPATIBLE_WALLET_VERSION,t=>`Update ${t}`],[J.DEVICE_WRONG_APP,()=>"Wrong App on Device"],[J.DEVICE_LOCKED,()=>"Signing Device Locked"]]);function $n({persistent:t,accountStorage:e,onError:n,btcValidation:i}){const r=me(),{confirmed:o,confirmationReceipt:c,visible:s,selectWallet:l,removeWallet:p,displayLoader:m,displayChains:a,displayConnectGuide:d,displayError:f,confirm:E,unconfirm:C,requiredChainIds:T=[]}=ee(),{verifyBTCAddress:g}=St(),I=h.useRef(0),y=h.useRef(T),N=c??(t&&!s?e.get(Y):void 0),W=h.useRef(),B=h.useRef(new Set),D=T.every(w=>{var _;return(_=r[w])==null?void 0:_.connectedWallet}),O=h.useRef(new Set),S=async w=>{O.current.add(w.id),p==null||p(w.id),t&&e.delete(w.id);try{await w.disconnect("chain")}catch(_){he(_)||console.error("Failed to disconnect rejected wallet:",_ instanceof Error?_.message:"Unknown error"),await w.disconnect("local")}finally{O.current.delete(w.id)}};h.useEffect(()=>{if(!s)return;const _=Object.values(r).filter(Boolean).map(A=>A.on("connecting",(v,x)=>{m==null||m(v,x)}));return()=>_.forEach(A=>A())},[s,m,r]),h.useEffect(()=>{const w=Object.values(r).filter(Boolean),_={BTC:v=>async x=>{var j,ge,Ce,Ie;try{if(!x||!x.account)return;if(!i)throw new Error("Bitcoin address validation is unavailable");if(l==null||l("BTC",x),t&&((j=x.account)!=null&&j.address)&&e.set(v.id,x.id),!s)return;i.validateAddress(v.config.network,x.account.address);const P=()=>void(a==null?void 0:a());if(!i.validateAddressWithPK(((ge=x.account)==null?void 0:ge.address)??"",((Ce=x.account)==null?void 0:Ce.publicKeyHex)??"",v.config.network)){f==null||f({title:"Public Key Mismatch",description:"The Bitcoin address and Public Key for this wallet do not match. Please contact your wallet provider for support.",onSubmit:P,onCancel:()=>{S(v),a==null||a()}});return}if(g&&!await g(((Ie=x.account)==null?void 0:Ie.address)??"")){f==null||f({title:"Staking Currently Unavailable",description:"Staking is temporarily disabled due to network downtime. New stakes are paused until the network resumes.",submitButton:"",cancelButton:"Done",onCancel:async()=>{S(v),a==null||a()}});return}P()}catch(P){S(v),f==null||f({title:"Connection Failed",description:P.message,submitButton:"",cancelButton:"Done",onCancel:async()=>{a==null||a()}})}},BBN:v=>x=>{var j;x&&(l==null||l(v.id,x),t&&((j=x.account)!=null&&j.address)&&e.set(v.id,x.id)),a==null||a()},ETH:v=>async x=>{var j;x&&(l==null||l(v.id,await at(x)),t&&((j=x.account)!=null&&j.address)&&e.set(v.id,x.id)),a==null||a()}},A=w.map(v=>{var x;return v.on("connect",(x=_[v.id])==null?void 0:x.call(_,v))});return w.forEach(v=>{const x=O.current.has(v.id)?null:v.connectedWallet;if(v.id==="ETH"&&x){at(x).then(j=>l==null?void 0:l(v.id,j));return}l==null||l(v.id,x)}),()=>A.forEach(v=>v())},[n,l,p,a,f,g,i,e,r,t,s]),h.useLayoutEffect(()=>{const _=Object.values(r).filter(Boolean).map(A=>A.on("disconnect",v=>{v&&(T.includes(A.id)&&(I.current+=1,e.delete(Y)),p==null||p(A.id),a==null||a(),t&&e.delete(A.id))}));return()=>_.forEach(A=>A())},[p,a,r,t,e,T]),h.useEffect(()=>{const _=Object.values(r).filter(Boolean).map(A=>A.on("error",v=>{if(n==null||n(v),v instanceof ae&&f){const x=Yn.get(v.code);if(x){f({title:x(v.wallet??"your wallet"),description:v.message,submitButton:"",cancelButton:"Done",onCancel:()=>{a==null||a()}});return}}a==null||a()}));return()=>_.forEach(A=>A())},[n,a,f,r]);const K=h.useCallback(async()=>{const w=++I.current;if(!N||!c&&!D)return;const _=await Nn(N,T,r);if(w===I.current){if(!_){e.delete(Y),C==null||C();return}if(!o&&!s){E==null||E(N),a==null||a();return}t&&o&&e.set(Y,N)}},[e,N,c,o,E,r,a,t,T,D,C,s]);h.useEffect(()=>{K()},[K]),h.useLayoutEffect(()=>{const w=W.current;(!N||w&&w!==N)&&B.current.clear(),W.current=N},[N]),h.useLayoutEffect(()=>{I.current+=1;const w=T.filter(A=>!y.current.includes(A));if(y.current=T,!N)return;const _=_t(N,yt(N),r,A=>{if(!T.includes(A)){B.current.add(A);return}I.current+=1,e.delete(Y),C==null||C()});if(!c&&!D)return _;if(!In(N,T,r)||w.some(A=>B.current.has(A))||c&&w.length>0&&!Cn(N,w,r)){_(),e.delete(Y),C==null||C();return}return c&&w.length>0&&(C==null||C(!0)),_},[e,N,c,r,T,D,C]),h.useEffect(()=>()=>{I.current+=1},[]);const k=h.useCallback(async(w,_)=>{const A=r[w.id];await(A==null?void 0:A.connect(_.id))},[r]),b=h.useCallback(async(w,_)=>{if(_.connectGuide&&d){d(w.id,_.id);return}await k(w,_)},[k,d]);return{connect:k,chooseWallet:b}}function Zn(t,e,n){const i=h.useCallback((r,o)=>u.jsx(u.Fragment,{children:o.map(({id:c,widget:s})=>u.jsx(s,{id:c,connector:t[r],createWallet:Nt,onError:n},c))}),[t,n]);return h.useMemo(()=>e.reduce((r,o)=>({...r,[o.chain]:i(o.chain,o.connectors??[])}),{}),[i,e])}function Ze(){const{confirmed:t,chains:e,requiredChainIds:n,selectedWallets:i,open:r,displayChains:o,displayError:c,displayWallets:s,reset:l}=ee(),p=me(),m=h.useCallback(f=>{f!==void 0&&Object.prototype.hasOwnProperty.call(e,f)?s==null||s(f):o==null||o(),r==null||r()},[e,o,s,r]),a=h.useCallback(async f=>{var E;if(f!==void 0&&Object.prototype.hasOwnProperty.call(p,f)){try{await((E=p[f])==null?void 0:E.disconnect("chain"))}catch(C){throw he(C)&&(c==null||c({title:"Wallets share one session",description:C.message,submitButton:"",cancelButton:"Done",onCancel:()=>{o==null||o()}})),C}return}for(const C of Object.values(p))C&&await C.disconnect("all");l==null||l()},[p,o,c,l]),d=h.useMemo(()=>n.every(f=>!!i[f]),[n,i]);return{selected:d,connected:d&&t,open:m,disconnect:a}}function Xn({className:t,alt:e,logo:n,title:i,description:r,optional:o,children:c,onClick:s}){const l=typeof n=="string"?u.jsx(R.Avatar,{url:n,alt:e}):u.jsx(R.Avatar,{children:n}),p=()=>{if(typeof i=="string"){if(i.includes("Bitcoin"))return"select-bitcoin-wallet-button";if(i.includes("Ethereum"))return"select-ethereum-wallet-button";if(i.includes("Babylon"))return"select-babylon-wallet-button"}return"chain-button"};return u.jsxs(R.Text,{as:"button",className:$.twMerge("flex w-full cursor-pointer flex-col gap-4 rounded-lg bg-neutral-200 p-4 text-accent-primary",t),onClick:s,"data-testid":p(),"data-optional":o,children:[u.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[u.jsx("div",{className:"flex items-center",children:l}),u.jsxs("div",{className:"flex flex-col text-left",children:[i,r&&u.jsx(R.Text,{as:"span",variant:"body2",className:"text-accent-secondary",children:r})]}),u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",className:"ml-auto block shrink-0 text-accent-secondary",children:u.jsx("path",{d:"M8.58984 16.59L13.1698 12L8.58984 7.41L9.99984 6L15.9998 12L9.99984 18L8.58984 16.59Z",fill:"currentColor"})})]}),c&&u.jsx("div",{className:"w-full",children:c})]})}const qn=36,lt=14;function Qn(t){return t.length<=qn?t:`${t.slice(0,lt)}…${t.slice(-lt)}`}const Jn=h.memo(({className:t,logo:e,logoBackground:n,address:i})=>{const{isCopied:r,copyToClipboard:o}=R.useCopy(),c=r(i),s=l=>{l.stopPropagation(),o(i,i)};return u.jsxs("div",{className:$.twMerge("flex items-center gap-2.5 rounded-lg bg-neutral-200 p-2",t),children:[u.jsx(R.WalletIcon,{size:"small",className:"shrink-0",url:e,background:n}),u.jsx(R.Text,{as:"div",variant:"caption",title:i,className:"min-w-0 flex-1 truncate text-left font-mono text-accent-secondary",children:Qn(i)}),u.jsx("span",{role:"button",tabIndex:0,"aria-label":c?"Address copied":"Copy address",onClick:s,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&s(l)},className:"flex shrink-0 cursor-pointer items-center text-accent-secondary hover:text-accent-primary",children:c?u.jsx(R.CheckIcon,{size:16,variant:"success"}):u.jsx(R.CopyIcon,{size:16})})]})}),ei="disabled:!bg-[#CCCCCC] dark:disabled:!bg-secondary-strokeDark",ti="Select ",ni=" Wallet",ii=h.memo(({disabled:t=!1,chains:e,requiredChainIds:n,chainDescriptions:i,selectedWallets:r={},className:o,onConfirm:c,onSelectChain:s})=>u.jsxs("div",{className:$.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight text-accent-primary",o),children:[u.jsx("div",{className:"border-b border-secondary-strokeLight p-6",children:u.jsx(R.Heading,{variant:"h5",className:"text-accent-primary",children:"Connect Wallets"})}),u.jsxs("div",{className:"flex flex-col gap-4 p-6",children:[u.jsxs("div",{className:"flex flex-col gap-2",children:[e.map(l=>{var a;const p=r[l.id],m=n!==void 0&&!n.includes(l.id);return u.jsx(Xn,{title:`${ti}${l.name}${ni}`,description:i==null?void 0:i[l.id],optional:m,logo:l.icon,alt:l.name,onClick:()=>void(s==null?void 0:s(l)),children:p&&u.jsx(Jn,{logo:p.icon,logoBackground:p.iconBackground,address:((a=p.account)==null?void 0:a.address)??""})},l.id)}),u.jsx(R.Button,{color:"secondary",disabled:t,fluid:!0,onClick:c,className:$.twMerge("text-sm disabled:!opacity-100",ei),"data-testid":"chains-connect-button",children:"Connect"})]}),u.jsxs(R.Text,{variant:"body2",className:"text-center text-accent-secondary",children:["By clicking Connect you agree with the"," ",u.jsx("a",{href:"https://babylonlabs.io/terms-of-use",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Terms of Use"})," ","and"," ",u.jsx("a",{href:"https://babylonlabs.io/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Privacy Policy"}),"."]})]})]}));function ri(){typeof window<"u"&&window.dispatchEvent(new Event(fe))}function oi({isChainHidden:t,...e}){const{chains:n,requiredChainIds:i,selectedWallets:r,displayWallets:o}=ee(),{selected:c,disconnect:s}=Ze(),l=me(),p=h.useMemo(()=>Object.values(n).filter(a=>r[a.id]||!(t!=null&&t(a))),[n,t,r]),m=h.useCallback(async a=>{if(a.id==="ETH"||a.id==="BTC"){const d=l[a.id],f=a.id==="ETH"?Ye:Dt,E=d==null?void 0:d.wallets.find(C=>C.id===f);if(E&&(d==null?void 0:d.wallets.length)===1){const C=!!d.connectedWallet;try{C?a.id==="ETH"&&!Ht()?ri():await s(a.id):await d.connect(E.id)}catch(T){he(T)||console.error(`Failed to ${C?"disconnect":"connect"} AppKit ${a.id}:`,T instanceof Error?T.message:"Unknown error")}return}}o==null||o(a.id)},[o,l,s]);return u.jsx(ii,{disabled:!c,chains:p,requiredChainIds:i,selectedWallets:r,onSelectChain:m,...e})}function si({name:t,logo:e,logoBackground:n,guide:i,onConnect:r}){return u.jsxs("div",{children:[u.jsxs(R.DialogBody,{className:"flex flex-col gap-6 py-10",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx(R.WalletIcon,{className:"shrink-0",alt:t,url:e,background:n}),u.jsx(R.Heading,{variant:"h5",className:"text-accent-primary",children:"Before you connect"})]}),u.jsx("ol",{className:"flex list-decimal flex-col gap-2 pl-5 text-accent-primary",children:i.steps.map(o=>u.jsx(R.Text,{as:"li",variant:"body2",children:o},o))}),i.installSteps&&u.jsxs("div",{className:"flex flex-col gap-2 rounded-lg bg-neutral-100 p-4",children:[u.jsx(R.Text,{variant:"body2",className:"text-accent-primary",children:"Don't have the app yet?"}),u.jsx("ol",{className:"flex list-decimal flex-col gap-2 pl-5 text-accent-secondary",children:i.installSteps.map(o=>u.jsx(R.Text,{as:"li",variant:"body2",children:o},o))})]})]}),u.jsx(R.DialogFooter,{children:u.jsx(R.Button,{fluid:!0,onClick:r,"data-testid":"connect-guide-connect-button",children:"Connect"})})]})}function ci({onConnect:t}){var o;const{chains:e,screen:n}=ee(),i=e[((o=n.params)==null?void 0:o.chain)??""],r=i==null?void 0:i.wallets.find(({id:c})=>{var s;return c===((s=n.params)==null?void 0:s.wallet)});return!i||!(r!=null&&r.connectGuide)?null:u.jsx(si,{name:r.name,logo:r.icon,logoBackground:r.iconBackground,guide:r.connectGuide,onConnect:()=>t==null?void 0:t(i,r)})}const ai=u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"52",height:"52",viewBox:"0 0 52 52",fill:"none",children:u.jsx("path",{d:"M2.16675 46.5837H49.8334L26.0001 5.41699L2.16675 46.5837ZM28.1667 40.0837H23.8334V35.7503H28.1667V40.0837ZM28.1667 31.417H23.8334V22.7503H28.1667V31.417Z",fill:"#387085"})});function li({className:t,icon:e=ai,title:n,description:i,cancelButton:r="Cancel",submitButton:o=u.jsxs(u.Fragment,{children:["Continue ",u.jsx("span",{className:"hidden md:inline",children:"Anyway"})]}),onCancel:c,onSubmit:s}){return u.jsxs("div",{className:t,children:[u.jsxs(R.DialogBody,{className:"py-16 text-center",children:[u.jsx("div",{className:"mb-6 inline-flex size-20 items-center justify-center bg-primary-contrast text-primary-light",children:e}),u.jsx(R.Heading,{variant:"h4",className:"mb-4 text-accent-primary",children:n}),u.jsx(R.Text,{as:"div",className:"text-accent-secondary",children:i})]}),u.jsxs(R.DialogFooter,{className:"flex gap-4",children:[r&&u.jsx(R.Button,{variant:"outlined",fluid:!0,onClick:c,children:r}),o&&u.jsx(R.Button,{fluid:!0,onClick:s,"data-testid":"error-continue-button",children:o})]})]})}function di({className:t}){const{screen:e}=ee(),{icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:l}=e.params??{};return u.jsx(li,{className:t,icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:l})}function ui({className:t,title:e,description:n}){return u.jsxs("div",{className:$.twMerge("flex flex-col items-center justify-center gap-6",t),children:[u.jsx("div",{className:"flex items-center justify-center bg-primary-contrast p-6",children:u.jsx(R.Loader,{className:"text-primary-light"})}),(e||n)&&u.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[e&&u.jsx(R.Heading,{variant:"h4",className:"capitalize text-accent-primary",children:e}),n&&u.jsx(R.Text,{as:"div",className:"text-accent-secondary",children:n})]})]})}const fi="text-[#15B768] dark:text-[#00E676]",hi="bg-[#15B768] dark:bg-[#00E676]",Ei="text-[#FFB300]",pi="bg-[#FFB300]";function mi({className:t,disabled:e=!1,name:n,logo:i,logoBackground:r,fallbackLink:o,installed:c=!0,hardware:s=!1,label:l,onClick:p}){const a=c||s?{as:"button",disabled:e,onClick:p}:{as:"a",href:o,target:"_blank",rel:"noopener noreferrer"},d=()=>{const f=n.toLowerCase();return f.includes("okx")?"wallet-option-okx":f.includes("keplr")?"wallet-option-keplr":f.includes("leap")?"wallet-option-leap":`wallet-option-${f.replace(/\s+/g,"-")}`};return u.jsxs(R.Text,{variant:"body2",className:$.twMerge("flex h-14 w-full items-center gap-2.5 rounded-lg p-2 text-accent-primary",c?"bg-neutral-200":"bg-neutral-100",e?"cursor-default":"cursor-pointer",t),...a,"data-testid":d(),children:[u.jsx(R.WalletIcon,{className:"shrink-0",alt:n,url:i,background:r}),u.jsx("span",{className:$.twMerge("min-w-0 flex-1 truncate text-left",!c&&"text-accent-secondary"),children:n}),u.jsxs(R.Chip,{className:$.twMerge("flex shrink-0 items-center gap-1.5 rounded-full",c?"bg-neutral-100":"bg-neutral-200"),children:[(s||c)&&u.jsx("span",{className:$.twMerge("size-2 rounded-full",s?pi:hi)}),u.jsx("span",{className:s?Ei:c?fi:"text-accent-secondary",children:s?l:c?"Installed":"Uninstalled"})]})]})}const gi={[G.MAINNET]:"bc1p",[G.TESTNET]:"tb1p",[G.SIGNET]:"tb1p"},Ci="https://tbv-faucet.testnet.babylonlabs.io/",dt=t=>t.installed&&!t.hardware?0:t.hardware?1:2,Ii=h.memo(({chain:t,className:e,append:n,onSelectWallet:i})=>{const r=h.useMemo(()=>t.wallets.filter(s=>s.id==="injectable"?s.installed:!0).sort((s,l)=>dt(s)-dt(l)),[t]),o=h.useMemo(()=>{var p;if(t.id!=="BTC")return null;const s=(p=t.config)==null?void 0:p.network,l=s?gi[s]:void 0;return l?{prefix:l,showFaucet:s!==G.MAINNET}:null},[t]),c=h.useCallback(async s=>{i==null||i(t,s)},[t,i]);return u.jsxs("div",{className:$.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight",e),children:[u.jsxs("div",{className:"flex flex-col gap-2 border-b border-secondary-strokeLight p-6",children:[u.jsx(R.Heading,{variant:"h5",className:"text-accent-primary",children:`Select ${t.name} Wallet`}),o&&u.jsxs(R.Text,{variant:"body2",className:"text-accent-secondary",children:[`To continue, connect a ${t.name} wallet with a `,u.jsx("span",{className:"text-accent-primary",children:`${o.prefix} (Taproot)`})," address.",o.showFaucet&&u.jsxs("span",{className:"block",children:[" Don't have testnet BTC yet? Get it from ",u.jsx("a",{href:Ci,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline underline-offset-2 transition-opacity hover:opacity-80",children:"Faucet"}),"."]})]})]}),u.jsxs("div",{className:"flex flex-col gap-2 p-6",children:[r.map(s=>u.jsx(mi,{installed:s.installed,hardware:s.hardware,label:s.label,name:s.name,logo:s.icon,logoBackground:s.iconBackground,fallbackLink:s.docs,onClick:()=>c(s)},s.id)),n]})]})});function Ni({widgets:t={},...e}){var s;const{chains:n,screen:i}=ee(),r=((s=i.params)==null?void 0:s.chain)??"",o=n==null?void 0:n[r],c=t==null?void 0:t[r];return u.jsx(Ii,{append:c,chain:o,...e})}const ut={CHAINS:({onConfirm:t,chainDescriptions:e,isChainHidden:n})=>u.jsx(oi,{onConfirm:t,chainDescriptions:e,isChainHidden:n}),WALLETS:({widgets:t,onSelectWallet:e})=>u.jsx(Ni,{widgets:t,onSelectWallet:e}),CONNECT_GUIDE:({onConnectWallet:t})=>u.jsx(ci,{onConnect:t}),LOADER:({current:t})=>{var e,n;return u.jsx(ui,{title:(e=t==null?void 0:t.params)==null?void 0:e.message,description:(n=t==null?void 0:t.params)==null?void 0:n.description})},ERROR:()=>u.jsx(di,{}),EMPTY:()=>u.jsx("div",{})};function wi(t){const e=ut[t.current.type]??ut.EMPTY;return u.jsx(e,{...t})}const oe="Wallet changed while confirming",Ti="Wallet did not report its network",Ai="Wallet network does not match the configured network",_i="Connected wallet has no provider";function yi(t,e){for(const n of e){const i=t.find(({chain:r})=>r===n);if(i)return i}return t[0]}function Fe(t){return Object.entries(t).flatMap(([e,n])=>{const i=n==null?void 0:n.connectedWallet;return i!=null&&i.account?[{chain:e,wallet:i,account:{...i.account}}]:[]})}function ft(t){return t.map(({chain:e,wallet:n,account:i})=>{const r={...i},o={id:n.id,name:n.name,icon:n.icon,iconBackground:n.iconBackground,docs:n.docs,installed:n.installed,provider:n.provider,account:r,label:n.label,hardware:n.hardware};return{chain:e,wallet:o,account:r}})}function vi(t,e,n){return t.every(({chain:i,wallet:r,provider:o,receipt:c})=>{const s=e.find(l=>l.chain===i);return s?s.wallet===r&&s.provider===o&&s.receipt===c:!n.includes(i)})}async function ht(t,e,n){const i=t(),r=Fe(i).map(d=>({connection:d,provider:d.wallet.provider,receipt:de([d],i)})),c=(await Promise.all(r.map(async d=>{var C,T;const{chain:f}=d.connection,{provider:E}=d;try{if(!E)throw new Error(`${_i}: ${f}`);if(((C=E.isIdentityCurrent)==null?void 0:C.call(E))===!1)throw new Error(oe);let g;if(f==="ETH"||f==="BTC"){if(g=f==="ETH"?await E.getChainId():await E.getNetwork(),g==null||!String(g))throw new Error(Ti);if(de([d.connection],i,{[f]:g})!==d.receipt)throw new Error(Ai)}const[I,y]=await Promise.all([E.getAddress(),E.getPublicKeyHex()]);if(!I||!y||!ie(I,d.connection.account.address)||!ie(y,d.connection.account.publicKeyHex))throw new Error(oe);if(((T=E.isIdentityCurrent)==null?void 0:T.call(E))===!1)throw new Error(oe);return{...d,connection:{...d.connection,account:{address:I,publicKeyHex:y}}}}catch(g){if(e.includes(f))throw g;return n==null||n(g instanceof Error?g:new Error("Optional wallet verification failed")),null}}))).filter(d=>d!==null),s=t(),l=Fe(s),p=c.flatMap(d=>{const{connection:f,receipt:E}=d,C=l.find(({chain:g})=>g===f.chain);if(!!(C&&C.wallet===f.wallet&&C.wallet.provider===d.provider&&de([C],s)===E))return[d];if(e.includes(f.chain))throw new Error(oe);return n==null||n(new Error(oe)),[]}),m=p.map(({connection:d})=>d),a=p.map(({connection:d,provider:f,receipt:E})=>({chain:d.chain,wallet:d.wallet,provider:f,receipt:E}));return{receipt:de(m,s),connections:m,identities:Object.freeze(a)}}function Ri({persistent:t,storage:e,config:n,onError:i,btcValidation:r,actions:o,closeButtonClassName:c,actionsClassName:s,chainDescriptions:l,isChainHidden:p}){const{visible:m,screen:a,confirmed:d,requiredChainIds:f,close:E,confirm:C,unconfirm:T,displayChains:g,displayWallets:I,displayError:y}=ee(),{acceptTermsOfService:N,onConfirm:W}=St(),B=me(),D=Zn(B,n,i),{connect:O,chooseWallet:S}=$n({persistent:t,accountStorage:e,onError:i,btcValidation:r}),K=h.useRef(B),k=h.useRef(0),b=h.useRef(null),w=h.useRef(null),_=h.useRef(!1),A=h.useRef(m),v=h.useRef(d),x=h.useRef({persistent:t,requiredChainIds:[...f],storage:e}),j=h.useCallback(()=>{const P=w.current;w.current=null,k.current+=1,b.current=null,P==null||P()},[]);h.useLayoutEffect(()=>{K.current=B,(A.current&&!m||!v.current&&d)&&j(),A.current=m,v.current=d},[d,B,j,m]),h.useLayoutEffect(()=>(_.current=!0,()=>{_.current=!1,j()}),[j]),h.useLayoutEffect(()=>{const P=x.current,U=P.requiredChainIds.length!==f.length||P.requiredChainIds.some((te,Ne)=>te!==f[Ne]);(P.persistent!==t||P.storage!==e||U)&&j(),x.current={persistent:t,requiredChainIds:[...f],storage:e}},[j,t,f,e]);const ge=h.useCallback(()=>{j(),E==null||E()},[E,j]),Ce=h.useCallback(async()=>{if(b.current!==null||!_.current||!A.current)return;const P=k.current+1;k.current=P,b.current=P;const U=()=>b.current===P&&k.current===P&&_.current&&A.current;let te=()=>{},Ne=!1;try{if(!d){const re=K.current,le=de(Fe(re),re),Gt=_t(le,yt(le),re,()=>{j(),e.delete(Y),T==null||T()});let Xe=!0;if(te=()=>{Xe&&(Xe=!1,Gt())},!U()){te();return}w.current=te;const we=await ht(()=>K.current,f,i);if(!U())return;const{connections:Te}=we,We=f.filter(je=>!Te.some(({chain:zt})=>zt===je));if(We.length>0)throw new Error(`No connected account for required chain${We.length>1?"s":""}: ${We.join(", ")}`);const Ae=yi(Te,f),qe=async()=>{if(!U())return!1;const je=await ht(()=>K.current,f,i);if(!U())return!1;if(!vi(we.identities,je.identities,f))throw new Error(oe);return!0};if(Ae&&(await(N==null?void 0:N({address:Ae.account.address,public_key:Ae.account.publicKeyHex,chain:Ae.chain,connections:ft(Te)})),!await qe())||(await(W==null?void 0:W(ft(Te))),!await qe())||(t&&e.set(Y,we.receipt),!U())||(C==null||C(we.receipt),!U()))return;Ne=!!C}if(!U())return;E==null||E()}catch(re){if(!U())return;const le=re instanceof Error?re:new Error("Wallet confirmation failed");if(i==null||i(le),!U())return;y==null||y({title:"Connection Failed",description:le.message,submitButton:"",cancelButton:"Done",onCancel:g})}finally{Ne||(te(),w.current===te&&(w.current=null),k.current===P&&b.current===P&&(b.current=null))}},[N,E,C,d,g,y,j,W,i,t,f,e,T]),Ie=a.type==="WALLETS"?g:a.type==="CONNECT_GUIDE"?()=>{var P;return I==null?void 0:I((P=a.params)==null?void 0:P.chain)}:void 0;return u.jsx(R.FullScreenDialog,{open:m,onClose:ge,onBack:Ie,className:"items-center justify-center p-6",actions:o,closeButtonClassName:c,actionsClassName:s,children:u.jsx("div",{className:"mx-auto w-full max-w-[612px]",children:u.jsx(wi,{current:a,widgets:D,onConfirm:Ce,onSelectWallet:S,onConnectWallet:O,chainDescriptions:l,isChainHidden:p})})})}function kt(t,e){const{enabled:n,delay:i=500}=e,r=h.useRef(null);h.useEffect(()=>{if(!n||typeof window>"u"||typeof document>"u")return;const o=()=>{document.visibilityState==="visible"&&(r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{Promise.resolve(t()).catch(c=>{console.error("Error in visibility check callback:",c instanceof Error?c.message:"Unknown error")})},i))};return document.addEventListener("visibilitychange",o),()=>{document.removeEventListener("visibilitychange",o),r.current&&(clearTimeout(r.current),r.current=null)}},[n,t,i])}const Ut=h.createContext({loading:!0,connected:!1,address:void 0,disconnect:()=>{},open:()=>{}}),xi=({children:t,callbacks:e})=>{const[n,i]=h.useState(!0),[r,o]=h.useState(),[c,s]=h.useState(null),{open:l,disconnect:p}=Ze(),m=Ft("ETH"),a=h.useCallback(async()=>{try{await(m==null?void 0:m.disconnect("local"))}catch(g){console.error("Failed to disconnect ETH connector:",g instanceof Error?g.message:"Unknown error")}},[m]),d=h.useCallback(async g=>{var I,y;try{o(g),i(!1),await((I=e==null?void 0:e.onConnect)==null?void 0:I.call(e,g))}catch(N){i(!1),(y=e==null?void 0:e.onError)==null||y.call(e,N instanceof Error?N:new Error("ETH connection failed"),{address:g})}},[e]);h.useEffect(()=>{if(i(!1),!m)return;(async()=>{var D;try{if((D=m.connectedWallet)!=null&&D.provider&&!r){const O=m.connectedWallet.provider,S=await O.getAddress();S&&(s(O),d(S));return}if(!r&&m.wallets.length>0){const O=m.wallets[0];if(O.provider)try{await O.provider.getAddress()&&await m.connect(O)}catch{}}}catch{}})();const I=m.on("connect",async D=>{if(D.provider)try{const O=await D.provider.getAddress();O&&(s(D.provider),d(O))}catch(O){console.error("Error getting ETH address:",O instanceof Error?O.message:"Unknown error")}}),y=m.wallets[0],N=y==null?void 0:y.provider;let W=!1;const B=D=>{!(D!=null&&D[0])||r||W||(W=!0,m.connect(y).then(O=>{O||(W=!1)}).catch(O=>{W=!1,console.error("ETH late reconnect failed:",O instanceof Error?O.message:"Unknown error")}))};return N&&typeof N.on=="function"&&N.on("accountsChanged",B),()=>{I(),N&&typeof N.off=="function"&&N.off("accountsChanged",B)}},[m,d,r]),h.useEffect(()=>{if(m)return m.on("disconnect",async()=>{var g;o(void 0),s(null);try{await((g=e==null?void 0:e.onDisconnect)==null?void 0:g.call(e))}catch(I){console.error("Error in onDisconnect callback:",I instanceof Error?I.message:"Unknown error")}})},[m,e]);const f=h.useRef(void 0),E=h.useRef(!1);h.useEffect(()=>{f.current=r},[r]),h.useEffect(()=>{if(!c)return;const g=async I=>{var W,B;if(E.current)return;const y=I[0],N=f.current;if(y&&y.toLowerCase()!==(N==null?void 0:N.toLowerCase())){E.current=!0,f.current=y,o(y);try{await((W=e==null?void 0:e.onAddressChange)==null?void 0:W.call(e,y))}catch(D){(B=e==null?void 0:e.onError)==null||B.call(e,D instanceof Error?D:new Error("ETH address change failed"),{address:y})}finally{E.current=!1}}else!y&&N&&a()};return typeof c.on=="function"&&c.on("accountsChanged",g),()=>{typeof c.off=="function"&&c.off("accountsChanged",g)}},[c,e,a]);const C=h.useCallback(async()=>{var g;if(c)try{const I=await c.getAddress();I?I.toLowerCase()!==(r==null?void 0:r.toLowerCase())&&(f.current=I,o(I),await((g=e==null?void 0:e.onAddressChange)==null?void 0:g.call(e,I))):a()}catch(I){console.error("ETH wallet connection check failed:",I instanceof Error?I.message:"Unknown error"),a()}},[c,r,e,a]);kt(C,{enabled:!!(c&&r)});const T=h.useMemo(()=>!!r,[r]);return u.jsx(Ut.Provider,{value:{loading:n,connected:T,address:r,disconnect:()=>p("ETH"),open:l},children:t})},Si=()=>h.useContext(Ut);exports.ACCOUNT_CHANGE_EVENTS=ke;exports.APPKIT_BTC_CONNECTOR_ID=Dt;exports.APPKIT_ETH_CONNECTOR_ID=Ye;exports.APPKIT_OPEN_EVENT=fe;exports.COSMOS_KEYSTORE_CHANGE_EVENTS=nn;exports.ChainProvider=Tn;exports.DISCONNECT_EVENT=Ge;exports.ERROR_CODES=J;exports.ETHWalletProvider=xi;exports.LifeCycleHooksProvider=An;exports.MONOCHROME_MARK_BACKGROUND=Ot;exports.NETWORK_CHANGE_EVENT=Ue;exports.Network=G;exports.ONEKEY_BRAND_GREEN=yn;exports.ONE_HOUR=on;exports.StateContext=Ve;exports.StateProvider=vt;exports.WALLET_MODAL_OPEN_EVENT=Se;exports.WalletDialog=Ri;exports.WalletError=ae;exports.assertAppKitCapabilities=Bt;exports.createAccountStorage=_n;exports.createAppKitCapabilities=bt;exports.createETHWagmiAdapter=Kt;exports.createExternalWallet=Nt;exports.failInitialization=F;exports.getAppKitState=Pe;exports.getSharedWagmiConfig=$e;exports.hasSharedWagmiConfig=Re;exports.initializeAppKitModal=Un;exports.isAccountChangeEvent=Jt;exports.isSharedSessionRefusal=he;exports.isUserRejectionMessage=cn;exports.metadata=kn;exports.okxLogo=Lt;exports.process$1=It;exports.registerManualAppKitConfig=Wt;exports.removeProviderListener=rn;exports.setAppKitState=Mt;exports.setSharedWagmiConfig=Dn;exports.trackProviderIdentityChanges=tn;exports.useAppKitOpenListener=Gn;exports.useChainConnector=Ft;exports.useETHWallet=Si;exports.useInscriptionProvider=pn;exports.useVisibilityCheck=kt;exports.useWalletConnect=Ze;exports.useWidgetState=ee;exports.validateAppKitInitialization=jt;
2
- //# sourceMappingURL=ETHWalletProvider-C8PygVM5.cjs.map
1
+ "use strict";var Yt=Object.defineProperty;var $t=(t,e,n)=>e in t?Yt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var L=(t,e,n)=>$t(t,typeof e!="symbol"?e+"":e,n);const xe=require("viem"),H=require("wagmi/actions"),Et=require("wagmi/connectors"),Zt=require("@reown/appkit-adapter-wagmi"),Qe=require("@reown/appkit/react"),Je=require("wagmi"),h=require("react"),u=require("react/jsx-runtime"),R=require("@babylonlabs-io/core-ui"),$=require("tailwind-merge");function Xt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var pt={exports:{}},M=pt.exports={},z,V;function Me(){throw new Error("setTimeout has not been defined")}function Be(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?z=setTimeout:z=Me}catch{z=Me}try{typeof clearTimeout=="function"?V=clearTimeout:V=Be}catch{V=Be}})();function mt(t){if(z===setTimeout)return setTimeout(t,0);if((z===Me||!z)&&setTimeout)return z=setTimeout,setTimeout(t,0);try{return z(t,0)}catch{try{return z.call(null,t,0)}catch{return z.call(this,t,0)}}}function qt(t){if(V===clearTimeout)return clearTimeout(t);if((V===Be||!V)&&clearTimeout)return V=clearTimeout,clearTimeout(t);try{return V(t)}catch{try{return V.call(null,t)}catch{return V.call(this,t)}}}var Z=[],se=!1,ne,ve=-1;function Qt(){!se||!ne||(se=!1,ne.length?Z=ne.concat(Z):ve=-1,Z.length&&gt())}function gt(){if(!se){var t=mt(Qt);se=!0;for(var e=Z.length;e;){for(ne=Z,Z=[];++ve<e;)ne&&ne[ve].run();ve=-1,e=Z.length}ne=null,se=!1,qt(t)}}M.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];Z.push(new Ct(t,e)),Z.length===1&&!se&&mt(gt)};function Ct(t,e){this.fun=t,this.array=e}Ct.prototype.run=function(){this.fun.apply(null,this.array)};M.title="browser";M.browser=!0;M.env={};M.argv=[];M.version="";M.versions={};function q(){}M.on=q;M.addListener=q;M.once=q;M.off=q;M.removeListener=q;M.removeAllListeners=q;M.emit=q;M.prependListener=q;M.prependOnceListener=q;M.listeners=function(t){return[]};M.binding=function(t){throw new Error("process.binding is not supported")};M.cwd=function(){return"/"};M.chdir=function(t){throw new Error("process.chdir is not supported")};M.umask=function(){return 0};var Jt=pt.exports;const It=Xt(Jt),ke=["accountChanged","accountsChanged"];function en(t){return ke.includes(t)}const Ue="networkChanged",tn="chainChanged",Ge="disconnect";function nn(t,e){if(typeof t.on!="function")return!1;try{t.on("accountsChanged",e)}catch{return!1}return[...ke.filter(i=>i!=="accountsChanged"),Ue,tn,Ge].forEach(i=>{var r;try{(r=t.on)==null||r.call(t,i,e)}catch{}}),!0}const Se="babylon-wallet#modal-open",rn=["keplr_keystorechange","leap_keystorechange","okx_keystorechange"];function on(t,e,n){typeof t.removeListener=="function"?t.removeListener(e,n):typeof t.off=="function"&&t.off(e,n)}const sn=3600*1e3;class De{constructor({id:e,origin:n,name:i,icon:r,iconBackground:o,docs:c,networks:s,provider:l,label:p,hardware:m,connectGuide:a}){L(this,"id");L(this,"origin");L(this,"name");L(this,"icon");L(this,"iconBackground");L(this,"docs");L(this,"networks");L(this,"provider",null);L(this,"hardware");L(this,"connectGuide");L(this,"_label");L(this,"account",null);this.id=e,this.origin=n,this.name=i,this.icon=r,this.iconBackground=o,this.docs=c,this.networks=s,this.provider=l,this._label=p,this.hardware=m??!1,this.connectGuide=a}get installed(){return!!this.provider}get label(){return this._label??(this.installed?"Installed":"")}async connect(e){if(!this.provider)throw Error("Provider not found");await this.provider.connectWallet(e);const[n,i]=await Promise.all([this.provider.getAddress(),this.provider.getPublicKeyHex()]);return this.account={address:n,publicKeyHex:i},this}clone(){return new De({id:this.id,origin:this.origin,name:this.name,icon:this.icon,iconBackground:this.iconBackground,docs:this.docs,networks:this.networks,provider:this.provider})}}let cn=()=>({emit(t,...e){for(let n=this.events[t]||[],i=0,r=n.length;i<r;i++)n[i](...e)},events:{},on(t,e){var n;return((n=this.events)[t]||(n[t]=[])).push(e),()=>{var i;this.events[t]=(i=this.events[t])==null?void 0:i.filter(r=>e!==r)}}});const J={UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_PARAMS:"INVALID_PARAMS",CONNECTION_FAILED:"CONNECTION_FAILED",METHOD_NOT_IMPLEMENTED:"METHOD_NOT_IMPLEMENTED",MAX_ITERATION_EXCEEDED:"MAX_ITERATION_EXCEEDED",EXTENSION_NOT_FOUND:"EXTENSION_NOT_FOUND",EXTENSION_CONTEXT_INVALIDATED:"EXTENSION_CONTEXT_INVALIDATED",CONNECTION_REJECTED:"CONNECTION_REJECTED",CONNECTION_CANCELED:"CONNECTION_CANCELED",CHAIN_ID_NOT_INITIALIZED:"CHAIN_ID_NOT_INITIALIZED",RPC_URL_NOT_INITIALIZED:"RPC_URL_NOT_INITIALIZED",FAILED_TO_ADD_CHAIN:"FAILED_TO_ADD_CHAIN",FAILED_TO_GET_KEY:"FAILED_TO_GET_KEY",WALLET_INITIALIZATION_FAILED:"WALLET_INITIALIZATION_FAILED",WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",INCOMPATIBLE_WALLET_VERSION:"INCOMPATIBLE_WALLET_VERSION",WALLET_METHOD_NOT_SUPPORTED:"WALLET_METHOD_NOT_SUPPORTED",WALLET_ACCOUNT_NOT_SUPPORTED:"WALLET_ACCOUNT_NOT_SUPPORTED",WALLET_ACCOUNT_CHANGED:"WALLET_ACCOUNT_CHANGED",NETWORK_NOT_ENABLED_IN_WALLET:"NETWORK_NOT_ENABLED_IN_WALLET",WALLET_CONFIG_REQUIRED:"WALLET_CONFIG_REQUIRED",SHARED_SESSION_DISCONNECT_REFUSED:"SHARED_SESSION_DISCONNECT_REFUSED",INVALID_PUBLIC_KEY:"INVALID_PUBLIC_KEY",ADDRESS_GENERATION_FAILED:"ADDRESS_GENERATION_FAILED",UNSUPPORTED_NETWORK:"UNSUPPORTED_NETWORK",INVALID_ADDRESS_PREFIX:"INVALID_ADDRESS_PREFIX",MISSING_PSBT_HEX:"MISSING_PSBT_HEX",PSBT_HEX_REQUIRED:"PSBT_HEX_REQUIRED",PSBTS_HEXES_REQUIRED:"PSBTS_HEXES_REQUIRED",SIGNATURE_EXTRACT_ERROR:"SIGNATURE_EXTRACT_ERROR",GENERATION_ERROR:"GENERATION_ERROR",ADDRESS_NOT_FOUND:"ADDRESS_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",EMPTY_WITNESS_STACK:"EMPTY_WITNESS_STACK",QR_READ_ERROR:"QR_READ_ERROR",QR_SCAN_ERROR:"QR_SCAN_ERROR",DEVICE_CEREMONY_INVALID:"DEVICE_CEREMONY_INVALID",DEVICE_LOCKED:"DEVICE_LOCKED",DEVICE_WRONG_APP:"DEVICE_WRONG_APP",DEVICE_DISCONNECTED:"DEVICE_DISCONNECTED",INSCRIPTIONS_UNSUPPORTED_NETWORK:"INSCRIPTIONS_UNSUPPORTED_NETWORK",INSCRIPTION_FETCH_ERROR:"INSCRIPTION_FETCH_ERROR"};class ae extends Error{constructor({code:n,message:i,wallet:r,version:o,chainId:c},s){super(i,s);L(this,"code");L(this,"wallet");L(this,"version");L(this,"chainId");this.code=n,this.wallet=r,this.version=o,this.chainId=c}}function an(t){if(!t)return!1;const e=t.toLowerCase();return e.includes("user rejected")||e.includes("user denied")||e.includes("user cancelled")||e.includes("user canceled")}function he(t){return t instanceof ae&&t.code===J.SHARED_SESSION_DISCONNECT_REFUSED}class ze{constructor(e,n,i,r,o){L(this,"_connectedWallet",null);L(this,"_connectionGeneration",0);L(this,"_ee",cn());this.id=e,this.name=n,this.icon=i,this.wallets=r,this.config=o}get connectedWallet(){return this._connectedWallet}async connect(e){try{const n=typeof e=="string"?this.wallets.find(r=>r.id===e):e;if(!n)throw new ae({code:J.EXTENSION_NOT_FOUND,message:"Wallet not found"});this._ee.emit("connecting",`Connecting ${n.name}`);const i=(r,o)=>this._ee.emit("connecting",r,o);return await n.connect(i),this._connectedWallet=n,this._connectionGeneration+=1,this._ee.emit("connect",this._connectedWallet),this.connectedWallet}catch(n){return this._ee.emit("error",n),null}}async disconnect(e="chain"){const n=this._connectedWallet,i=this._connectionGeneration;if(!n)return;const r=n.provider;if(r!=null&&r.disconnect)try{await r.disconnect(e)}catch(o){if(e==="chain"&&he(o)||(this._ee.emit("error",o instanceof Error?o:new Error(String(o))),e==="chain"))throw o}this._connectedWallet!==n||this._connectionGeneration!==i||(this._connectedWallet=null,this._ee.emit("disconnect",n))}clone(){return new ze(this.id,this.name,this.icon,this.wallets,this.config)}on(e,n){return this._ee.on(e,n)}}var G=(t=>(t.MAINNET="mainnet",t.TESTNET="testnet",t.SIGNET="signet",t))(G||{});const ln=t=>e=>e[t],dn=async({metadata:t,context:e,config:n})=>{const{id:i,wallet:r,name:o,icon:c,iconBackground:s,docs:l="",networks:p=[],createProvider:m,label:a,hardware:d,connectGuide:f}=t,E={id:i,name:"",icon:"",iconBackground:s,origin:null,provider:null,docs:l,networks:p,label:a,hardware:d,connectGuide:f==null?void 0:f(n)};if(r){const C=typeof r=="string"?ln(r):r;E.origin=await C(e,n)??null,E.provider=E.origin?m(E.origin,n):null}else E.origin=null,E.provider=m(null,n);return typeof o=="string"?E.name=o??"":E.name=E.origin?await o(E.origin,n):"",typeof c=="string"?E.icon=c??"":E.icon=E.origin?await c(E.origin,n):"",new De(E)},Nt=({id:t,name:e,icon:n,provider:i})=>new De({id:t,origin:null,name:e,icon:n,docs:"",networks:[G.MAINNET,G.SIGNET],provider:i}),wt=async({persistent:t,metadata:e,context:n,config:i,accountStorage:r,disabledWallets:o})=>{const c=[],s=t?r.get(e.chain):void 0;for(const d of e.wallets)o!=null&&o.includes(d.id)||c.push(await dn({metadata:d,context:n,config:i}));const l=c.find(d=>d.id==="injectable"&&d.installed),p=c.filter(d=>d.name.toLowerCase()!==(l==null?void 0:l.name.toLowerCase())||d.id==="injectable"),m=new ze(e.chain,e.name,e.icon,p,i);return e.chain!=="ETH"&&s&&c.some(d=>d.id===s&&d.installed)&&m.connect(s).catch(d=>{console.error("Auto-reconnect failed:",d instanceof Error?d.message:"Unknown error")}),m};function un({connectors:t,storage:e,allowReconnect:n,persistent:i,eligibleChainIds:r}){if(!n||!i)return[];const o=[];for(const c of t){if(!r.has(c.id)||c.connectedWallet)continue;const s=e.get(c.id);s&&c.wallets.some(l=>l.id===s&&l.installed)&&o.push({connector:c,walletId:s})}return o}const et="unisat#initialized",fn=3e3;function hn({connectors:t,setConnectors:e,config:n,context:i,storage:r,disabledWallets:o,persistent:c,metadata:s}){const l=h.useRef(t);l.current=t;const p=Object.values(t).some(Boolean);h.useEffect(()=>{if(!p)return;let m=!1,a=!1;const d=new Set,f=new Set,E=async N=>{if(!(m||a)){m=!0;try{await C(N)}finally{m=!1}}},C=async N=>{const W=Object.values(l.current).filter(Boolean).filter(S=>!!s[S.id]&&!S.connectedWallet&&S.wallets.some(K=>K.id!=="injectable"&&!K.installed));let B=[];if(W.length>0){const S=await Promise.all(W.map(b=>{var w;return wt({persistent:!1,metadata:s[b.id],context:i,config:(w=n.find(_=>_.chain===b.id))==null?void 0:w.config,accountStorage:r,disabledWallets:o}).catch(()=>null)}));if(a)return;const K=S.filter(b=>{if(!b)return!1;const w=l.current[b.id];if(!w||w.connectedWallet)return!1;const _=new Set(w.wallets.filter(A=>A.installed).map(A=>A.id));return b.wallets.some(A=>A.installed&&!_.has(A.id))});for(const b of K)f.add(b.id);const k=l.current;B=K.filter(b=>{var w;return!((w=k[b.id])!=null&&w.connectedWallet)}),B.length>0&&e(b=>{var _;const w={};for(const A of B)(_=b[A.id])!=null&&_.connectedWallet||(w[A.id]=A);return Object.keys(w).length>0?{...b,...w}:b})}if(!N||!c||f.size===0)return;const D={};for(const S of Object.values(l.current))S&&(D[S.id]=S);for(const S of B)D[S.id]=S;const O=un({connectors:Object.values(D),storage:r,allowReconnect:N,persistent:c,eligibleChainIds:f});for(const{connector:S,walletId:K}of O)d.has(S.id)||(d.add(S.id),S.connect(K).then(k=>{d.delete(S.id),k&&f.delete(S.id)}).catch(()=>d.delete(S.id)))},T=()=>void E(!0),g=()=>void E(!1),I=setTimeout(T,fn),y=typeof window<"u";return y&&(window.addEventListener(et,T,{once:!0}),window.addEventListener(Se,g)),()=>{a=!0,clearTimeout(I),y&&(window.removeEventListener(et,T),window.removeEventListener(Se,g))}},[p,n,i,r,o,e,c,s])}function En(t,e,n){function i(){const c=n;if(typeof e>"u")return c;const s=e.getItem(t);return(s?JSON.parse(s):null)??c}const[r,o]=h.useState(i);return h.useEffect(function(){e.setItem(t,JSON.stringify(r??""))},[t,e,r]),[r,o]}const Tt=h.createContext({lockInscriptions:!0});function pn({children:t,context:e}){const[n,i]=En("bwc-inscription-modal-lock",e.localStorage,!0),r=h.useMemo(()=>({lockInscriptions:n,toggleLockInscriptions:i}),[n,i]);return u.jsx(Tt.Provider,{value:r,children:t})}const mn=()=>h.useContext(Tt),Y="__babylon-wallet-confirmation-v1__",At=2,gn={BTC:["accountsChanged",Ue,Ge],BBN:["accountChanged"],ETH:["accountsChanged","chainChanged"]};function Ee(t,e){return t[e]}function be(t,e,n){var o;const i=(o=Ee(t,e))==null?void 0:o.config,r=(n==null?void 0:n[e])??(e==="BTC"?i==null?void 0:i.network:i==null?void 0:i.chainId);return r===void 0?"":String(r)}function ie(t,e){return t.toLowerCase()===e.toLowerCase()}function Cn(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const e=t;return typeof e.chain=="string"&&typeof e.walletId=="string"&&typeof e.address=="string"&&typeof e.publicKeyHex=="string"&&typeof e.network=="string"}function pe(t){if(t)try{const e=JSON.parse(t);return(e==null?void 0:e.version)!==At||!Array.isArray(e.entries)||!e.entries.every(Cn)?void 0:e}catch{return}}function de(t,e,n){const i=t.filter(r=>r.account&&Ee(e,r.chain)).map(r=>({chain:r.chain,walletId:r.wallet.id,address:r.account.address,publicKeyHex:r.account.publicKeyHex,network:be(e,r.chain,n)})).sort((r,o)=>r.chain.localeCompare(o.chain));return JSON.stringify({version:At,entries:i})}function In(t,e,n){var r;const i=(r=pe(t))==null?void 0:r.entries;return i?e.every(o=>{var m;const c=o,s=(m=Ee(n,c))==null?void 0:m.connectedWallet,l=s==null?void 0:s.account,p=i.find(a=>a.chain===c);return!!(s&&l&&p&&p.walletId===s.id&&ie(p.address,l.address)&&ie(p.publicKeyHex,l.publicKeyHex)&&p.network===be(n,c))}):!1}function Nn(t,e,n){var r;const i=(r=pe(t))==null?void 0:r.entries;return i?e.every(o=>{var p;const c=o,s=(p=Ee(n,c))==null?void 0:p.connectedWallet,l=i.find(m=>m.chain===c);return!!(s&&l&&l.walletId===s.id&&l.network===be(n,c))}):!1}async function wn(t,e,n){var o;const i=(o=pe(t))==null?void 0:o.entries;return i?(await Promise.all(e.map(async c=>{var d,f;const s=c,l=Ee(n,s),p=l==null?void 0:l.connectedWallet,m=p==null?void 0:p.provider,a=i.find(E=>E.chain===s);if(!p||!m||!a||a.walletId!==p.id)return!1;try{if(((d=m.isIdentityCurrent)==null?void 0:d.call(m))===!1)return!1;const[E,C,T]=await Promise.all([m.getAddress(),m.getPublicKeyHex(),s==="ETH"?m.getChainId():s==="BTC"?m.getNetwork():be(n,s)]);return((f=m.isIdentityCurrent)==null?void 0:f.call(m))===!1?!1:ie(a.address,E)&&ie(a.publicKeyHex,C)&&a.network===String(T)}catch{return!1}}))).every(Boolean):!1}function _t(t,e,n,i){var c;const r=(c=pe(t))==null?void 0:c.entries;if(!r)return()=>{};const o=[];return e.forEach(s=>{var m,a,d;const l=s,p=(a=(m=n[l])==null?void 0:m.connectedWallet)==null?void 0:a.provider;p!=null&&p.on&&((d=gn[l])==null||d.forEach(f=>{var C;const E=(...T)=>{const g=T[0],I=r.find(y=>y.chain===l);l==="ETH"&&f==="accountsChanged"&&Array.isArray(g)&&g.length===1&&typeof g[0]=="string"&&I&&ie(I.address,g[0])||i(l)};try{(C=p.on)==null||C.call(p,f,E),o.push({event:f,handler:E,provider:p})}catch{}}))}),()=>{o.forEach(({event:s,handler:l,provider:p})=>{var m;try{(m=p.off)==null||m.call(p,s,l)}catch{}})}}function yt(t){var e;return((e=pe(t))==null?void 0:e.entries.map(n=>n.chain))??[]}const He={confirmed:!1,visible:!1,screen:{type:"CHAINS"},chains:{},selectedWallets:{},requiredChainIds:[]},Ve=h.createContext(He);function Tn(t,e){return Object.keys(t).reduce((n,i)=>(e.has(i)&&(n[i]=t[i]),n),{})}function vt({children:t,chains:e,requiredChainIds:n,storage:i}){const[r,o]=h.useState(()=>({...He,chains:e.reduce((a,d)=>({...a,[d.id]:d}),{}),requiredChainIds:[...n]})),c=n.some(a=>!r.requiredChainIds.includes(a)),s=h.useMemo(()=>({...r,confirmed:c?!1:r.confirmed,requiredChainIds:[...n]}),[n,c,r]),l=h.useRef(n);h.useInsertionEffect(()=>{l.current=n},[n]),h.useEffect(()=>{o(a=>{const d=e.reduce((T,g)=>({...T,[g.id]:g}),{}),f=new Set(e.map(T=>T.id)),E=Tn(a.selectedWallets,f),C=n.some(T=>!a.requiredChainIds.includes(T));return{...a,confirmed:C?!1:a.confirmed,chains:d,selectedWallets:E,requiredChainIds:[...n]}})},[e,n]);const p=h.useMemo(()=>({open:()=>{typeof window<"u"&&window.dispatchEvent(new Event(Se)),o(a=>({...a,visible:!0}))},close:()=>{o(a=>({...a,visible:!1}))},reset:()=>{i==null||i.delete(Y),o(({chains:a,requiredChainIds:d})=>({...He,chains:a,requiredChainIds:d}))},displayLoader:(a="",d="")=>{o(f=>({...f,screen:{type:"LOADER",params:{message:a,description:d}}}))},displayChains:()=>{o(a=>({...a,screen:{type:"CHAINS"}}))},displayWallets:a=>{o(d=>({...d,screen:{type:"WALLETS",params:{chain:a}}}))},displayConnectGuide:(a,d)=>{o(f=>({...f,screen:{type:"CONNECT_GUIDE",params:{chain:a,wallet:d}}}))},displayError:a=>{o(d=>({...d,screen:{type:"ERROR",params:a}}))},selectWallet:(a,d)=>{o(f=>({...f,selectedWallets:{...f.selectedWallets,[a]:d}}))},removeWallet:a=>{const d=l.current.includes(a);d&&(i==null||i.delete(Y)),o(f=>({...f,confirmed:d?!1:f.confirmed,confirmationReceipt:d?void 0:f.confirmationReceipt,selectedWallets:{...f.selectedWallets,[a]:void 0}}))},confirm:a=>{o(d=>({...d,confirmed:!0,confirmationReceipt:a}))},unconfirm:(a=!1)=>{o(d=>({...d,confirmed:!1,confirmationReceipt:a?d.confirmationReceipt:void 0}))}}),[i]),m=h.useMemo(()=>({...s,...p}),[s,p]);return u.jsx(Ve.Provider,{value:m,children:t})}const Ke={BTC:null,BBN:null,ETH:null},Rt=h.createContext(Ke);function An({persistent:t,storage:e,children:n,context:i,config:r,onError:o,disabledWallets:c,requiredChains:s,metadata:l}){const[p,m]=h.useState(Ke),a=h.useCallback(async()=>{const C=r.filter(g=>l[g.chain]).map(async({chain:g,config:I})=>{const y=l[g];if(!y)return null;try{return await wt({persistent:t,metadata:y,context:i,config:I,accountStorage:e,disabledWallets:c})}catch(N){throw console.error("[ChainProvider] failed to create connector for chain:",g,N instanceof Error?N.message:"Unknown error"),N}});return(await Promise.all(C)).reduce((g,I)=>I?{...g,[I.id]:I}:g,{...Ke})},[t,r,i,e,c,l]);h.useEffect(()=>{a().then(E=>{m(E)}).catch(E=>{console.error("[ChainProvider] init failed with error:",E instanceof Error?E.message:"Unknown error"),o==null||o(E)})},[m,a,o]),hn({connectors:p,setConnectors:m,config:r,context:i,storage:e,disabledWallets:c,persistent:t,metadata:l}),h.useEffect(()=>{const E=Object.values(p).filter(Boolean);if(E.length===0)return;const C=()=>m(g=>({...g})),T=E.flatMap(g=>[g.on("connect",C),g.on("disconnect",C)]);return()=>T.forEach(g=>g())},[p]);const d=h.useMemo(()=>Object.values(p).filter(E=>!!E),[p]),f=h.useMemo(()=>s===void 0?r.filter(E=>l[E.chain]).map(E=>E.chain):[...s],[r,l,s]);return u.jsx(pn,{context:i,children:u.jsx(vt,{chains:d,requiredChainIds:f,storage:e,children:u.jsx(Rt.Provider,{value:p,children:n})})})}const me=()=>h.useContext(Rt),xt=h.createContext({});function _n({children:t,value:e}){const n=h.useMemo(()=>e??{},[e]);return u.jsx(xt.Provider,{value:n,children:t})}const St=()=>h.useContext(xt),ue="baby-connected-wallet-accounts";function _e(t,e){const n=e==null?void 0:e[t];return n?`${t}:${n}`:t}function ye(){const t=localStorage.getItem(ue);if(!t)return{};try{const e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?(localStorage.removeItem(ue),{}):e}catch(e){return console.error("[account-storage] Failed to parse accounts map, clearing corrupted entry:",e),localStorage.removeItem(ue),{}}}function tt(t){try{localStorage.setItem(ue,JSON.stringify(t))}catch(e){console.error("[account-storage] Failed to write accounts map, clearing entry:",e),localStorage.removeItem(ue)}}const yn=(t,e)=>{function n(r){const o=r._timestamps;return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}function i(r,o){const s=n(r)[o];if(typeof s!="number"||!Number.isFinite(s))return!0;const l=Date.now();return s<0||s>l+t?!0:l-s>t}return{get:r=>{const o=ye(),c=_e(r,e);if(!i(o,c))return o[c]},has:r=>{const o=ye(),c=_e(r,e);return i(o,c)?!1:!!o[c]},set:(r,o)=>{const c=ye(),s=_e(r,e),l=n(c);c[s]=o,c._timestamps={...l,[s]:Date.now()},tt(c)},delete:r=>{const o=ye(),c=_e(r,e),s=n(o),l=Reflect.deleteProperty(o,c);return delete s[c],o._timestamps=s,tt(o),l}}},Ot="#000000",vn="#1FE121",Lt="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20width='225px'%20height='224px'%20viewBox='0%200%20225%20224'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3ctitle%3eokx%3c/title%3e%3cg%20id='Page-1'%20stroke='none'%20strokeWidth='1'%20fill='none'%20fill-rule='evenodd'%3e%3cg%20id='okx'%20transform='translate(0.401000,%200.006000)'%20fill='%23FFFFFF'%20fill-rule='nonzero'%3e%3cpath%20d='M144.382,74.667%20L79.673,74.667%20C76.924,74.667%2074.695,76.895%2074.695,79.644%20L74.695,144.354%20C74.695,147.103%2076.924,149.332%2079.673,149.332%20L144.382,149.332%20C147.131,149.332%20149.36,147.103%20149.36,144.354%20L149.36,79.644%20C149.36,76.895%20147.131,74.667%20144.382,74.667%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,0%20L4.978,0%20C2.229,0%200,2.228%200,4.978%20L0,69.687%20C0,72.436%202.229,74.665%204.978,74.665%20L69.687,74.665%20C72.437,74.665%2074.665,72.436%2074.665,69.687%20L74.665,4.978%20C74.665,2.228%2072.437,0%2069.687,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,0%20L154.307,0%20C151.558,0%20149.329,2.228%20149.329,4.978%20L149.329,69.687%20C149.329,72.436%20151.558,74.665%20154.307,74.665%20L219.017,74.665%20C221.766,74.665%20223.994,72.436%20223.994,69.687%20L223.994,4.978%20C223.994,2.228%20221.766,0%20219.017,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,149.328%20L4.978,149.328%20C2.229,149.328%200,151.556%200,154.305%20L0,219.015%20C0,221.764%202.229,223.993%204.978,223.993%20L69.687,223.993%20C72.437,223.993%2074.665,221.764%2074.665,219.015%20L74.665,154.305%20C74.665,151.556%2072.437,149.328%2069.687,149.328%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,149.328%20L154.307,149.328%20C151.558,149.328%20149.329,151.556%20149.329,154.305%20L149.329,219.015%20C149.329,221.764%20151.558,223.993%20154.307,223.993%20L219.017,223.993%20C221.766,223.993%20223.994,221.764%20223.994,219.015%20L223.994,154.305%20C223.994,151.556%20221.766,149.328%20219.017,149.328%20Z'%20id='Path'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/svg%3e",fe="babylon:open-appkit",Ye="appkit-eth-connector",Dt="appkit-btc-connector",nt="bigint",it="function",Rn="AppKit configuration cannot be serialized.",xn=1,rt=new WeakMap;let Sn=xn;function On(t){const e=rt.get(t);if(e)return e;const n=Sn++;return rt.set(t,n),n}function ot(t){const e=JSON.stringify(t,(n,i)=>typeof i===nt?{type:nt,value:i.toString()}:typeof i===it?{type:it,value:On(i)}:i&&typeof i=="object"&&!Array.isArray(i)?Object.fromEntries(Object.entries(i).sort(([r],[o])=>r<o?-1:r>o?1:0)):i);if(e===void 0)throw new TypeError(Rn);return e}function bt({projectId:t,metadata:e,ethChain:n,btcNetwork:i}){return Object.freeze({projectId:t,metadataFingerprint:ot(e),ethFingerprint:n?ot(n):void 0,btcNetwork:i})}let X=null,Pt=null;const Oe=new Set;function F(t,e){throw new ae({code:J.WALLET_INITIALIZATION_FAILED,message:t,chainId:e})}function Pe(){return X}function Le(){return(X==null?void 0:X.modal)??Pt}function Wt(t,e){X&&F(`Cannot set a manual ${t} AppKit configuration after AppKit initialization. Use the canonical AppKit state.`),Oe.add(t),e&&(Pt=e)}function jt(t){return t?(Oe.size>0&&F(`Cannot initialize AppKit after a manual ${[...Oe].join(" and ")} configuration was set. Use only one initialization method.`),!0):(X&&F("AppKit is already initialized. A project ID is required to validate the requested configuration."),!1)}function Mt(t){return X&&F("AppKit is already initialized. Reuse the shared AppKit state instead of replacing it."),Oe.size>0&&F("Cannot publish AppKit state after a manual shared configuration was set."),X=Object.freeze({...t,btcConfig:t.btcConfig?Object.freeze({...t.btcConfig}):void 0}),X}function Bt(t,e){t.projectId!==e.projectId&&F("AppKit was already initialized with a different project ID. A page can use only one AppKit configuration."),t.metadataFingerprint!==e.metadataFingerprint&&F("AppKit was already initialized with different metadata. A page can use only one AppKit configuration."),e.ethFingerprint&&(t.ethFingerprint||F("AppKit was already initialized without Ethereum support. A page that needs Ethereum must initialize AppKit with Ethereum first.","ETH"),t.ethFingerprint!==e.ethFingerprint&&F("AppKit was already initialized with a different Ethereum chain configuration.","ETH")),e.btcNetwork&&(t.btcNetwork||F("AppKit was already initialized without Bitcoin support. A page that needs Bitcoin must initialize AppKit with Bitcoin first.","BTC"),t.btcNetwork!==e.btcNetwork&&F("AppKit was already initialized with a different Bitcoin network.","BTC"))}function st(t,e){if(typeof document>"u"){const l=setTimeout(t,e);return()=>clearTimeout(l)}let n=e,i=0,r;const o=()=>{i=Date.now(),r=setTimeout(()=>{document.removeEventListener("visibilitychange",s),t()},n)},c=()=>{clearTimeout(r),r=void 0,n=Math.max(0,n-(Date.now()-i))},s=()=>{document.visibilityState==="hidden"?r!==void 0&&c():r===void 0&&o()};return document.addEventListener("visibilitychange",s),document.visibilityState!=="hidden"&&o(),()=>{clearTimeout(r),document.removeEventListener("visibilitychange",s)}}const Ln="Ethereum",Dn="Shared wagmi config is being replaced. This might indicate multiple initializations.";let ce=null;function bn(t){Wt(Ln),ce&&ce!==t&&console.warn(Dn),ce=t}function $e(){const t=Pe();if(t)return t.wagmiConfig||F("AppKit was initialized without Ethereum support. Initialize it with Ethereum support.","ETH"),t.wagmiConfig;if(!ce)throw new Error("Shared wagmi config not initialized. Initialize AppKit with Ethereum support, or use setSharedWagmiConfig() as an exclusive manual alternative.");return ce}function Re(){const t=Pe();return t?t.wagmiConfig!==void 0:ce!==null}function Ht(){var n;const t=Le();return(t==null?void 0:t.getProviderType("eip155"))==="WALLET_CONNECT"&&((n=t==null?void 0:t.getAccount("bip122"))==null?void 0:n.isConnected)===!0}const Pn=1500,Wn=6e4,Kt=3e3,ct="Wallet not connected",jn="Ethereum Wallet",Mn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=";function Q(t){return t&&xe.isAddress(t,{strict:!1})?t:void 0}class Bn{constructor(e){L(this,"config");L(this,"address");L(this,"chainId");L(this,"eventHandlers",new Map);L(this,"unwatchFunctions",[]);L(this,"emptyAccountTimer");this.config=e,this.ensureEventWatchers()}ensureEventWatchers(){this.unwatchFunctions.length>0||Re()&&this.setupEventWatchers()}getWagmiConfig(){if(!Re())throw new Error("AppKit ETH not initialized. Ensure AppKit modal is initialized at application startup by calling initializeAppKitModal() with eth config in your app's entry point.");return $e()}setupEventWatchers(){const e=this.getWagmiConfig(),n=H.getAccount(e),i=Q(n.address);i&&n.status==="connected"&&(this.address=i,this.chainId=n.chainId,setTimeout(()=>{this.emit("accountsChanged",[i])},100));const r=H.watchAccount(e,{onChange:c=>{const s=this.address,l=Q(c.address);if(!l){if(!s){this.chainId=c.chainId;return}if(this.emptyAccountTimer!==void 0)return;this.emptyAccountTimer=setTimeout(()=>{this.emptyAccountTimer=void 0,this.address=void 0,this.chainId=void 0,this.emit("accountsChanged",[])},Kt);return}this.clearEmptyAccountTimer(),this.address=l,this.chainId=c.chainId,(s==null?void 0:s.toLowerCase())!==l.toLowerCase()&&this.emit("accountsChanged",[l])}}),o=H.watchChainId(e,{onChange:c=>{const s=this.chainId;this.chainId=c,s!==c&&this.emit("chainChanged",`0x${c.toString(16)}`)}});this.unwatchFunctions.push(r,o,()=>this.clearEmptyAccountTimer())}clearEmptyAccountTimer(){clearTimeout(this.emptyAccountTimer),this.emptyAccountTimer=void 0}emit(e,n){const i=this.eventHandlers.get(e);i&&i.forEach(r=>r(n))}async connectWallet(){try{const e=this.getWagmiConfig();this.ensureEventWatchers();const n=H.getAccount(e),i=Q(n.address);if(i){this.address=i,this.chainId=n.chainId;return}if(typeof window<"u"){await new Promise((l,p)=>{let m=!1,a;const d=()=>{f(),a==null||a(),E(),T==null||T()},f=st(()=>{d(),p(new Error("Connection timeout"))},Wn),E=H.watchAccount(e,{onChange:g=>{const I=Q(g.address);I&&(this.address=I,this.chainId=g.chainId,d(),l())}}),C=Le(),T=C==null?void 0:C.subscribeState(g=>{if(g.open)m=!0,a==null||a(),a=void 0;else if(m){const I=H.getAccount(e),y=Q(I.address);if(y){this.address=y,this.chainId=I.chainId,d(),l();return}if(a)return;a=st(()=>{const N=H.getAccount(e),W=Q(N.address);W?(this.address=W,this.chainId=N.chainId,d(),l()):(d(),p(new Error("Connection cancelled")))},Pn)}});window.dispatchEvent(new CustomEvent(fe))});return}const r=It.env.NEXT_PUBLIC_REOWN_PROJECT_ID;if(!r)throw new Error("NEXT_PUBLIC_REOWN_PROJECT_ID environment variable is required");const o=Et.walletConnect({projectId:r,metadata:{name:"Babylon Vault",description:"",url:"",icons:[""]}}),c=await H.connect(e,{connector:o});this.address=Q(c.accounts[0]),this.chainId=c.chainId}catch(e){throw console.error("Failed to connect wallet:",e instanceof Error?e.message:"Unknown error"),new Error(`Failed to connect wallet: ${e instanceof Error?e.message:"Unknown error"}`)}}async disconnect(e){if(e==="chain"&&Ht())throw new ae({code:J.SHARED_SESSION_DISCONNECT_REFUSED,message:"Ethereum and Bitcoin share one wallet session. Disconnecting Ethereum alone would also disconnect Bitcoin. Disconnect all wallets instead.",wallet:"AppKit",chainId:"ETH"});e!=="local"&&await H.disconnect(this.getWagmiConfig()),this.clearEmptyAccountTimer(),this.address=void 0,this.chainId=void 0}async getAddress(){const e=this.getWagmiConfig(),n=H.getAccount(e),i=Q(n.address);if(i)return this.address=i,this.chainId=n.chainId,i;if(this.address)return this.address;throw new Error(ct)}async getPublicKeyHex(){return this.getAddress()}async signMessage(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.signMessage(n,{message:e,account:i})}catch(n){throw new Error(`Failed to sign message: ${n}`)}}async signTypedData(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.signTypedData(n,{account:i,domain:{...e.domain,salt:e.domain.salt,verifyingContract:e.domain.verifyingContract},types:e.types,primaryType:e.primaryType,message:e.message})}catch(n){throw new Error(`Failed to sign typed data: ${n}`)}}async sendTransaction(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.sendTransaction(n,{account:i,to:e.to,value:e.value?xe.parseEther(e.value):void 0,data:e.data,gas:e.gasLimit,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce})}catch(n){throw new Error(`Failed to send transaction: ${n}`)}}async estimateGas(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await H.estimateGas(n,{account:i,to:e.to,value:e.value?xe.parseEther(e.value):void 0,data:e.data})}catch(n){throw new Error(`Failed to estimate gas: ${n}`)}}async getChainId(){if(this.chainId)return this.chainId;const e=this.getWagmiConfig(),n=H.getAccount(e);if(n.chainId)return this.chainId=n.chainId,this.chainId;throw new Error(ct)}async switchChain(e){try{const n=this.getWagmiConfig();if(![1,11155111,31337].includes(e))throw new Error(`Unsupported chain ID: ${e}`);await H.switchChain(n,{chainId:e}),this.chainId=e}catch(n){throw new Error(`Failed to switch chain: ${n}`)}}async getBalance(){try{const e=this.getWagmiConfig(),n=await this.getAddress();return(await H.getBalance(e,{address:n})).value}catch(e){throw new Error(`Failed to get balance: ${e}`)}}async getNonce(){try{const e=this.getWagmiConfig(),n=await this.getAddress();return await H.getTransactionCount(e,{address:n})}catch(e){throw new Error(`Failed to get nonce: ${e}`)}}async getNetworkInfo(){const e=await this.getChainId();return{name:this.config.chainName||"Ethereum",chainId:e.toString()}}getActiveConnectorIdentity(){var n;const e=(n=Le())==null?void 0:n.getWalletInfo("eip155");if(e!=null&&e.name||e!=null&&e.icon)return{name:e.name,icon:e.icon};if(Re())try{const{connector:i}=H.getAccount(this.getWagmiConfig());return i?{name:i.name,icon:i.icon}:void 0}catch{return}}getWalletProviderName(){var n;const e=(n=this.getActiveConnectorIdentity())==null?void 0:n.name;return e!=null&&e.trim()?e:jn}getWalletProviderIcon(){var n;const e=(n=this.getActiveConnectorIdentity())==null?void 0:n.icon;return e!=null&&e.trim()?e:Mn}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(n)}off(e,n){const i=this.eventHandlers.get(e);i&&i.delete(n)}destroy(){this.unwatchFunctions.forEach(e=>e()),this.eventHandlers.clear()}}const Hn="AppKit",Kn={id:Ye,name:Hn,icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=",docs:"https://docs.reown.com/appkit/overview",wallet:void 0,createProvider:(t,e)=>new Bn(e),networks:[G.MAINNET,G.TESTNET,G.SIGNET],label:"Connect ETH Wallet"},Fn="data:image/svg+xml,%3csvg%20enable-background='new%200%200%201920%201920'%20viewBox='0%200%201920%201920'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='m959.8%2080.7-539.7%20895.6%20539.7-245.3z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%20731-539.7%20245.3%20539.7%20319.1z'%20fill='%2362688f'/%3e%3cpath%20d='m1499.6%20976.3-539.8-895.6v650.3z'%20fill='%2362688f'/%3e%3cpath%20d='m959.8%201295.4%20539.8-319.1-539.8-245.3z'%20fill='%23454a75'/%3e%3cpath%20d='m420.1%201078.7%20539.7%20760.6v-441.7z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%201397.6v441.7l540.1-760.6z'%20fill='%2362688f'/%3e%3c/svg%3e",kn={chain:"ETH",name:"Ethereum",icon:Fn,wallets:[Kn]};function Ft(t,e){const n=t.rpcUrls.default.http[0];return new Zt.WagmiAdapter({networks:[t],projectId:e,ssr:!1,storage:Je.createStorage({storage:Je.cookieStorage}),connectors:[Et.baseAccount({preference:{telemetry:!1}})],transports:{[t.id]:xe.http(n)}})}function Un(t){if(!jt(t.projectId))return null;const{chain:e}=t.eth,n=bt({projectId:t.projectId,metadata:t.metadata,ethChain:e}),i=Pe();if(i)return Bt(i,n),{modal:i.modal,wagmiConfig:$e()};Qe.modal&&F("Reown AppKit was initialized outside this package. Use only this package to initialize it.");const r=Ft(e,t.projectId),o=Qe.createAppKit({adapters:[r],networks:[e],projectId:t.projectId,metadata:t.metadata,features:{email:!1,socials:!1}});return{modal:Mt({modal:o,...n,wagmiConfig:r.wagmiConfig}).modal,wagmiConfig:r.wagmiConfig}}const Gn=()=>{h.useEffect(()=>{const t=()=>{try{const e=Le();e&&e.open()}catch(e){console.warn("AppKit modal not available:",e)}};return window.addEventListener(fe,t),()=>window.removeEventListener(fe,t)},[])};function kt(t){const e=me();return(e==null?void 0:e[t])??null}const zn=[{match:/okx/i,icon:Lt,iconBackground:Ot}];function Vn(t){return zn.find(({match:e})=>e.test(t))}const ee=()=>h.useContext(Ve);async function at(t){const e=t.provider;if(!(e!=null&&e.getWalletProviderName)||!(e!=null&&e.getWalletProviderIcon))return t;const[n,i]=await Promise.all([e.getWalletProviderName(),e.getWalletProviderIcon()]),r=Vn(n||t.name);return{id:t.id,name:n||t.name,icon:(r==null?void 0:r.icon)||i||t.icon,iconBackground:r==null?void 0:r.iconBackground,docs:t.docs,installed:t.installed,provider:t.provider,account:t.account,label:t.label,hardware:t.hardware}}const Yn=new Map([[J.INCOMPATIBLE_WALLET_VERSION,t=>`Update ${t}`],[J.DEVICE_WRONG_APP,()=>"Wrong App on Device"],[J.DEVICE_LOCKED,()=>"Signing Device Locked"]]);function $n({persistent:t,accountStorage:e,onError:n,btcValidation:i}){const r=me(),{confirmed:o,confirmationReceipt:c,visible:s,selectWallet:l,removeWallet:p,displayLoader:m,displayChains:a,displayConnectGuide:d,displayError:f,confirm:E,unconfirm:C,requiredChainIds:T=[]}=ee(),{verifyBTCAddress:g}=St(),I=h.useRef(0),y=h.useRef(T),N=c??(t&&!s?e.get(Y):void 0),W=h.useRef(),B=h.useRef(new Set),D=T.every(w=>{var _;return(_=r[w])==null?void 0:_.connectedWallet}),O=h.useRef(new Set),S=async w=>{O.current.add(w.id),p==null||p(w.id),t&&e.delete(w.id);try{await w.disconnect("chain")}catch(_){he(_)||console.error("Failed to disconnect rejected wallet:",_ instanceof Error?_.message:"Unknown error"),await w.disconnect("local")}finally{O.current.delete(w.id)}};h.useEffect(()=>{if(!s)return;const _=Object.values(r).filter(Boolean).map(A=>A.on("connecting",(v,x)=>{m==null||m(v,x)}));return()=>_.forEach(A=>A())},[s,m,r]),h.useEffect(()=>{const w=Object.values(r).filter(Boolean),_={BTC:v=>async x=>{var j,ge,Ce,Ie;try{if(!x||!x.account)return;if(!i)throw new Error("Bitcoin address validation is unavailable");if(l==null||l("BTC",x),t&&((j=x.account)!=null&&j.address)&&e.set(v.id,x.id),!s)return;i.validateAddress(v.config.network,x.account.address);const P=()=>void(a==null?void 0:a());if(!i.validateAddressWithPK(((ge=x.account)==null?void 0:ge.address)??"",((Ce=x.account)==null?void 0:Ce.publicKeyHex)??"",v.config.network)){f==null||f({title:"Public Key Mismatch",description:"The Bitcoin address and Public Key for this wallet do not match. Please contact your wallet provider for support.",onSubmit:P,onCancel:()=>{S(v),a==null||a()}});return}if(g&&!await g(((Ie=x.account)==null?void 0:Ie.address)??"")){f==null||f({title:"Staking Currently Unavailable",description:"Staking is temporarily disabled due to network downtime. New stakes are paused until the network resumes.",submitButton:"",cancelButton:"Done",onCancel:async()=>{S(v),a==null||a()}});return}P()}catch(P){S(v),f==null||f({title:"Connection Failed",description:P.message,submitButton:"",cancelButton:"Done",onCancel:async()=>{a==null||a()}})}},BBN:v=>x=>{var j;x&&(l==null||l(v.id,x),t&&((j=x.account)!=null&&j.address)&&e.set(v.id,x.id)),a==null||a()},ETH:v=>async x=>{var j;x&&(l==null||l(v.id,await at(x)),t&&((j=x.account)!=null&&j.address)&&e.set(v.id,x.id)),a==null||a()}},A=w.map(v=>{var x;return v.on("connect",(x=_[v.id])==null?void 0:x.call(_,v))});return w.forEach(v=>{const x=O.current.has(v.id)?null:v.connectedWallet;if(v.id==="ETH"&&x){at(x).then(j=>l==null?void 0:l(v.id,j));return}l==null||l(v.id,x)}),()=>A.forEach(v=>v())},[n,l,p,a,f,g,i,e,r,t,s]),h.useLayoutEffect(()=>{const _=Object.values(r).filter(Boolean).map(A=>A.on("disconnect",v=>{v&&(T.includes(A.id)&&(I.current+=1,e.delete(Y)),p==null||p(A.id),a==null||a(),t&&e.delete(A.id))}));return()=>_.forEach(A=>A())},[p,a,r,t,e,T]),h.useEffect(()=>{const _=Object.values(r).filter(Boolean).map(A=>A.on("error",v=>{if(n==null||n(v),v instanceof ae&&f){const x=Yn.get(v.code);if(x){f({title:x(v.wallet??"your wallet"),description:v.message,submitButton:"",cancelButton:"Done",onCancel:()=>{a==null||a()}});return}}a==null||a()}));return()=>_.forEach(A=>A())},[n,a,f,r]);const K=h.useCallback(async()=>{const w=++I.current;if(!N||!c&&!D)return;const _=await wn(N,T,r);if(w===I.current){if(!_){e.delete(Y),C==null||C();return}if(!o&&!s){E==null||E(N),a==null||a();return}t&&o&&e.set(Y,N)}},[e,N,c,o,E,r,a,t,T,D,C,s]);h.useEffect(()=>{K()},[K]),h.useLayoutEffect(()=>{const w=W.current;(!N||w&&w!==N)&&B.current.clear(),W.current=N},[N]),h.useLayoutEffect(()=>{I.current+=1;const w=T.filter(A=>!y.current.includes(A));if(y.current=T,!N)return;const _=_t(N,yt(N),r,A=>{if(!T.includes(A)){B.current.add(A);return}I.current+=1,e.delete(Y),C==null||C()});if(!c&&!D)return _;if(!Nn(N,T,r)||w.some(A=>B.current.has(A))||c&&w.length>0&&!In(N,w,r)){_(),e.delete(Y),C==null||C();return}return c&&w.length>0&&(C==null||C(!0)),_},[e,N,c,r,T,D,C]),h.useEffect(()=>()=>{I.current+=1},[]);const k=h.useCallback(async(w,_)=>{const A=r[w.id];await(A==null?void 0:A.connect(_.id))},[r]),b=h.useCallback(async(w,_)=>{if(_.connectGuide&&d){d(w.id,_.id);return}await k(w,_)},[k,d]);return{connect:k,chooseWallet:b}}function Zn(t,e,n){const i=h.useCallback((r,o)=>u.jsx(u.Fragment,{children:o.map(({id:c,widget:s})=>u.jsx(s,{id:c,connector:t[r],createWallet:Nt,onError:n},c))}),[t,n]);return h.useMemo(()=>e.reduce((r,o)=>({...r,[o.chain]:i(o.chain,o.connectors??[])}),{}),[i,e])}function Ze(){const{confirmed:t,chains:e,requiredChainIds:n,selectedWallets:i,open:r,displayChains:o,displayError:c,displayWallets:s,reset:l}=ee(),p=me(),m=h.useCallback(f=>{f!==void 0&&Object.prototype.hasOwnProperty.call(e,f)?s==null||s(f):o==null||o(),r==null||r()},[e,o,s,r]),a=h.useCallback(async f=>{var E;if(f!==void 0&&Object.prototype.hasOwnProperty.call(p,f)){try{await((E=p[f])==null?void 0:E.disconnect("chain"))}catch(C){throw he(C)&&(c==null||c({title:"Wallets share one session",description:C.message,submitButton:"",cancelButton:"Done",onCancel:()=>{o==null||o()}})),C}return}for(const C of Object.values(p))C&&await C.disconnect("all");l==null||l()},[p,o,c,l]),d=h.useMemo(()=>n.every(f=>!!i[f]),[n,i]);return{selected:d,connected:d&&t,open:m,disconnect:a}}function Xn({className:t,alt:e,logo:n,title:i,description:r,optional:o,children:c,onClick:s}){const l=typeof n=="string"?u.jsx(R.Avatar,{url:n,alt:e}):u.jsx(R.Avatar,{children:n}),p=()=>{if(typeof i=="string"){if(i.includes("Bitcoin"))return"select-bitcoin-wallet-button";if(i.includes("Ethereum"))return"select-ethereum-wallet-button";if(i.includes("Babylon"))return"select-babylon-wallet-button"}return"chain-button"};return u.jsxs(R.Text,{as:"button",className:$.twMerge("flex w-full cursor-pointer flex-col gap-4 rounded-lg bg-neutral-200 p-4 text-accent-primary",t),onClick:s,"data-testid":p(),"data-optional":o,children:[u.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[u.jsx("div",{className:"flex items-center",children:l}),u.jsxs("div",{className:"flex flex-col text-left",children:[i,r&&u.jsx(R.Text,{as:"span",variant:"body2",className:"text-accent-secondary",children:r})]}),u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",className:"ml-auto block shrink-0 text-accent-secondary",children:u.jsx("path",{d:"M8.58984 16.59L13.1698 12L8.58984 7.41L9.99984 6L15.9998 12L9.99984 18L8.58984 16.59Z",fill:"currentColor"})})]}),c&&u.jsx("div",{className:"w-full",children:c})]})}const qn=36,lt=14;function Qn(t){return t.length<=qn?t:`${t.slice(0,lt)}…${t.slice(-lt)}`}const Jn=h.memo(({className:t,logo:e,logoBackground:n,address:i})=>{const{isCopied:r,copyToClipboard:o}=R.useCopy(),c=r(i),s=l=>{l.stopPropagation(),o(i,i)};return u.jsxs("div",{className:$.twMerge("flex items-center gap-2.5 rounded-lg bg-neutral-200 p-2",t),children:[u.jsx(R.WalletIcon,{size:"small",className:"shrink-0",url:e,background:n}),u.jsx(R.Text,{as:"div",variant:"caption",title:i,className:"min-w-0 flex-1 truncate text-left font-mono text-accent-secondary",children:Qn(i)}),u.jsx("span",{role:"button",tabIndex:0,"aria-label":c?"Address copied":"Copy address",onClick:s,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&s(l)},className:"flex shrink-0 cursor-pointer items-center text-accent-secondary hover:text-accent-primary",children:c?u.jsx(R.CheckIcon,{size:16,variant:"success"}):u.jsx(R.CopyIcon,{size:16})})]})}),ei="disabled:!bg-[#CCCCCC] dark:disabled:!bg-secondary-strokeDark",ti="Select ",ni=" Wallet",ii=h.memo(({disabled:t=!1,chains:e,requiredChainIds:n,chainDescriptions:i,selectedWallets:r={},className:o,onConfirm:c,onSelectChain:s})=>u.jsxs("div",{className:$.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight text-accent-primary",o),children:[u.jsx("div",{className:"border-b border-secondary-strokeLight p-6",children:u.jsx(R.Heading,{variant:"h5",className:"text-accent-primary",children:"Connect Wallets"})}),u.jsxs("div",{className:"flex flex-col gap-4 p-6",children:[u.jsxs("div",{className:"flex flex-col gap-2",children:[e.map(l=>{var a;const p=r[l.id],m=n!==void 0&&!n.includes(l.id);return u.jsx(Xn,{title:`${ti}${l.name}${ni}`,description:i==null?void 0:i[l.id],optional:m,logo:l.icon,alt:l.name,onClick:()=>void(s==null?void 0:s(l)),children:p&&u.jsx(Jn,{logo:p.icon,logoBackground:p.iconBackground,address:((a=p.account)==null?void 0:a.address)??""})},l.id)}),u.jsx(R.Button,{color:"secondary",disabled:t,fluid:!0,onClick:c,className:$.twMerge("text-sm disabled:!opacity-100",ei),"data-testid":"chains-connect-button",children:"Connect"})]}),u.jsxs(R.Text,{variant:"body2",className:"text-center text-accent-secondary",children:["By clicking Connect you agree with the"," ",u.jsx("a",{href:"https://babylonlabs.io/terms-of-use",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Terms of Use"})," ","and"," ",u.jsx("a",{href:"https://babylonlabs.io/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Privacy Policy"}),"."]})]})]}));function ri(){typeof window<"u"&&window.dispatchEvent(new Event(fe))}function oi({isChainHidden:t,...e}){const{chains:n,requiredChainIds:i,selectedWallets:r,displayWallets:o}=ee(),{selected:c,disconnect:s}=Ze(),l=me(),p=h.useMemo(()=>Object.values(n).filter(a=>r[a.id]||!(t!=null&&t(a))),[n,t,r]),m=h.useCallback(async a=>{if(a.id==="ETH"||a.id==="BTC"){const d=l[a.id],f=a.id==="ETH"?Ye:Dt,E=d==null?void 0:d.wallets.find(C=>C.id===f);if(E&&(d==null?void 0:d.wallets.length)===1){const C=!!d.connectedWallet;try{C?a.id==="ETH"&&!Ht()?ri():await s(a.id):await d.connect(E.id)}catch(T){he(T)||console.error(`Failed to ${C?"disconnect":"connect"} AppKit ${a.id}:`,T instanceof Error?T.message:"Unknown error")}return}}o==null||o(a.id)},[o,l,s]);return u.jsx(ii,{disabled:!c,chains:p,requiredChainIds:i,selectedWallets:r,onSelectChain:m,...e})}function si({name:t,logo:e,logoBackground:n,guide:i,onConnect:r}){return u.jsxs("div",{children:[u.jsxs(R.DialogBody,{className:"flex flex-col gap-6 py-10",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx(R.WalletIcon,{className:"shrink-0",alt:t,url:e,background:n}),u.jsx(R.Heading,{variant:"h5",className:"text-accent-primary",children:"Before you connect"})]}),u.jsx("ol",{className:"flex list-decimal flex-col gap-2 pl-5 text-accent-primary",children:i.steps.map(o=>u.jsx(R.Text,{as:"li",variant:"body2",children:o},o))}),i.installSteps&&u.jsxs("div",{className:"flex flex-col gap-2 rounded-lg bg-neutral-100 p-4",children:[u.jsx(R.Text,{variant:"body2",className:"text-accent-primary",children:"Don't have the app yet?"}),u.jsx("ol",{className:"flex list-decimal flex-col gap-2 pl-5 text-accent-secondary",children:i.installSteps.map(o=>u.jsx(R.Text,{as:"li",variant:"body2",children:o},o))})]})]}),u.jsx(R.DialogFooter,{children:u.jsx(R.Button,{fluid:!0,onClick:r,"data-testid":"connect-guide-connect-button",children:"Connect"})})]})}function ci({onConnect:t}){var o;const{chains:e,screen:n}=ee(),i=e[((o=n.params)==null?void 0:o.chain)??""],r=i==null?void 0:i.wallets.find(({id:c})=>{var s;return c===((s=n.params)==null?void 0:s.wallet)});return!i||!(r!=null&&r.connectGuide)?null:u.jsx(si,{name:r.name,logo:r.icon,logoBackground:r.iconBackground,guide:r.connectGuide,onConnect:()=>t==null?void 0:t(i,r)})}const ai=u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"52",height:"52",viewBox:"0 0 52 52",fill:"none",children:u.jsx("path",{d:"M2.16675 46.5837H49.8334L26.0001 5.41699L2.16675 46.5837ZM28.1667 40.0837H23.8334V35.7503H28.1667V40.0837ZM28.1667 31.417H23.8334V22.7503H28.1667V31.417Z",fill:"#387085"})});function li({className:t,icon:e=ai,title:n,description:i,cancelButton:r="Cancel",submitButton:o=u.jsxs(u.Fragment,{children:["Continue ",u.jsx("span",{className:"hidden md:inline",children:"Anyway"})]}),onCancel:c,onSubmit:s}){return u.jsxs("div",{className:t,children:[u.jsxs(R.DialogBody,{className:"py-16 text-center",children:[u.jsx("div",{className:"mb-6 inline-flex size-20 items-center justify-center bg-primary-contrast text-primary-light",children:e}),u.jsx(R.Heading,{variant:"h4",className:"mb-4 text-accent-primary",children:n}),u.jsx(R.Text,{as:"div",className:"text-accent-secondary",children:i})]}),u.jsxs(R.DialogFooter,{className:"flex gap-4",children:[r&&u.jsx(R.Button,{variant:"outlined",fluid:!0,onClick:c,children:r}),o&&u.jsx(R.Button,{fluid:!0,onClick:s,"data-testid":"error-continue-button",children:o})]})]})}function di({className:t}){const{screen:e}=ee(),{icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:l}=e.params??{};return u.jsx(li,{className:t,icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:l})}function ui({className:t,title:e,description:n}){return u.jsxs("div",{className:$.twMerge("flex flex-col items-center justify-center gap-6",t),children:[u.jsx("div",{className:"flex items-center justify-center bg-primary-contrast p-6",children:u.jsx(R.Loader,{className:"text-primary-light"})}),(e||n)&&u.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[e&&u.jsx(R.Heading,{variant:"h4",className:"capitalize text-accent-primary",children:e}),n&&u.jsx(R.Text,{as:"div",className:"text-accent-secondary",children:n})]})]})}const fi="text-[#15B768] dark:text-[#00E676]",hi="bg-[#15B768] dark:bg-[#00E676]",Ei="text-[#FFB300]",pi="bg-[#FFB300]";function mi({className:t,disabled:e=!1,name:n,logo:i,logoBackground:r,fallbackLink:o,installed:c=!0,hardware:s=!1,label:l,onClick:p}){const a=c||s?{as:"button",disabled:e,onClick:p}:{as:"a",href:o,target:"_blank",rel:"noopener noreferrer"},d=()=>{const f=n.toLowerCase();return f.includes("okx")?"wallet-option-okx":f.includes("keplr")?"wallet-option-keplr":f.includes("leap")?"wallet-option-leap":`wallet-option-${f.replace(/\s+/g,"-")}`};return u.jsxs(R.Text,{variant:"body2",className:$.twMerge("flex h-14 w-full items-center gap-2.5 rounded-lg p-2 text-accent-primary",c?"bg-neutral-200":"bg-neutral-100",e?"cursor-default":"cursor-pointer",t),...a,"data-testid":d(),children:[u.jsx(R.WalletIcon,{className:"shrink-0",alt:n,url:i,background:r}),u.jsx("span",{className:$.twMerge("min-w-0 flex-1 truncate text-left",!c&&"text-accent-secondary"),children:n}),u.jsxs(R.Chip,{className:$.twMerge("flex shrink-0 items-center gap-1.5 rounded-full",c?"bg-neutral-100":"bg-neutral-200"),children:[(s||c)&&u.jsx("span",{className:$.twMerge("size-2 rounded-full",s?pi:hi)}),u.jsx("span",{className:s?Ei:c?fi:"text-accent-secondary",children:s?l:c?"Installed":"Uninstalled"})]})]})}const gi={[G.MAINNET]:"bc1p",[G.TESTNET]:"tb1p",[G.SIGNET]:"tb1p"},Ci="https://tbv-faucet.testnet.babylonlabs.io/",dt=t=>t.installed&&!t.hardware?0:t.hardware?1:2,Ii=h.memo(({chain:t,className:e,append:n,onSelectWallet:i})=>{const r=h.useMemo(()=>t.wallets.filter(s=>s.id==="injectable"?s.installed:!0).sort((s,l)=>dt(s)-dt(l)),[t]),o=h.useMemo(()=>{var p;if(t.id!=="BTC")return null;const s=(p=t.config)==null?void 0:p.network,l=s?gi[s]:void 0;return l?{prefix:l,showFaucet:s!==G.MAINNET}:null},[t]),c=h.useCallback(async s=>{i==null||i(t,s)},[t,i]);return u.jsxs("div",{className:$.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight",e),children:[u.jsxs("div",{className:"flex flex-col gap-2 border-b border-secondary-strokeLight p-6",children:[u.jsx(R.Heading,{variant:"h5",className:"text-accent-primary",children:`Select ${t.name} Wallet`}),o&&u.jsxs(R.Text,{variant:"body2",className:"text-accent-secondary",children:[`To continue, connect a ${t.name} wallet with a `,u.jsx("span",{className:"text-accent-primary",children:`${o.prefix} (Taproot)`})," address.",o.showFaucet&&u.jsxs("span",{className:"block",children:[" Don't have testnet BTC yet? Get it from ",u.jsx("a",{href:Ci,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline underline-offset-2 transition-opacity hover:opacity-80",children:"Faucet"}),"."]})]})]}),u.jsxs("div",{className:"flex flex-col gap-2 p-6",children:[r.map(s=>u.jsx(mi,{installed:s.installed,hardware:s.hardware,label:s.label,name:s.name,logo:s.icon,logoBackground:s.iconBackground,fallbackLink:s.docs,onClick:()=>c(s)},s.id)),n]})]})});function Ni({widgets:t={},...e}){var s;const{chains:n,screen:i}=ee(),r=((s=i.params)==null?void 0:s.chain)??"",o=n==null?void 0:n[r],c=t==null?void 0:t[r];return u.jsx(Ii,{append:c,chain:o,...e})}const ut={CHAINS:({onConfirm:t,chainDescriptions:e,isChainHidden:n})=>u.jsx(oi,{onConfirm:t,chainDescriptions:e,isChainHidden:n}),WALLETS:({widgets:t,onSelectWallet:e})=>u.jsx(Ni,{widgets:t,onSelectWallet:e}),CONNECT_GUIDE:({onConnectWallet:t})=>u.jsx(ci,{onConnect:t}),LOADER:({current:t})=>{var e,n;return u.jsx(ui,{title:(e=t==null?void 0:t.params)==null?void 0:e.message,description:(n=t==null?void 0:t.params)==null?void 0:n.description})},ERROR:()=>u.jsx(di,{}),EMPTY:()=>u.jsx("div",{})};function wi(t){const e=ut[t.current.type]??ut.EMPTY;return u.jsx(e,{...t})}const oe="Wallet changed while confirming",Ti="Wallet did not report its network",Ai="Wallet network does not match the configured network",_i="Connected wallet has no provider";function yi(t,e){for(const n of e){const i=t.find(({chain:r})=>r===n);if(i)return i}return t[0]}function Fe(t){return Object.entries(t).flatMap(([e,n])=>{const i=n==null?void 0:n.connectedWallet;return i!=null&&i.account?[{chain:e,wallet:i,account:{...i.account}}]:[]})}function ft(t){return t.map(({chain:e,wallet:n,account:i})=>{const r={...i},o={id:n.id,name:n.name,icon:n.icon,iconBackground:n.iconBackground,docs:n.docs,installed:n.installed,provider:n.provider,account:r,label:n.label,hardware:n.hardware};return{chain:e,wallet:o,account:r}})}function vi(t,e,n){return t.every(({chain:i,wallet:r,provider:o,receipt:c})=>{const s=e.find(l=>l.chain===i);return s?s.wallet===r&&s.provider===o&&s.receipt===c:!n.includes(i)})}async function ht(t,e,n){const i=t(),r=Fe(i).map(d=>({connection:d,provider:d.wallet.provider,receipt:de([d],i)})),c=(await Promise.all(r.map(async d=>{var C,T;const{chain:f}=d.connection,{provider:E}=d;try{if(!E)throw new Error(`${_i}: ${f}`);if(((C=E.isIdentityCurrent)==null?void 0:C.call(E))===!1)throw new Error(oe);let g;if(f==="ETH"||f==="BTC"){if(g=f==="ETH"?await E.getChainId():await E.getNetwork(),g==null||!String(g))throw new Error(Ti);if(de([d.connection],i,{[f]:g})!==d.receipt)throw new Error(Ai)}const[I,y]=await Promise.all([E.getAddress(),E.getPublicKeyHex()]);if(!I||!y||!ie(I,d.connection.account.address)||!ie(y,d.connection.account.publicKeyHex))throw new Error(oe);if(((T=E.isIdentityCurrent)==null?void 0:T.call(E))===!1)throw new Error(oe);return{...d,connection:{...d.connection,account:{address:I,publicKeyHex:y}}}}catch(g){if(e.includes(f))throw g;return n==null||n(g instanceof Error?g:new Error("Optional wallet verification failed")),null}}))).filter(d=>d!==null),s=t(),l=Fe(s),p=c.flatMap(d=>{const{connection:f,receipt:E}=d,C=l.find(({chain:g})=>g===f.chain);if(!!(C&&C.wallet===f.wallet&&C.wallet.provider===d.provider&&de([C],s)===E))return[d];if(e.includes(f.chain))throw new Error(oe);return n==null||n(new Error(oe)),[]}),m=p.map(({connection:d})=>d),a=p.map(({connection:d,provider:f,receipt:E})=>({chain:d.chain,wallet:d.wallet,provider:f,receipt:E}));return{receipt:de(m,s),connections:m,identities:Object.freeze(a)}}function Ri({persistent:t,storage:e,config:n,onError:i,btcValidation:r,actions:o,closeButtonClassName:c,actionsClassName:s,chainDescriptions:l,isChainHidden:p}){const{visible:m,screen:a,confirmed:d,requiredChainIds:f,close:E,confirm:C,unconfirm:T,displayChains:g,displayWallets:I,displayError:y}=ee(),{acceptTermsOfService:N,onConfirm:W}=St(),B=me(),D=Zn(B,n,i),{connect:O,chooseWallet:S}=$n({persistent:t,accountStorage:e,onError:i,btcValidation:r}),K=h.useRef(B),k=h.useRef(0),b=h.useRef(null),w=h.useRef(null),_=h.useRef(!1),A=h.useRef(m),v=h.useRef(d),x=h.useRef({persistent:t,requiredChainIds:[...f],storage:e}),j=h.useCallback(()=>{const P=w.current;w.current=null,k.current+=1,b.current=null,P==null||P()},[]);h.useLayoutEffect(()=>{K.current=B,(A.current&&!m||!v.current&&d)&&j(),A.current=m,v.current=d},[d,B,j,m]),h.useLayoutEffect(()=>(_.current=!0,()=>{_.current=!1,j()}),[j]),h.useLayoutEffect(()=>{const P=x.current,U=P.requiredChainIds.length!==f.length||P.requiredChainIds.some((te,Ne)=>te!==f[Ne]);(P.persistent!==t||P.storage!==e||U)&&j(),x.current={persistent:t,requiredChainIds:[...f],storage:e}},[j,t,f,e]);const ge=h.useCallback(()=>{j(),E==null||E()},[E,j]),Ce=h.useCallback(async()=>{if(b.current!==null||!_.current||!A.current)return;const P=k.current+1;k.current=P,b.current=P;const U=()=>b.current===P&&k.current===P&&_.current&&A.current;let te=()=>{},Ne=!1;try{if(!d){const re=K.current,le=de(Fe(re),re),zt=_t(le,yt(le),re,()=>{j(),e.delete(Y),T==null||T()});let Xe=!0;if(te=()=>{Xe&&(Xe=!1,zt())},!U()){te();return}w.current=te;const we=await ht(()=>K.current,f,i);if(!U())return;const{connections:Te}=we,We=f.filter(je=>!Te.some(({chain:Vt})=>Vt===je));if(We.length>0)throw new Error(`No connected account for required chain${We.length>1?"s":""}: ${We.join(", ")}`);const Ae=yi(Te,f),qe=async()=>{if(!U())return!1;const je=await ht(()=>K.current,f,i);if(!U())return!1;if(!vi(we.identities,je.identities,f))throw new Error(oe);return!0};if(Ae&&(await(N==null?void 0:N({address:Ae.account.address,public_key:Ae.account.publicKeyHex,chain:Ae.chain,connections:ft(Te)})),!await qe())||(await(W==null?void 0:W(ft(Te))),!await qe())||(t&&e.set(Y,we.receipt),!U())||(C==null||C(we.receipt),!U()))return;Ne=!!C}if(!U())return;E==null||E()}catch(re){if(!U())return;const le=re instanceof Error?re:new Error("Wallet confirmation failed");if(i==null||i(le),!U())return;y==null||y({title:"Connection Failed",description:le.message,submitButton:"",cancelButton:"Done",onCancel:g})}finally{Ne||(te(),w.current===te&&(w.current=null),k.current===P&&b.current===P&&(b.current=null))}},[N,E,C,d,g,y,j,W,i,t,f,e,T]),Ie=a.type==="WALLETS"?g:a.type==="CONNECT_GUIDE"?()=>{var P;return I==null?void 0:I((P=a.params)==null?void 0:P.chain)}:void 0;return u.jsx(R.FullScreenDialog,{open:m,onClose:ge,onBack:Ie,className:"items-center justify-center p-6",actions:o,closeButtonClassName:c,actionsClassName:s,children:u.jsx("div",{className:"mx-auto w-full max-w-[612px]",children:u.jsx(wi,{current:a,widgets:D,onConfirm:Ce,onSelectWallet:S,onConnectWallet:O,chainDescriptions:l,isChainHidden:p})})})}function Ut(t,e){const{enabled:n,delay:i=500}=e,r=h.useRef(null);h.useEffect(()=>{if(!n||typeof window>"u"||typeof document>"u")return;const o=()=>{document.visibilityState==="visible"&&(r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{Promise.resolve(t()).catch(c=>{console.error("Error in visibility check callback:",c instanceof Error?c.message:"Unknown error")})},i))};return document.addEventListener("visibilitychange",o),()=>{document.removeEventListener("visibilitychange",o),r.current&&(clearTimeout(r.current),r.current=null)}},[n,t,i])}const Gt=h.createContext({loading:!0,connected:!1,address:void 0,disconnect:()=>{},open:()=>{}}),xi=({children:t,callbacks:e})=>{const[n,i]=h.useState(!0),[r,o]=h.useState(),[c,s]=h.useState(null),{open:l,disconnect:p}=Ze(),m=kt("ETH"),a=h.useCallback(async()=>{try{await(m==null?void 0:m.disconnect("local"))}catch(g){console.error("Failed to disconnect ETH connector:",g instanceof Error?g.message:"Unknown error")}},[m]),d=h.useCallback(async g=>{var I,y;try{o(g),i(!1),await((I=e==null?void 0:e.onConnect)==null?void 0:I.call(e,g))}catch(N){i(!1),(y=e==null?void 0:e.onError)==null||y.call(e,N instanceof Error?N:new Error("ETH connection failed"),{address:g})}},[e]);h.useEffect(()=>{if(i(!1),!m)return;(async()=>{var D;try{if((D=m.connectedWallet)!=null&&D.provider&&!r){const O=m.connectedWallet.provider,S=await O.getAddress();S&&(s(O),d(S));return}if(!r&&m.wallets.length>0){const O=m.wallets[0];if(O.provider)try{await O.provider.getAddress()&&await m.connect(O)}catch{}}}catch{}})();const I=m.on("connect",async D=>{if(D.provider)try{const O=await D.provider.getAddress();O&&(s(D.provider),d(O))}catch(O){console.error("Error getting ETH address:",O instanceof Error?O.message:"Unknown error")}}),y=m.wallets[0],N=y==null?void 0:y.provider;let W=!1;const B=D=>{!(D!=null&&D[0])||r||W||(W=!0,m.connect(y).then(O=>{O||(W=!1)}).catch(O=>{W=!1,console.error("ETH late reconnect failed:",O instanceof Error?O.message:"Unknown error")}))};return N&&typeof N.on=="function"&&N.on("accountsChanged",B),()=>{I(),N&&typeof N.off=="function"&&N.off("accountsChanged",B)}},[m,d,r]),h.useEffect(()=>{if(m)return m.on("disconnect",async()=>{var g;o(void 0),s(null);try{await((g=e==null?void 0:e.onDisconnect)==null?void 0:g.call(e))}catch(I){console.error("Error in onDisconnect callback:",I instanceof Error?I.message:"Unknown error")}})},[m,e]);const f=h.useRef(void 0),E=h.useRef(!1);h.useEffect(()=>{f.current=r},[r]),h.useEffect(()=>{if(!c)return;const g=async I=>{var W,B;if(E.current)return;const y=I[0],N=f.current;if(y&&y.toLowerCase()!==(N==null?void 0:N.toLowerCase())){E.current=!0,f.current=y,o(y);try{await((W=e==null?void 0:e.onAddressChange)==null?void 0:W.call(e,y))}catch(D){(B=e==null?void 0:e.onError)==null||B.call(e,D instanceof Error?D:new Error("ETH address change failed"),{address:y})}finally{E.current=!1}}else!y&&N&&a()};return typeof c.on=="function"&&c.on("accountsChanged",g),()=>{typeof c.off=="function"&&c.off("accountsChanged",g)}},[c,e,a]);const C=h.useCallback(async()=>{var g;if(c)try{const I=await c.getAddress();I?I.toLowerCase()!==(r==null?void 0:r.toLowerCase())&&(f.current=I,o(I),await((g=e==null?void 0:e.onAddressChange)==null?void 0:g.call(e,I))):a()}catch(I){console.error("ETH wallet connection check failed:",I instanceof Error?I.message:"Unknown error"),a()}},[c,r,e,a]);Ut(C,{enabled:!!(c&&r)});const T=h.useMemo(()=>!!r,[r]);return u.jsx(Gt.Provider,{value:{loading:n,connected:T,address:r,disconnect:()=>p("ETH"),open:l},children:t})},Si=()=>h.useContext(Gt);exports.ACCOUNT_CHANGE_EVENTS=ke;exports.APPKIT_BTC_CONNECTOR_ID=Dt;exports.APPKIT_ETH_CONNECTOR_ID=Ye;exports.APPKIT_OPEN_EVENT=fe;exports.COSMOS_KEYSTORE_CHANGE_EVENTS=rn;exports.ChainProvider=An;exports.DISCONNECT_EVENT=Ge;exports.ERROR_CODES=J;exports.ETHWalletProvider=xi;exports.ETH_EMPTY_ACCOUNT_GRACE_MS=Kt;exports.LifeCycleHooksProvider=_n;exports.MONOCHROME_MARK_BACKGROUND=Ot;exports.NETWORK_CHANGE_EVENT=Ue;exports.Network=G;exports.ONEKEY_BRAND_GREEN=vn;exports.ONE_HOUR=sn;exports.StateContext=Ve;exports.StateProvider=vt;exports.WALLET_MODAL_OPEN_EVENT=Se;exports.WalletDialog=Ri;exports.WalletError=ae;exports.assertAppKitCapabilities=Bt;exports.createAccountStorage=yn;exports.createAppKitCapabilities=bt;exports.createETHWagmiAdapter=Ft;exports.createExternalWallet=Nt;exports.failInitialization=F;exports.getAppKitState=Pe;exports.getSharedWagmiConfig=$e;exports.hasSharedWagmiConfig=Re;exports.initializeAppKitModal=Un;exports.isAccountChangeEvent=en;exports.isSharedSessionRefusal=he;exports.isUserRejectionMessage=an;exports.metadata=kn;exports.okxLogo=Lt;exports.process$1=It;exports.registerManualAppKitConfig=Wt;exports.removeProviderListener=on;exports.setAppKitState=Mt;exports.setSharedWagmiConfig=bn;exports.trackProviderIdentityChanges=nn;exports.useAppKitOpenListener=Gn;exports.useChainConnector=kt;exports.useETHWallet=Si;exports.useInscriptionProvider=mn;exports.useVisibilityCheck=Ut;exports.useWalletConnect=Ze;exports.useWidgetState=ee;exports.validateAppKitInitialization=jt;
2
+ //# sourceMappingURL=ETHWalletProvider-CphDrNAT.cjs.map