@babylonlabs-io/wallet-connector 2.0.15 → 2.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ETHWalletProvider-wp9s8vtc.cjs → ETHWalletProvider-B1utrSWQ.cjs} +2 -2
- package/dist/{ETHWalletProvider-wp9s8vtc.cjs.map → ETHWalletProvider-B1utrSWQ.cjs.map} +1 -1
- package/dist/{ETHWalletProvider-Dq5EwVtB.js → ETHWalletProvider-BBXEXYvk.js} +56 -56
- package/dist/{ETHWalletProvider-Dq5EwVtB.js.map → ETHWalletProvider-BBXEXYvk.js.map} +1 -1
- package/dist/eth.cjs +1 -1
- package/dist/eth.es.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.es.js +2 -2
- package/package.json +3 -3
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Ft=Object.defineProperty;var Kt=(t,e,n)=>e in t?Ft(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>Kt(t,typeof e!="symbol"?e+"":e,n);const Oe=require("viem"),W=require("wagmi/actions"),ct=require("wagmi/connectors"),kt=require("@reown/appkit-adapter-wagmi"),Ve=require("@reown/appkit/react"),Ye=require("wagmi"),h=require("react"),E=require("react/jsx-runtime"),L=require("@babylonlabs-io/core-ui"),Y=require("tailwind-merge");function Ut(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var at={exports:{}},D=at.exports={},G,z;function Le(){throw new Error("setTimeout has not been defined")}function be(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?G=setTimeout:G=Le}catch{G=Le}try{typeof clearTimeout=="function"?z=clearTimeout:z=be}catch{z=be}})();function dt(t){if(G===setTimeout)return setTimeout(t,0);if((G===Le||!G)&&setTimeout)return G=setTimeout,setTimeout(t,0);try{return G(t,0)}catch{try{return G.call(null,t,0)}catch{return G.call(this,t,0)}}}function Gt(t){if(z===clearTimeout)return clearTimeout(t);if((z===be||!z)&&clearTimeout)return z=clearTimeout,clearTimeout(t);try{return z(t)}catch{try{return z.call(null,t)}catch{return z.call(this,t)}}}var $=[],ne=!1,q,Ne=-1;function zt(){!ne||!q||(ne=!1,q.length?$=q.concat($):Ne=-1,$.length&<())}function lt(){if(!ne){var t=dt(zt);ne=!0;for(var e=$.length;e;){for(q=$,$=[];++Ne<e;)q&&q[Ne].run();Ne=-1,e=$.length}q=null,ne=!1,Gt(t)}}D.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];$.push(new ut(t,e)),$.length===1&&!ne&&dt(lt)};function ut(t,e){this.fun=t,this.array=e}ut.prototype.run=function(){this.fun.apply(null,this.array)};D.title="browser";D.browser=!0;D.env={};D.argv=[];D.version="";D.versions={};function Z(){}D.on=Z;D.addListener=Z;D.once=Z;D.off=Z;D.removeListener=Z;D.removeAllListeners=Z;D.emit=Z;D.prependListener=Z;D.prependOnceListener=Z;D.listeners=function(t){return[]};D.binding=function(t){throw new Error("process.binding is not supported")};D.cwd=function(){return"/"};D.chdir=function(t){throw new Error("process.chdir is not supported")};D.umask=function(){return 0};var Vt=at.exports;const ft=Ut(Vt),ht=["accountChanged","accountsChanged"];function Yt(t){return ht.includes(t)}const Me="networkChanged",Be="disconnect";function $t(t,e){if(typeof t.on!="function")return!1;try{t.on("accountsChanged",e)}catch{return!1}return[Me,Be].forEach(n=>{var i;try{(i=t.on)==null||i.call(t,n,e)}catch{}}),!0}const De="babylon-wallet#modal-open",Xt=["keplr_keystorechange","leap_keystorechange","okx_keystorechange"];function Zt(t,e,n){typeof t.removeListener=="function"?t.removeListener(e,n):typeof t.off=="function"&&t.off(e,n)}const qt=3600*1e3;class ye{constructor({id:e,origin:n,name:i,icon:r,iconBackground:o,docs:c,networks:s,provider:d,label:g,hardware:u}){b(this,"id");b(this,"origin");b(this,"name");b(this,"icon");b(this,"iconBackground");b(this,"docs");b(this,"networks");b(this,"provider",null);b(this,"hardware");b(this,"_label");b(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=d,this._label=g,this.hardware=u??!1}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 ye({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 Qt=()=>({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 re={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",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",INSCRIPTIONS_UNSUPPORTED_NETWORK:"INSCRIPTIONS_UNSUPPORTED_NETWORK",INSCRIPTION_FETCH_ERROR:"INSCRIPTION_FETCH_ERROR"};class oe extends Error{constructor({code:n,message:i,wallet:r,version:o,chainId:c},s){super(i,s);b(this,"code");b(this,"wallet");b(this,"version");b(this,"chainId");this.code=n,this.wallet=r,this.version=o,this.chainId=c}}function Jt(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 le(t){return t instanceof oe&&t.code===re.SHARED_SESSION_DISCONNECT_REFUSED}class He{constructor(e,n,i,r,o){b(this,"_connectedWallet",null);b(this,"_connectionGeneration",0);b(this,"_ee",Qt());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 oe({code:re.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"&&le(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 He(this.id,this.name,this.icon,this.wallets,this.config)}on(e,n){return this._ee.on(e,n)}}var U=(t=>(t.MAINNET="mainnet",t.TESTNET="testnet",t.SIGNET="signet",t))(U||{});const en=t=>e=>e[t],tn=async({metadata:t,context:e,config:n})=>{const{id:i,wallet:r,name:o,icon:c,iconBackground:s,docs:d="",networks:g=[],createProvider:u,label:a,hardware:l}=t,f={id:i,name:"",icon:"",iconBackground:s,origin:null,provider:null,docs:d,networks:g,label:a,hardware:l};if(r){const p=typeof r=="string"?en(r):r;f.origin=await p(e,n)??null,f.provider=f.origin?u(f.origin,n):null}else f.origin=null,f.provider=u(null,n);return typeof o=="string"?f.name=o??"":f.name=f.origin?await o(f.origin,n):"",typeof c=="string"?f.icon=c??"":f.icon=f.origin?await c(f.origin,n):"",new ye(f)},Et=({id:t,name:e,icon:n,provider:i})=>new ye({id:t,origin:null,name:e,icon:n,docs:"",networks:[U.MAINNET,U.SIGNET],provider:i}),pt=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 l of e.wallets)o!=null&&o.includes(l.id)||c.push(await tn({metadata:l,context:n,config:i}));const d=c.find(l=>l.id==="injectable"&&l.installed),g=c.filter(l=>l.name.toLowerCase()!==(d==null?void 0:d.name.toLowerCase())||l.id==="injectable"),u=new He(e.chain,e.name,e.icon,g,i);return e.chain!=="ETH"&&s&&c.some(l=>l.id===s&&l.installed)&&u.connect(s).catch(l=>{console.error("Auto-reconnect failed:",l instanceof Error?l.message:"Unknown error")}),u};function nn({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(d=>d.id===s&&d.installed)&&o.push({connector:c,walletId:s})}return o}const $e="unisat#initialized",rn=3e3;function on({connectors:t,setConnectors:e,config:n,context:i,storage:r,disabledWallets:o,persistent:c,metadata:s}){const d=h.useRef(t);d.current=t;const g=Object.values(t).some(Boolean);h.useEffect(()=>{if(!g)return;let u=!1,a=!1;const l=new Set,f=new Set,p=async x=>{if(!(u||a)){u=!0;try{await C(x)}finally{u=!1}}},C=async x=>{const M=Object.values(d.current).filter(Boolean).filter(R=>!!s[R.id]&&!R.connectedWallet&&R.wallets.some(F=>F.id!=="injectable"&&!F.installed));let P=[];if(M.length>0){const R=await Promise.all(M.map(_=>{var T;return pt({persistent:!1,metadata:s[_.id],context:i,config:(T=n.find(I=>I.chain===_.id))==null?void 0:T.config,accountStorage:r,disabledWallets:o}).catch(()=>null)}));if(a)return;const F=R.filter(_=>{if(!_)return!1;const T=d.current[_.id];if(!T||T.connectedWallet)return!1;const I=new Set(T.wallets.filter(A=>A.installed).map(A=>A.id));return _.wallets.some(A=>A.installed&&!I.has(A.id))});for(const _ of F)f.add(_.id);const v=d.current;P=F.filter(_=>{var T;return!((T=v[_.id])!=null&&T.connectedWallet)}),P.length>0&&e(_=>{var I;const T={};for(const A of P)(I=_[A.id])!=null&&I.connectedWallet||(T[A.id]=A);return Object.keys(T).length>0?{..._,...T}:_})}if(!x||!c||f.size===0)return;const O={};for(const R of Object.values(d.current))R&&(O[R.id]=R);for(const R of P)O[R.id]=R;const S=nn({connectors:Object.values(O),storage:r,allowReconnect:x,persistent:c,eligibleChainIds:f});for(const{connector:R,walletId:F}of S)l.has(R.id)||(l.add(R.id),R.connect(F).then(v=>{l.delete(R.id),v&&f.delete(R.id)}).catch(()=>l.delete(R.id)))},y=()=>void p(!0),m=()=>void p(!1),N=setTimeout(y,rn),w=typeof window<"u";return w&&(window.addEventListener($e,y,{once:!0}),window.addEventListener(De,m)),()=>{a=!0,clearTimeout(N),w&&(window.removeEventListener($e,y),window.removeEventListener(De,m))}},[g,n,i,r,o,e,c,s])}function sn(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 gt=h.createContext({lockInscriptions:!0});function cn({children:t,context:e}){const[n,i]=sn("bwc-inscription-modal-lock",e.localStorage,!0),r=h.useMemo(()=>({lockInscriptions:n,toggleLockInscriptions:i}),[n,i]);return E.jsx(gt.Provider,{value:r,children:t})}const an=()=>h.useContext(gt),V="__babylon-wallet-confirmation-v1__",mt=2,dn={BTC:["accountsChanged",Me,Be],BBN:["accountChanged"],ETH:["accountsChanged","chainChanged"]};function ue(t,e){return t[e]}function ve(t,e,n){var o;const i=(o=ue(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 Q(t,e){return t.toLowerCase()===e.toLowerCase()}function ln(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 fe(t){if(t)try{const e=JSON.parse(t);return(e==null?void 0:e.version)!==mt||!Array.isArray(e.entries)||!e.entries.every(ln)?void 0:e}catch{return}}function ce(t,e,n){const i=t.filter(r=>r.account&&ue(e,r.chain)).map(r=>({chain:r.chain,walletId:r.wallet.id,address:r.account.address,publicKeyHex:r.account.publicKeyHex,network:ve(e,r.chain,n)})).sort((r,o)=>r.chain.localeCompare(o.chain));return JSON.stringify({version:mt,entries:i})}function un(t,e,n){var r;const i=(r=fe(t))==null?void 0:r.entries;return i?e.every(o=>{var u;const c=o,s=(u=ue(n,c))==null?void 0:u.connectedWallet,d=s==null?void 0:s.account,g=i.find(a=>a.chain===c);return!!(s&&d&&g&&g.walletId===s.id&&Q(g.address,d.address)&&Q(g.publicKeyHex,d.publicKeyHex)&&g.network===ve(n,c))}):!1}function fn(t,e,n){var r;const i=(r=fe(t))==null?void 0:r.entries;return i?e.every(o=>{var g;const c=o,s=(g=ue(n,c))==null?void 0:g.connectedWallet,d=i.find(u=>u.chain===c);return!!(s&&d&&d.walletId===s.id&&d.network===ve(n,c))}):!1}async function hn(t,e,n){var o;const i=(o=fe(t))==null?void 0:o.entries;return i?(await Promise.all(e.map(async c=>{var l,f;const s=c,d=ue(n,s),g=d==null?void 0:d.connectedWallet,u=g==null?void 0:g.provider,a=i.find(p=>p.chain===s);if(!g||!u||!a||a.walletId!==g.id)return!1;try{if(((l=u.isIdentityCurrent)==null?void 0:l.call(u))===!1)return!1;const[p,C,y]=await Promise.all([u.getAddress(),u.getPublicKeyHex(),s==="ETH"?u.getChainId():s==="BTC"?u.getNetwork():ve(n,s)]);return((f=u.isIdentityCurrent)==null?void 0:f.call(u))===!1?!1:Q(a.address,p)&&Q(a.publicKeyHex,C)&&a.network===String(y)}catch{return!1}}))).every(Boolean):!1}function Ct(t,e,n,i){var c;const r=(c=fe(t))==null?void 0:c.entries;if(!r)return()=>{};const o=[];return e.forEach(s=>{var u,a,l;const d=s,g=(a=(u=n[d])==null?void 0:u.connectedWallet)==null?void 0:a.provider;g!=null&&g.on&&((l=dn[d])==null||l.forEach(f=>{var C;const p=(...y)=>{const m=y[0],N=r.find(w=>w.chain===d);d==="ETH"&&f==="accountsChanged"&&Array.isArray(m)&&m.length===1&&typeof m[0]=="string"&&N&&Q(N.address,m[0])||i(d)};try{(C=g.on)==null||C.call(g,f,p),o.push({event:f,handler:p,provider:g})}catch{}}))}),()=>{o.forEach(({event:s,handler:d,provider:g})=>{var u;try{(u=g.off)==null||u.call(g,s,d)}catch{}})}}function It(t){var e;return((e=fe(t))==null?void 0:e.entries.map(n=>n.chain))??[]}const Pe={confirmed:!1,visible:!1,screen:{type:"CHAINS"},chains:{},selectedWallets:{},requiredChainIds:[]},Fe=h.createContext(Pe);function En(t,e){return Object.keys(t).reduce((n,i)=>(e.has(i)&&(n[i]=t[i]),n),{})}function wt({children:t,chains:e,requiredChainIds:n,storage:i}){const[r,o]=h.useState(()=>({...Pe,chains:e.reduce((a,l)=>({...a,[l.id]:l}),{}),requiredChainIds:[...n]})),c=n.some(a=>!r.requiredChainIds.includes(a)),s=h.useMemo(()=>({...r,confirmed:c?!1:r.confirmed,requiredChainIds:[...n]}),[n,c,r]),d=h.useRef(n);h.useInsertionEffect(()=>{d.current=n},[n]),h.useEffect(()=>{o(a=>{const l=e.reduce((y,m)=>({...y,[m.id]:m}),{}),f=new Set(e.map(y=>y.id)),p=En(a.selectedWallets,f),C=n.some(y=>!a.requiredChainIds.includes(y));return{...a,confirmed:C?!1:a.confirmed,chains:l,selectedWallets:p,requiredChainIds:[...n]}})},[e,n]);const g=h.useMemo(()=>({open:()=>{typeof window<"u"&&window.dispatchEvent(new Event(De)),o(a=>({...a,visible:!0}))},close:()=>{o(a=>({...a,visible:!1}))},reset:()=>{i==null||i.delete(V),o(({chains:a,requiredChainIds:l})=>({...Pe,chains:a,requiredChainIds:l}))},displayLoader:(a="",l="")=>{o(f=>({...f,screen:{type:"LOADER",params:{message:a,description:l}}}))},displayChains:()=>{o(a=>({...a,screen:{type:"CHAINS"}}))},displayWallets:a=>{o(l=>({...l,screen:{type:"WALLETS",params:{chain:a}}}))},displayError:a=>{o(l=>({...l,screen:{type:"ERROR",params:a}}))},selectWallet:(a,l)=>{o(f=>({...f,selectedWallets:{...f.selectedWallets,[a]:l}}))},removeWallet:a=>{const l=d.current.includes(a);l&&(i==null||i.delete(V)),o(f=>({...f,confirmed:l?!1:f.confirmed,confirmationReceipt:l?void 0:f.confirmationReceipt,selectedWallets:{...f.selectedWallets,[a]:void 0}}))},confirm:a=>{o(l=>({...l,confirmed:!0,confirmationReceipt:a}))},unconfirm:(a=!1)=>{o(l=>({...l,confirmed:!1,confirmationReceipt:a?l.confirmationReceipt:void 0}))}}),[i]),u=h.useMemo(()=>({...s,...g}),[s,g]);return E.jsx(Fe.Provider,{value:u,children:t})}const We={BTC:null,BBN:null,ETH:null},Nt=h.createContext(We);function pn({persistent:t,storage:e,children:n,context:i,config:r,onError:o,disabledWallets:c,requiredChains:s,metadata:d}){const[g,u]=h.useState(We),a=h.useCallback(async()=>{const C=r.filter(m=>d[m.chain]).map(async({chain:m,config:N})=>{const w=d[m];if(!w)return null;try{return await pt({persistent:t,metadata:w,context:i,config:N,accountStorage:e,disabledWallets:c})}catch(x){throw console.error("[ChainProvider] failed to create connector for chain:",m,x instanceof Error?x.message:"Unknown error"),x}});return(await Promise.all(C)).reduce((m,N)=>N?{...m,[N.id]:N}:m,{...We})},[t,r,i,e,c,d]);h.useEffect(()=>{a().then(p=>{u(p)}).catch(p=>{console.error("[ChainProvider] init failed with error:",p instanceof Error?p.message:"Unknown error"),o==null||o(p)})},[u,a,o]),on({connectors:g,setConnectors:u,config:r,context:i,storage:e,disabledWallets:c,persistent:t,metadata:d}),h.useEffect(()=>{const p=Object.values(g).filter(Boolean);if(p.length===0)return;const C=()=>u(m=>({...m})),y=p.flatMap(m=>[m.on("connect",C),m.on("disconnect",C)]);return()=>y.forEach(m=>m())},[g]);const l=h.useMemo(()=>Object.values(g).filter(p=>!!p),[g]),f=h.useMemo(()=>s===void 0?r.filter(p=>d[p.chain]).map(p=>p.chain):[...s],[r,d,s]);return E.jsx(cn,{context:i,children:E.jsx(wt,{chains:l,requiredChainIds:f,storage:e,children:E.jsx(Nt.Provider,{value:g,children:n})})})}const he=()=>h.useContext(Nt),Tt=h.createContext({});function gn({children:t,value:e}){const n=h.useMemo(()=>e??{},[e]);return E.jsx(Tt.Provider,{value:n,children:t})}const At=()=>h.useContext(Tt),ae="baby-connected-wallet-accounts";function Ie(t,e){const n=e==null?void 0:e[t];return n?`${t}:${n}`:t}function we(){const t=localStorage.getItem(ae);if(!t)return{};try{const e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?(localStorage.removeItem(ae),{}):e}catch(e){return console.error("[account-storage] Failed to parse accounts map, clearing corrupted entry:",e),localStorage.removeItem(ae),{}}}function Xe(t){try{localStorage.setItem(ae,JSON.stringify(t))}catch(e){console.error("[account-storage] Failed to write accounts map, clearing entry:",e),localStorage.removeItem(ae)}}const mn=(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 d=Date.now();return s<0||s>d+t?!0:d-s>t}return{get:r=>{const o=we(),c=Ie(r,e);if(!i(o,c))return o[c]},has:r=>{const o=we(),c=Ie(r,e);return i(o,c)?!1:!!o[c]},set:(r,o)=>{const c=we(),s=Ie(r,e),d=n(c);c[s]=o,c._timestamps={...d,[s]:Date.now()},Xe(c)},delete:r=>{const o=we(),c=Ie(r,e),s=n(o),d=Reflect.deleteProperty(o,c);return delete s[c],o._timestamps=s,Xe(o),d}}},_t="#000000",Cn="#1FE121",yt="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",de="babylon:open-appkit",Ke="appkit-eth-connector",vt="appkit-btc-connector",Ze="bigint",qe="function",In="AppKit configuration cannot be serialized.",wn=1,Qe=new WeakMap;let Nn=wn;function Tn(t){const e=Qe.get(t);if(e)return e;const n=Nn++;return Qe.set(t,n),n}function Je(t){const e=JSON.stringify(t,(n,i)=>typeof i===Ze?{type:Ze,value:i.toString()}:typeof i===qe?{type:qe,value:Tn(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(In);return e}function Rt({projectId:t,metadata:e,ethChain:n,btcNetwork:i}){return Object.freeze({projectId:t,metadataFingerprint:Je(e),ethFingerprint:n?Je(n):void 0,btcNetwork:i})}let X=null,St=null;const Ae=new Set;function H(t,e){throw new oe({code:re.WALLET_INITIALIZATION_FAILED,message:t,chainId:e})}function Re(){return X}function _e(){return(X==null?void 0:X.modal)??St}function xt(t,e){X&&H(`Cannot set a manual ${t} AppKit configuration after AppKit initialization. Use the canonical AppKit state.`),Ae.add(t),e&&(St=e)}function Ot(t){return t?(Ae.size>0&&H(`Cannot initialize AppKit after a manual ${[...Ae].join(" and ")} configuration was set. Use only one initialization method.`),!0):(X&&H("AppKit is already initialized. A project ID is required to validate the requested configuration."),!1)}function Lt(t){return X&&H("AppKit is already initialized. Reuse the shared AppKit state instead of replacing it."),Ae.size>0&&H("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&&H("AppKit was already initialized with a different project ID. A page can use only one AppKit configuration."),t.metadataFingerprint!==e.metadataFingerprint&&H("AppKit was already initialized with different metadata. A page can use only one AppKit configuration."),e.ethFingerprint&&(t.ethFingerprint||H("AppKit was already initialized without Ethereum support. A page that needs Ethereum must initialize AppKit with Ethereum first.","ETH"),t.ethFingerprint!==e.ethFingerprint&&H("AppKit was already initialized with a different Ethereum chain configuration.","ETH")),e.btcNetwork&&(t.btcNetwork||H("AppKit was already initialized without Bitcoin support. A page that needs Bitcoin must initialize AppKit with Bitcoin first.","BTC"),t.btcNetwork!==e.btcNetwork&&H("AppKit was already initialized with a different Bitcoin network.","BTC"))}const An="Ethereum",_n="Shared wagmi config is being replaced. This might indicate multiple initializations.";let ie=null;function yn(t){xt(An),ie&&ie!==t&&console.warn(_n),ie=t}function ke(){const t=Re();if(t)return t.wagmiConfig||H("AppKit was initialized without Ethereum support. Initialize it with Ethereum support.","ETH"),t.wagmiConfig;if(!ie)throw new Error("Shared wagmi config not initialized. Initialize AppKit with Ethereum support, or use setSharedWagmiConfig() as an exclusive manual alternative.");return ie}function Te(){const t=Re();return t?t.wagmiConfig!==void 0:ie!==null}function Dt(){var n;const t=_e();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 vn=1500,et="Wallet not connected",Rn="Ethereum Wallet",Sn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=";class xn{constructor(e){b(this,"config");b(this,"address");b(this,"chainId");b(this,"eventHandlers",new Map);b(this,"unwatchFunctions",[]);this.config=e,this.ensureEventWatchers()}ensureEventWatchers(){this.unwatchFunctions.length>0||Te()&&this.setupEventWatchers()}getWagmiConfig(){if(!Te())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 ke()}setupEventWatchers(){const e=this.getWagmiConfig(),n=W.getAccount(e);n.address&&n.status==="connected"&&(this.address=n.address,this.chainId=n.chainId,setTimeout(()=>{this.emit("accountsChanged",[n.address])},100));const i=W.watchAccount(e,{onChange:o=>{const c=this.address;this.address=o.address,this.chainId=o.chainId,c!==o.address&&this.emit("accountsChanged",o.address?[o.address]:[])}}),r=W.watchChainId(e,{onChange:o=>{const c=this.chainId;this.chainId=o,c!==o&&this.emit("chainChanged",`0x${o.toString(16)}`)}});this.unwatchFunctions.push(i,r)}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=W.getAccount(e);if(n.address){this.address=n.address,this.chainId=n.chainId;return}if(typeof window<"u"){await new Promise((s,d)=>{let g=!1,u;const a=()=>{clearTimeout(l),u&&clearTimeout(u),f(),C==null||C()},l=setTimeout(()=>{a(),d(new Error("Connection timeout"))},6e4),f=W.watchAccount(e,{onChange:y=>{y.address&&(this.address=y.address,this.chainId=y.chainId,a(),s())}}),p=_e(),C=p==null?void 0:p.subscribeState(y=>{if(y.open)g=!0,u&&(clearTimeout(u),u=void 0);else if(g){const m=W.getAccount(e);if(m.address){this.address=m.address,this.chainId=m.chainId,a(),s();return}u=setTimeout(()=>{const N=W.getAccount(e);N.address?(this.address=N.address,this.chainId=N.chainId,a(),s()):(a(),d(new Error("Connection cancelled")))},vn)}});window.dispatchEvent(new CustomEvent(de))});return}const i=ft.env.NEXT_PUBLIC_REOWN_PROJECT_ID;if(!i)throw new Error("NEXT_PUBLIC_REOWN_PROJECT_ID environment variable is required");const r=ct.walletConnect({projectId:i,metadata:{name:"Babylon Vault",description:"",url:"",icons:[""]}}),o=await W.connect(e,{connector:r});this.address=o.accounts[0],this.chainId=o.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"&&Dt())throw new oe({code:re.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 W.disconnect(this.getWagmiConfig()),this.address=void 0,this.chainId=void 0}async getAddress(){const e=this.getWagmiConfig(),n=W.getAccount(e);if(n.address)return this.address=n.address,this.chainId=n.chainId,this.address;if(this.address)return this.address;throw new Error(et)}async getPublicKeyHex(){return this.getAddress()}async signMessage(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await W.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 W.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 W.sendTransaction(n,{account:i,to:e.to,value:e.value?Oe.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 W.estimateGas(n,{account:i,to:e.to,value:e.value?Oe.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=W.getAccount(e);if(n.chainId)return this.chainId=n.chainId,this.chainId;throw new Error(et)}async switchChain(e){try{const n=this.getWagmiConfig();if(![1,11155111,31337].includes(e))throw new Error(`Unsupported chain ID: ${e}`);await W.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 W.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 W.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=_e())==null?void 0:n.getWalletInfo("eip155");if(e!=null&&e.name||e!=null&&e.icon)return{name:e.name,icon:e.icon};if(Te())try{const{connector:i}=W.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:Rn}getWalletProviderIcon(){var n;const e=(n=this.getActiveConnectorIdentity())==null?void 0:n.icon;return e!=null&&e.trim()?e:Sn}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 On="AppKit",Ln={id:Ke,name:On,icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=",docs:"https://docs.reown.com/appkit/overview",wallet:void 0,createProvider:(t,e)=>new xn(e),networks:[U.MAINNET,U.TESTNET,U.SIGNET],label:"Connect ETH Wallet"},bn="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",Dn={chain:"ETH",name:"Ethereum",icon:bn,wallets:[Ln]};function Pt(t,e){const n=t.rpcUrls.default.http[0];return new kt.WagmiAdapter({networks:[t],projectId:e,ssr:!1,storage:Ye.createStorage({storage:Ye.cookieStorage}),connectors:[ct.baseAccount({preference:{telemetry:!1}})],transports:{[t.id]:Oe.http(n)}})}function Pn(t){if(!Ot(t.projectId))return null;const{chain:e}=t.eth,n=Rt({projectId:t.projectId,metadata:t.metadata,ethChain:e}),i=Re();if(i)return bt(i,n),{modal:i.modal,wagmiConfig:ke()};Ve.modal&&H("Reown AppKit was initialized outside this package. Use only this package to initialize it.");const r=Pt(e,t.projectId),o=Ve.createAppKit({adapters:[r],networks:[e],projectId:t.projectId,metadata:t.metadata});return{modal:Lt({modal:o,...n,wagmiConfig:r.wagmiConfig}).modal,wagmiConfig:r.wagmiConfig}}const Wn=()=>{h.useEffect(()=>{const t=()=>{try{const e=_e();e&&e.open()}catch(e){console.warn("AppKit modal not available:",e)}};return window.addEventListener(de,t),()=>window.removeEventListener(de,t)},[])};function Wt(t){const e=he();return(e==null?void 0:e[t])??null}const jn=[{match:/okx/i,icon:yt,iconBackground:_t}];function Mn(t){return jn.find(({match:e})=>e.test(t))}const J=()=>h.useContext(Fe);async function tt(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=Mn(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 Bn=new Set([re.INCOMPATIBLE_WALLET_VERSION]);function Hn({persistent:t,accountStorage:e,onError:n,btcValidation:i}){const r=he(),{confirmed:o,confirmationReceipt:c,visible:s,selectWallet:d,removeWallet:g,displayLoader:u,displayChains:a,displayError:l,confirm:f,unconfirm:p,requiredChainIds:C=[]}=J(),{verifyBTCAddress:y}=At(),m=h.useRef(0),N=h.useRef(C),w=c??(t&&!s?e.get(V):void 0),x=h.useRef(),M=h.useRef(new Set),P=C.every(v=>{var _;return(_=r[v])==null?void 0:_.connectedWallet}),O=h.useRef(new Set),S=async v=>{O.current.add(v.id),g==null||g(v.id),t&&e.delete(v.id);try{await v.disconnect("chain")}catch(_){le(_)||console.error("Failed to disconnect rejected wallet:",_ instanceof Error?_.message:"Unknown error"),await v.disconnect("local")}finally{O.current.delete(v.id)}};h.useEffect(()=>{if(!s)return;const _=Object.values(r).filter(Boolean).map(T=>T.on("connecting",(I,A)=>{u==null||u(I,A)}));return()=>_.forEach(T=>T())},[s,u,r]),h.useEffect(()=>{const v=Object.values(r).filter(Boolean),_={BTC:I=>async A=>{var K,Ee,j,B;try{if(!A||!A.account)return;if(!i)throw new Error("Bitcoin address validation is unavailable");if(d==null||d("BTC",A),t&&((K=A.account)!=null&&K.address)&&e.set(I.id,A.id),!s)return;i.validateAddress(I.config.network,A.account.address);const k=()=>void(a==null?void 0:a());if(!i.validateAddressWithPK(((Ee=A.account)==null?void 0:Ee.address)??"",((j=A.account)==null?void 0:j.publicKeyHex)??"",I.config.network)){l==null||l({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:k,onCancel:()=>{S(I),a==null||a()}});return}if(y&&!await y(((B=A.account)==null?void 0:B.address)??"")){l==null||l({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(I),a==null||a()}});return}k()}catch(k){S(I),l==null||l({title:"Connection Failed",description:k.message,submitButton:"",cancelButton:"Done",onCancel:async()=>{a==null||a()}})}},BBN:I=>A=>{var K;A&&(d==null||d(I.id,A),t&&((K=A.account)!=null&&K.address)&&e.set(I.id,A.id)),a==null||a()},ETH:I=>async A=>{var K;A&&(d==null||d(I.id,await tt(A)),t&&((K=A.account)!=null&&K.address)&&e.set(I.id,A.id)),a==null||a()}},T=v.map(I=>{var A;return I.on("connect",(A=_[I.id])==null?void 0:A.call(_,I))});return v.forEach(I=>{const A=O.current.has(I.id)?null:I.connectedWallet;if(I.id==="ETH"&&A){tt(A).then(K=>d==null?void 0:d(I.id,K));return}d==null||d(I.id,A)}),()=>T.forEach(I=>I())},[n,d,g,a,l,y,i,e,r,t,s]),h.useLayoutEffect(()=>{const _=Object.values(r).filter(Boolean).map(T=>T.on("disconnect",I=>{I&&(C.includes(T.id)&&(m.current+=1,e.delete(V)),g==null||g(T.id),a==null||a(),t&&e.delete(T.id))}));return()=>_.forEach(T=>T())},[g,a,r,t,e,C]),h.useEffect(()=>{const _=Object.values(r).filter(Boolean).map(T=>T.on("error",I=>{if(n==null||n(I),I instanceof oe&&Bn.has(I.code)&&l){const A=I.wallet??"your wallet";l({title:`Update ${A}`,description:I.message||`${A} needs to be updated before you can connect.`,submitButton:"",cancelButton:"Done",onCancel:()=>{a==null||a()}});return}a==null||a()}));return()=>_.forEach(T=>T())},[n,a,l,r]);const R=h.useCallback(async()=>{const v=++m.current;if(!w||!c&&!P)return;const _=await hn(w,C,r);if(v===m.current){if(!_){e.delete(V),p==null||p();return}if(!o&&!s){f==null||f(w),a==null||a();return}t&&o&&e.set(V,w)}},[e,w,c,o,f,r,a,t,C,P,p,s]);return h.useEffect(()=>{R()},[R]),h.useLayoutEffect(()=>{const v=x.current;(!w||v&&v!==w)&&M.current.clear(),x.current=w},[w]),h.useLayoutEffect(()=>{m.current+=1;const v=C.filter(T=>!N.current.includes(T));if(N.current=C,!w)return;const _=Ct(w,It(w),r,T=>{if(!C.includes(T)){M.current.add(T);return}m.current+=1,e.delete(V),p==null||p()});if(!c&&!P)return _;if(!fn(w,C,r)||v.some(T=>M.current.has(T))||c&&v.length>0&&!un(w,v,r)){_(),e.delete(V),p==null||p();return}return c&&v.length>0&&(p==null||p(!0)),_},[e,w,c,r,C,P,p]),h.useEffect(()=>()=>{m.current+=1},[]),{connect:h.useCallback(async(v,_)=>{const T=r[v.id];await(T==null?void 0:T.connect(_.id))},[r])}}function Fn(t,e,n){const i=h.useCallback((r,o)=>E.jsx(E.Fragment,{children:o.map(({id:c,widget:s})=>E.jsx(s,{id:c,connector:t[r],createWallet:Et,onError:n},c))}),[t,n]);return h.useMemo(()=>e.reduce((r,o)=>({...r,[o.chain]:i(o.chain,o.connectors??[])}),{}),[i,e])}function Ue(){const{confirmed:t,chains:e,requiredChainIds:n,selectedWallets:i,open:r,displayChains:o,displayError:c,displayWallets:s,reset:d}=J(),g=he(),u=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 p;if(f!==void 0&&Object.prototype.hasOwnProperty.call(g,f)){try{await((p=g[f])==null?void 0:p.disconnect("chain"))}catch(C){throw le(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(g))C&&await C.disconnect("all");d==null||d()},[g,o,c,d]),l=h.useMemo(()=>n.every(f=>!!i[f]),[n,i]);return{selected:l,connected:l&&t,open:u,disconnect:a}}function Kn({className:t,alt:e,logo:n,title:i,children:r,onClick:o}){const c=typeof n=="string"?E.jsx(L.Avatar,{url:n,alt:e}):E.jsx(L.Avatar,{children:n}),s=()=>{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 E.jsxs(L.Text,{as:"button",className:Y.twMerge("flex w-full cursor-pointer flex-col gap-4 rounded-lg bg-neutral-200 p-4 text-accent-primary",t),onClick:o,"data-testid":s(),children:[E.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[E.jsx("div",{className:"flex items-center",children:c}),i,E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",className:"ml-auto block text-accent-secondary",children:E.jsx("path",{d:"M8.58984 16.59L13.1698 12L8.58984 7.41L9.99984 6L15.9998 12L9.99984 18L8.58984 16.59Z",fill:"currentColor"})})]}),r&&E.jsx("div",{className:"w-full",children:r})]})}const kn=36,nt=14;function Un(t){return t.length<=kn?t:`${t.slice(0,nt)}…${t.slice(-nt)}`}const Gn=h.memo(({className:t,logo:e,logoBackground:n,address:i})=>{const{isCopied:r,copyToClipboard:o}=L.useCopy(),c=r(i),s=d=>{d.stopPropagation(),o(i,i)};return E.jsxs("div",{className:Y.twMerge("flex items-center gap-2.5 rounded-lg bg-neutral-200 p-2",t),children:[E.jsx(L.WalletIcon,{size:"small",className:"shrink-0",url:e,background:n}),E.jsx(L.Text,{as:"div",variant:"caption",title:i,className:"min-w-0 flex-1 truncate text-left font-mono text-accent-secondary",children:Un(i)}),E.jsx("span",{role:"button",tabIndex:0,"aria-label":c?"Address copied":"Copy address",onClick:s,onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&s(d)},className:"flex shrink-0 cursor-pointer items-center text-accent-secondary hover:text-accent-primary",children:c?E.jsx(L.CheckIcon,{size:16,variant:"success"}):E.jsx(L.CopyIcon,{size:16})})]})}),zn="disabled:!bg-[#CCCCCC] dark:disabled:!bg-secondary-strokeDark",Vn="Select ",Yn=" Wallet",$n=" (Optional)",Xn=h.memo(({disabled:t=!1,chains:e,requiredChainIds:n,selectedWallets:i={},className:r,onConfirm:o,onSelectChain:c})=>E.jsxs("div",{className:Y.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight text-accent-primary",r),children:[E.jsx("div",{className:"border-b border-secondary-strokeLight p-6",children:E.jsx(L.Heading,{variant:"h5",className:"text-accent-primary",children:"Connect Wallets"})}),E.jsxs("div",{className:"flex flex-col gap-4 p-6",children:[E.jsxs("div",{className:"flex flex-col gap-2",children:[e.map(s=>{var u;const d=i[s.id],g=n!==void 0&&!n.includes(s.id);return E.jsx(Kn,{title:`${Vn}${s.name}${Yn}${g?$n:""}`,logo:s.icon,alt:s.name,onClick:()=>void(c==null?void 0:c(s)),children:d&&E.jsx(Gn,{logo:d.icon,logoBackground:d.iconBackground,address:((u=d.account)==null?void 0:u.address)??""})},s.id)}),E.jsx(L.Button,{color:"secondary",disabled:t,fluid:!0,onClick:o,className:Y.twMerge("text-sm disabled:!opacity-100",zn),"data-testid":"chains-connect-button",children:"Connect"})]}),E.jsxs(L.Text,{variant:"body2",className:"text-center text-accent-secondary",children:["By clicking Connect you agree with the"," ",E.jsx("a",{href:"https://babylonlabs.io/terms-of-use",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Terms of Use"})," ","and"," ",E.jsx("a",{href:"https://babylonlabs.io/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Privacy Policy"}),"."]})]})]}));function Zn(){typeof window<"u"&&window.dispatchEvent(new Event(de))}function qn(t){const{chains:e,requiredChainIds:n,selectedWallets:i,displayWallets:r}=J(),{selected:o,disconnect:c}=Ue(),s=he(),d=h.useMemo(()=>Object.values(e),[e]),g=h.useCallback(async u=>{if(u.id==="ETH"||u.id==="BTC"){const a=s[u.id],l=u.id==="ETH"?Ke:vt,f=a==null?void 0:a.wallets.find(p=>p.id===l);if(f&&(a==null?void 0:a.wallets.length)===1){const p=!!a.connectedWallet;try{p?u.id==="ETH"&&!Dt()?Zn():await c(u.id):await a.connect(f.id)}catch(C){le(C)||console.error(`Failed to ${p?"disconnect":"connect"} AppKit ${u.id}:`,C instanceof Error?C.message:"Unknown error")}return}}r==null||r(u.id)},[r,s,c]);return E.jsx(Xn,{disabled:!o,chains:d,requiredChainIds:n,selectedWallets:i,onSelectChain:g,...t})}const Qn=E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"52",height:"52",viewBox:"0 0 52 52",fill:"none",children:E.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 Jn({className:t,icon:e=Qn,title:n,description:i,cancelButton:r="Cancel",submitButton:o=E.jsxs(E.Fragment,{children:["Continue ",E.jsx("span",{className:"hidden md:inline",children:"Anyway"})]}),onCancel:c,onSubmit:s}){return E.jsxs("div",{className:t,children:[E.jsxs(L.DialogBody,{className:"py-16 text-center",children:[E.jsx("div",{className:"mb-6 inline-flex size-20 items-center justify-center bg-primary-contrast text-primary-light",children:e}),E.jsx(L.Heading,{variant:"h4",className:"mb-4 text-accent-primary",children:n}),E.jsx(L.Text,{as:"div",className:"text-accent-secondary",children:i})]}),E.jsxs(L.DialogFooter,{className:"flex gap-4",children:[r&&E.jsx(L.Button,{variant:"outlined",fluid:!0,onClick:c,children:r}),o&&E.jsx(L.Button,{fluid:!0,onClick:s,"data-testid":"error-continue-button",children:o})]})]})}function ei({className:t}){const{screen:e}=J(),{icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:d}=e.params??{};return E.jsx(Jn,{className:t,icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:d})}function ti({className:t,title:e,description:n}){return E.jsxs("div",{className:Y.twMerge("flex flex-col items-center justify-center gap-6",t),children:[E.jsx("div",{className:"flex items-center justify-center bg-primary-contrast p-6",children:E.jsx(L.Loader,{className:"text-primary-light"})}),(e||n)&&E.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[e&&E.jsx(L.Heading,{variant:"h4",className:"capitalize text-accent-primary",children:e}),n&&E.jsx(L.Text,{as:"div",className:"text-accent-secondary",children:n})]})]})}const ni="text-[#15B768] dark:text-[#00E676]",ii="bg-[#15B768] dark:bg-[#00E676]",ri="text-[#FFB300]",oi="bg-[#FFB300]";function si({className:t,disabled:e=!1,name:n,logo:i,logoBackground:r,fallbackLink:o,installed:c=!0,hardware:s=!1,label:d,onClick:g}){const a=c||s?{as:"button",disabled:e,onClick:g}:{as:"a",href:o,target:"_blank",rel:"noopener noreferrer"},l=()=>{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 E.jsxs(L.Text,{variant:"body2",className:Y.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":l(),children:[E.jsx(L.WalletIcon,{className:"shrink-0",alt:n,url:i,background:r}),E.jsx("span",{className:Y.twMerge("min-w-0 flex-1 truncate text-left",!c&&"text-accent-secondary"),children:n}),E.jsxs(L.Chip,{className:Y.twMerge("flex shrink-0 items-center gap-1.5 rounded-full",c?"bg-neutral-100":"bg-neutral-200"),children:[(s||c)&&E.jsx("span",{className:Y.twMerge("size-2 rounded-full",s?oi:ii)}),E.jsx("span",{className:s?ri:c?ni:"text-accent-secondary",children:s?d:c?"Installed":"Uninstalled"})]})]})}const ci={[U.MAINNET]:"bc1p",[U.TESTNET]:"tb1p",[U.SIGNET]:"tb1p"},ai="https://tbv-faucet.testnet.babylonlabs.io/",it=t=>t.installed&&!t.hardware?0:t.hardware?1:2,di=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,d)=>it(s)-it(d)),[t]),o=h.useMemo(()=>{var g;if(t.id!=="BTC")return null;const s=(g=t.config)==null?void 0:g.network,d=s?ci[s]:void 0;return d?{prefix:d,showFaucet:s!==U.MAINNET}:null},[t]),c=h.useCallback(async s=>{i==null||i(t,s)},[t,i]);return E.jsxs("div",{className:Y.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight",e),children:[E.jsxs("div",{className:"flex flex-col gap-2 border-b border-secondary-strokeLight p-6",children:[E.jsx(L.Heading,{variant:"h5",className:"text-accent-primary",children:`Select ${t.name} Wallet`}),o&&E.jsxs(L.Text,{variant:"body2",className:"text-accent-secondary",children:[`To continue, connect a ${t.name} wallet with a `,E.jsx("span",{className:"text-accent-primary",children:`${o.prefix} (Taproot)`})," address.",o.showFaucet&&E.jsxs(E.Fragment,{children:[" Don't have testnet BTC yet? Get it from ",E.jsx("a",{href:ai,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline underline-offset-2 transition-opacity hover:opacity-80",children:"Faucet"}),"."]})]})]}),E.jsxs("div",{className:"flex flex-col gap-4 p-6",children:[r.map(s=>E.jsx(si,{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 li({widgets:t={},...e}){var s;const{chains:n,screen:i}=J(),r=((s=i.params)==null?void 0:s.chain)??"",o=n==null?void 0:n[r],c=t==null?void 0:t[r];return E.jsx(di,{append:c,chain:o,...e})}const rt={CHAINS:({onConfirm:t})=>E.jsx(qn,{onConfirm:t}),WALLETS:({widgets:t,onSelectWallet:e})=>E.jsx(li,{widgets:t,onSelectWallet:e}),LOADER:({current:t})=>{var e,n;return E.jsx(ti,{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:()=>E.jsx(ei,{}),EMPTY:()=>E.jsx("div",{})};function ui(t){const e=rt[t.current.type]??rt.EMPTY;return E.jsx(e,{...t})}const te="Wallet changed while confirming",fi="Wallet did not report its network",hi="Wallet network does not match the configured network",Ei="Connected wallet has no provider";function pi(t,e){for(const n of e){const i=t.find(({chain:r})=>r===n);if(i)return i}return t[0]}function je(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 ot(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 gi(t,e,n){return t.every(({chain:i,wallet:r,provider:o,receipt:c})=>{const s=e.find(d=>d.chain===i);return s?s.wallet===r&&s.provider===o&&s.receipt===c:!n.includes(i)})}async function st(t,e,n){const i=t(),r=je(i).map(l=>({connection:l,provider:l.wallet.provider,receipt:ce([l],i)})),c=(await Promise.all(r.map(async l=>{var C,y;const{chain:f}=l.connection,{provider:p}=l;try{if(!p)throw new Error(`${Ei}: ${f}`);if(((C=p.isIdentityCurrent)==null?void 0:C.call(p))===!1)throw new Error(te);let m;if(f==="ETH"||f==="BTC"){if(m=f==="ETH"?await p.getChainId():await p.getNetwork(),m==null||!String(m))throw new Error(fi);if(ce([l.connection],i,{[f]:m})!==l.receipt)throw new Error(hi)}const[N,w]=await Promise.all([p.getAddress(),p.getPublicKeyHex()]);if(!N||!w||!Q(N,l.connection.account.address)||!Q(w,l.connection.account.publicKeyHex))throw new Error(te);if(((y=p.isIdentityCurrent)==null?void 0:y.call(p))===!1)throw new Error(te);return{...l,connection:{...l.connection,account:{address:N,publicKeyHex:w}}}}catch(m){if(e.includes(f))throw m;return n==null||n(m instanceof Error?m:new Error("Optional wallet verification failed")),null}}))).filter(l=>l!==null),s=t(),d=je(s),g=c.flatMap(l=>{const{connection:f,receipt:p}=l,C=d.find(({chain:m})=>m===f.chain);if(!!(C&&C.wallet===f.wallet&&C.wallet.provider===l.provider&&ce([C],s)===p))return[l];if(e.includes(f.chain))throw new Error(te);return n==null||n(new Error(te)),[]}),u=g.map(({connection:l})=>l),a=g.map(({connection:l,provider:f,receipt:p})=>({chain:l.chain,wallet:l.wallet,provider:f,receipt:p}));return{receipt:ce(u,s),connections:u,identities:Object.freeze(a)}}function mi({persistent:t,storage:e,config:n,onError:i,btcValidation:r,actions:o,closeButtonClassName:c,actionsClassName:s}){const{visible:d,screen:g,confirmed:u,requiredChainIds:a,close:l,confirm:f,unconfirm:p,displayChains:C,displayError:y}=J(),{acceptTermsOfService:m,onConfirm:N}=At(),w=he(),x=Fn(w,n,i),{connect:M}=Hn({persistent:t,accountStorage:e,onError:i,btcValidation:r}),P=h.useRef(w),O=h.useRef(0),S=h.useRef(null),R=h.useRef(null),F=h.useRef(!1),v=h.useRef(d),_=h.useRef(u),T=h.useRef({persistent:t,requiredChainIds:[...a],storage:e}),I=h.useCallback(()=>{const j=R.current;R.current=null,O.current+=1,S.current=null,j==null||j()},[]);h.useLayoutEffect(()=>{P.current=w,(v.current&&!d||!_.current&&u)&&I(),v.current=d,_.current=u},[u,w,I,d]),h.useLayoutEffect(()=>(F.current=!0,()=>{F.current=!1,I()}),[I]),h.useLayoutEffect(()=>{const j=T.current,B=j.requiredChainIds.length!==a.length||j.requiredChainIds.some((k,pe)=>k!==a[pe]);(j.persistent!==t||j.storage!==e||B)&&I(),T.current={persistent:t,requiredChainIds:[...a],storage:e}},[I,t,a,e]);const A=h.useCallback(()=>{I(),l==null||l()},[l,I]),K=h.useCallback(async()=>{if(S.current!==null||!F.current||!v.current)return;const j=O.current+1;O.current=j,S.current=j;const B=()=>S.current===j&&O.current===j&&F.current&&v.current;let k=()=>{},pe=!1;try{if(!u){const ee=P.current,se=ce(je(ee),ee),Bt=Ct(se,It(se),ee,()=>{I(),e.delete(V),p==null||p()});let Ge=!0;if(k=()=>{Ge&&(Ge=!1,Bt())},!B()){k();return}R.current=k;const ge=await st(()=>P.current,a,i);if(!B())return;const{connections:me}=ge,Se=a.filter(xe=>!me.some(({chain:Ht})=>Ht===xe));if(Se.length>0)throw new Error(`No connected account for required chain${Se.length>1?"s":""}: ${Se.join(", ")}`);const Ce=pi(me,a),ze=async()=>{if(!B())return!1;const xe=await st(()=>P.current,a,i);if(!B())return!1;if(!gi(ge.identities,xe.identities,a))throw new Error(te);return!0};if(Ce&&(await(m==null?void 0:m({address:Ce.account.address,public_key:Ce.account.publicKeyHex,chain:Ce.chain,connections:ot(me)})),!await ze())||(await(N==null?void 0:N(ot(me))),!await ze())||(t&&e.set(V,ge.receipt),!B())||(f==null||f(ge.receipt),!B()))return;pe=!!f}if(!B())return;l==null||l()}catch(ee){if(!B())return;const se=ee instanceof Error?ee:new Error("Wallet confirmation failed");if(i==null||i(se),!B())return;y==null||y({title:"Connection Failed",description:se.message,submitButton:"",cancelButton:"Done",onCancel:C})}finally{pe||(k(),R.current===k&&(R.current=null),O.current===j&&S.current===j&&(S.current=null))}},[m,l,f,u,C,y,I,N,i,t,a,e,p]),Ee=g.type==="WALLETS"?C:void 0;return E.jsx(L.FullScreenDialog,{open:d,onClose:A,onBack:Ee,className:"items-center justify-center p-6",actions:o,closeButtonClassName:c,actionsClassName:s,children:E.jsx("div",{className:"mx-auto w-full max-w-[612px]",children:E.jsx(ui,{current:g,widgets:x,onConfirm:K,onSelectWallet:M})})})}function jt(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 Mt=h.createContext({loading:!0,connected:!1,address:void 0,disconnect:()=>{},open:()=>{}}),Ci=({children:t,callbacks:e})=>{const[n,i]=h.useState(!0),[r,o]=h.useState(),[c,s]=h.useState(null),{open:d,disconnect:g}=Ue(),u=Wt("ETH"),a=h.useCallback(async()=>{try{await(u==null?void 0:u.disconnect("local"))}catch(m){console.error("Failed to disconnect ETH connector:",m instanceof Error?m.message:"Unknown error")}},[u]),l=h.useCallback(async m=>{var N,w;try{o(m),i(!1),await((N=e==null?void 0:e.onConnect)==null?void 0:N.call(e,m))}catch(x){i(!1),(w=e==null?void 0:e.onError)==null||w.call(e,x instanceof Error?x:new Error("ETH connection failed"),{address:m})}},[e]);h.useEffect(()=>{if(i(!1),!u)return;(async()=>{var O;try{if((O=u.connectedWallet)!=null&&O.provider&&!r){const S=u.connectedWallet.provider,R=await S.getAddress();R&&(s(S),l(R));return}if(!r&&u.wallets.length>0){const S=u.wallets[0];if(S.provider)try{await S.provider.getAddress()&&await u.connect(S)}catch{}}}catch{}})();const N=u.on("connect",async O=>{if(O.provider)try{const S=await O.provider.getAddress();S&&(s(O.provider),l(S))}catch(S){console.error("Error getting ETH address:",S instanceof Error?S.message:"Unknown error")}}),w=u.wallets[0],x=w==null?void 0:w.provider;let M=!1;const P=O=>{!(O!=null&&O[0])||r||M||(M=!0,u.connect(w).then(S=>{S||(M=!1)}).catch(S=>{M=!1,console.error("ETH late reconnect failed:",S instanceof Error?S.message:"Unknown error")}))};return x&&typeof x.on=="function"&&x.on("accountsChanged",P),()=>{N(),x&&typeof x.off=="function"&&x.off("accountsChanged",P)}},[u,l,r]),h.useEffect(()=>{if(u)return u.on("disconnect",async()=>{var m;o(void 0),s(null);try{await((m=e==null?void 0:e.onDisconnect)==null?void 0:m.call(e))}catch(N){console.error("Error in onDisconnect callback:",N instanceof Error?N.message:"Unknown error")}})},[u,e]);const f=h.useRef(void 0),p=h.useRef(!1);h.useEffect(()=>{f.current=r},[r]),h.useEffect(()=>{if(!c)return;const m=async N=>{var M,P;if(p.current)return;const w=N[0],x=f.current;if(w&&w.toLowerCase()!==(x==null?void 0:x.toLowerCase())){p.current=!0,f.current=w,o(w);try{await((M=e==null?void 0:e.onAddressChange)==null?void 0:M.call(e,w))}catch(O){(P=e==null?void 0:e.onError)==null||P.call(e,O instanceof Error?O:new Error("ETH address change failed"),{address:w})}finally{p.current=!1}}else!w&&x&&a()};return typeof c.on=="function"&&c.on("accountsChanged",m),()=>{typeof c.off=="function"&&c.off("accountsChanged",m)}},[c,e,a]);const C=h.useCallback(async()=>{var m;if(c)try{const N=await c.getAddress();N?N.toLowerCase()!==(r==null?void 0:r.toLowerCase())&&(f.current=N,o(N),await((m=e==null?void 0:e.onAddressChange)==null?void 0:m.call(e,N))):a()}catch(N){console.error("ETH wallet connection check failed:",N instanceof Error?N.message:"Unknown error"),a()}},[c,r,e,a]);jt(C,{enabled:!!(c&&r)});const y=h.useMemo(()=>!!r,[r]);return E.jsx(Mt.Provider,{value:{loading:n,connected:y,address:r,disconnect:()=>g("ETH"),open:d},children:t})},Ii=()=>h.useContext(Mt);exports.ACCOUNT_CHANGE_EVENTS=ht;exports.APPKIT_BTC_CONNECTOR_ID=vt;exports.APPKIT_ETH_CONNECTOR_ID=Ke;exports.APPKIT_OPEN_EVENT=de;exports.COSMOS_KEYSTORE_CHANGE_EVENTS=Xt;exports.ChainProvider=pn;exports.DISCONNECT_EVENT=Be;exports.ERROR_CODES=re;exports.ETHWalletProvider=Ci;exports.LifeCycleHooksProvider=gn;exports.MONOCHROME_MARK_BACKGROUND=_t;exports.NETWORK_CHANGE_EVENT=Me;exports.Network=U;exports.ONEKEY_BRAND_GREEN=Cn;exports.ONE_HOUR=qt;exports.StateContext=Fe;exports.StateProvider=wt;exports.WalletDialog=mi;exports.WalletError=oe;exports.assertAppKitCapabilities=bt;exports.createAccountStorage=mn;exports.createAppKitCapabilities=Rt;exports.createETHWagmiAdapter=Pt;exports.createExternalWallet=Et;exports.failInitialization=H;exports.getAppKitState=Re;exports.getSharedWagmiConfig=ke;exports.hasSharedWagmiConfig=Te;exports.initializeAppKitModal=Pn;exports.isAccountChangeEvent=Yt;exports.isSharedSessionRefusal=le;exports.isUserRejectionMessage=Jt;exports.metadata=Dn;exports.okxLogo=yt;exports.process$1=ft;exports.registerManualAppKitConfig=xt;exports.removeProviderListener=Zt;exports.setAppKitState=Lt;exports.setSharedWagmiConfig=yn;exports.trackProviderIdentityChanges=$t;exports.useAppKitOpenListener=Wn;exports.useChainConnector=Wt;exports.useETHWallet=Ii;exports.useInscriptionProvider=an;exports.useVisibilityCheck=jt;exports.useWalletConnect=Ue;exports.useWidgetState=J;exports.validateAppKitInitialization=Ot;
|
|
2
|
-
//# sourceMappingURL=ETHWalletProvider-
|
|
1
|
+
"use strict";var Kt=Object.defineProperty;var Ft=(t,e,n)=>e in t?Kt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>Ft(t,typeof e!="symbol"?e+"":e,n);const Oe=require("viem"),W=require("wagmi/actions"),ct=require("wagmi/connectors"),kt=require("@reown/appkit-adapter-wagmi"),Ve=require("@reown/appkit/react"),Ye=require("wagmi"),h=require("react"),p=require("react/jsx-runtime"),L=require("@babylonlabs-io/core-ui"),Y=require("tailwind-merge");function Ut(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var at={exports:{}},D=at.exports={},G,z;function Le(){throw new Error("setTimeout has not been defined")}function be(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?G=setTimeout:G=Le}catch{G=Le}try{typeof clearTimeout=="function"?z=clearTimeout:z=be}catch{z=be}})();function dt(t){if(G===setTimeout)return setTimeout(t,0);if((G===Le||!G)&&setTimeout)return G=setTimeout,setTimeout(t,0);try{return G(t,0)}catch{try{return G.call(null,t,0)}catch{return G.call(this,t,0)}}}function Gt(t){if(z===clearTimeout)return clearTimeout(t);if((z===be||!z)&&clearTimeout)return z=clearTimeout,clearTimeout(t);try{return z(t)}catch{try{return z.call(null,t)}catch{return z.call(this,t)}}}var $=[],ne=!1,q,Ne=-1;function zt(){!ne||!q||(ne=!1,q.length?$=q.concat($):Ne=-1,$.length&<())}function lt(){if(!ne){var t=dt(zt);ne=!0;for(var e=$.length;e;){for(q=$,$=[];++Ne<e;)q&&q[Ne].run();Ne=-1,e=$.length}q=null,ne=!1,Gt(t)}}D.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];$.push(new ut(t,e)),$.length===1&&!ne&&dt(lt)};function ut(t,e){this.fun=t,this.array=e}ut.prototype.run=function(){this.fun.apply(null,this.array)};D.title="browser";D.browser=!0;D.env={};D.argv=[];D.version="";D.versions={};function Z(){}D.on=Z;D.addListener=Z;D.once=Z;D.off=Z;D.removeListener=Z;D.removeAllListeners=Z;D.emit=Z;D.prependListener=Z;D.prependOnceListener=Z;D.listeners=function(t){return[]};D.binding=function(t){throw new Error("process.binding is not supported")};D.cwd=function(){return"/"};D.chdir=function(t){throw new Error("process.chdir is not supported")};D.umask=function(){return 0};var Vt=at.exports;const ft=Ut(Vt),ht=["accountChanged","accountsChanged"];function Yt(t){return ht.includes(t)}const Me="networkChanged",Be="disconnect";function $t(t,e){if(typeof t.on!="function")return!1;try{t.on("accountsChanged",e)}catch{return!1}return[Me,Be].forEach(n=>{var i;try{(i=t.on)==null||i.call(t,n,e)}catch{}}),!0}const De="babylon-wallet#modal-open",Xt=["keplr_keystorechange","leap_keystorechange","okx_keystorechange"];function Zt(t,e,n){typeof t.removeListener=="function"?t.removeListener(e,n):typeof t.off=="function"&&t.off(e,n)}const qt=3600*1e3;class ye{constructor({id:e,origin:n,name:i,icon:r,iconBackground:o,docs:c,networks:s,provider:d,label:g,hardware:u}){b(this,"id");b(this,"origin");b(this,"name");b(this,"icon");b(this,"iconBackground");b(this,"docs");b(this,"networks");b(this,"provider",null);b(this,"hardware");b(this,"_label");b(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=d,this._label=g,this.hardware=u??!1}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 ye({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 Qt=()=>({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 re={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",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",INSCRIPTIONS_UNSUPPORTED_NETWORK:"INSCRIPTIONS_UNSUPPORTED_NETWORK",INSCRIPTION_FETCH_ERROR:"INSCRIPTION_FETCH_ERROR"};class oe extends Error{constructor({code:n,message:i,wallet:r,version:o,chainId:c},s){super(i,s);b(this,"code");b(this,"wallet");b(this,"version");b(this,"chainId");this.code=n,this.wallet=r,this.version=o,this.chainId=c}}function Jt(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 le(t){return t instanceof oe&&t.code===re.SHARED_SESSION_DISCONNECT_REFUSED}class He{constructor(e,n,i,r,o){b(this,"_connectedWallet",null);b(this,"_connectionGeneration",0);b(this,"_ee",Qt());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 oe({code:re.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"&&le(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 He(this.id,this.name,this.icon,this.wallets,this.config)}on(e,n){return this._ee.on(e,n)}}var U=(t=>(t.MAINNET="mainnet",t.TESTNET="testnet",t.SIGNET="signet",t))(U||{});const en=t=>e=>e[t],tn=async({metadata:t,context:e,config:n})=>{const{id:i,wallet:r,name:o,icon:c,iconBackground:s,docs:d="",networks:g=[],createProvider:u,label:a,hardware:l}=t,f={id:i,name:"",icon:"",iconBackground:s,origin:null,provider:null,docs:d,networks:g,label:a,hardware:l};if(r){const E=typeof r=="string"?en(r):r;f.origin=await E(e,n)??null,f.provider=f.origin?u(f.origin,n):null}else f.origin=null,f.provider=u(null,n);return typeof o=="string"?f.name=o??"":f.name=f.origin?await o(f.origin,n):"",typeof c=="string"?f.icon=c??"":f.icon=f.origin?await c(f.origin,n):"",new ye(f)},Et=({id:t,name:e,icon:n,provider:i})=>new ye({id:t,origin:null,name:e,icon:n,docs:"",networks:[U.MAINNET,U.SIGNET],provider:i}),pt=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 l of e.wallets)o!=null&&o.includes(l.id)||c.push(await tn({metadata:l,context:n,config:i}));const d=c.find(l=>l.id==="injectable"&&l.installed),g=c.filter(l=>l.name.toLowerCase()!==(d==null?void 0:d.name.toLowerCase())||l.id==="injectable"),u=new He(e.chain,e.name,e.icon,g,i);return e.chain!=="ETH"&&s&&c.some(l=>l.id===s&&l.installed)&&u.connect(s).catch(l=>{console.error("Auto-reconnect failed:",l instanceof Error?l.message:"Unknown error")}),u};function nn({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(d=>d.id===s&&d.installed)&&o.push({connector:c,walletId:s})}return o}const $e="unisat#initialized",rn=3e3;function on({connectors:t,setConnectors:e,config:n,context:i,storage:r,disabledWallets:o,persistent:c,metadata:s}){const d=h.useRef(t);d.current=t;const g=Object.values(t).some(Boolean);h.useEffect(()=>{if(!g)return;let u=!1,a=!1;const l=new Set,f=new Set,E=async x=>{if(!(u||a)){u=!0;try{await C(x)}finally{u=!1}}},C=async x=>{const M=Object.values(d.current).filter(Boolean).filter(R=>!!s[R.id]&&!R.connectedWallet&&R.wallets.some(K=>K.id!=="injectable"&&!K.installed));let P=[];if(M.length>0){const R=await Promise.all(M.map(_=>{var T;return pt({persistent:!1,metadata:s[_.id],context:i,config:(T=n.find(I=>I.chain===_.id))==null?void 0:T.config,accountStorage:r,disabledWallets:o}).catch(()=>null)}));if(a)return;const K=R.filter(_=>{if(!_)return!1;const T=d.current[_.id];if(!T||T.connectedWallet)return!1;const I=new Set(T.wallets.filter(A=>A.installed).map(A=>A.id));return _.wallets.some(A=>A.installed&&!I.has(A.id))});for(const _ of K)f.add(_.id);const v=d.current;P=K.filter(_=>{var T;return!((T=v[_.id])!=null&&T.connectedWallet)}),P.length>0&&e(_=>{var I;const T={};for(const A of P)(I=_[A.id])!=null&&I.connectedWallet||(T[A.id]=A);return Object.keys(T).length>0?{..._,...T}:_})}if(!x||!c||f.size===0)return;const O={};for(const R of Object.values(d.current))R&&(O[R.id]=R);for(const R of P)O[R.id]=R;const S=nn({connectors:Object.values(O),storage:r,allowReconnect:x,persistent:c,eligibleChainIds:f});for(const{connector:R,walletId:K}of S)l.has(R.id)||(l.add(R.id),R.connect(K).then(v=>{l.delete(R.id),v&&f.delete(R.id)}).catch(()=>l.delete(R.id)))},y=()=>void E(!0),m=()=>void E(!1),N=setTimeout(y,rn),w=typeof window<"u";return w&&(window.addEventListener($e,y,{once:!0}),window.addEventListener(De,m)),()=>{a=!0,clearTimeout(N),w&&(window.removeEventListener($e,y),window.removeEventListener(De,m))}},[g,n,i,r,o,e,c,s])}function sn(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 gt=h.createContext({lockInscriptions:!0});function cn({children:t,context:e}){const[n,i]=sn("bwc-inscription-modal-lock",e.localStorage,!0),r=h.useMemo(()=>({lockInscriptions:n,toggleLockInscriptions:i}),[n,i]);return p.jsx(gt.Provider,{value:r,children:t})}const an=()=>h.useContext(gt),V="__babylon-wallet-confirmation-v1__",mt=2,dn={BTC:["accountsChanged",Me,Be],BBN:["accountChanged"],ETH:["accountsChanged","chainChanged"]};function ue(t,e){return t[e]}function ve(t,e,n){var o;const i=(o=ue(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 Q(t,e){return t.toLowerCase()===e.toLowerCase()}function ln(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 fe(t){if(t)try{const e=JSON.parse(t);return(e==null?void 0:e.version)!==mt||!Array.isArray(e.entries)||!e.entries.every(ln)?void 0:e}catch{return}}function ce(t,e,n){const i=t.filter(r=>r.account&&ue(e,r.chain)).map(r=>({chain:r.chain,walletId:r.wallet.id,address:r.account.address,publicKeyHex:r.account.publicKeyHex,network:ve(e,r.chain,n)})).sort((r,o)=>r.chain.localeCompare(o.chain));return JSON.stringify({version:mt,entries:i})}function un(t,e,n){var r;const i=(r=fe(t))==null?void 0:r.entries;return i?e.every(o=>{var u;const c=o,s=(u=ue(n,c))==null?void 0:u.connectedWallet,d=s==null?void 0:s.account,g=i.find(a=>a.chain===c);return!!(s&&d&&g&&g.walletId===s.id&&Q(g.address,d.address)&&Q(g.publicKeyHex,d.publicKeyHex)&&g.network===ve(n,c))}):!1}function fn(t,e,n){var r;const i=(r=fe(t))==null?void 0:r.entries;return i?e.every(o=>{var g;const c=o,s=(g=ue(n,c))==null?void 0:g.connectedWallet,d=i.find(u=>u.chain===c);return!!(s&&d&&d.walletId===s.id&&d.network===ve(n,c))}):!1}async function hn(t,e,n){var o;const i=(o=fe(t))==null?void 0:o.entries;return i?(await Promise.all(e.map(async c=>{var l,f;const s=c,d=ue(n,s),g=d==null?void 0:d.connectedWallet,u=g==null?void 0:g.provider,a=i.find(E=>E.chain===s);if(!g||!u||!a||a.walletId!==g.id)return!1;try{if(((l=u.isIdentityCurrent)==null?void 0:l.call(u))===!1)return!1;const[E,C,y]=await Promise.all([u.getAddress(),u.getPublicKeyHex(),s==="ETH"?u.getChainId():s==="BTC"?u.getNetwork():ve(n,s)]);return((f=u.isIdentityCurrent)==null?void 0:f.call(u))===!1?!1:Q(a.address,E)&&Q(a.publicKeyHex,C)&&a.network===String(y)}catch{return!1}}))).every(Boolean):!1}function Ct(t,e,n,i){var c;const r=(c=fe(t))==null?void 0:c.entries;if(!r)return()=>{};const o=[];return e.forEach(s=>{var u,a,l;const d=s,g=(a=(u=n[d])==null?void 0:u.connectedWallet)==null?void 0:a.provider;g!=null&&g.on&&((l=dn[d])==null||l.forEach(f=>{var C;const E=(...y)=>{const m=y[0],N=r.find(w=>w.chain===d);d==="ETH"&&f==="accountsChanged"&&Array.isArray(m)&&m.length===1&&typeof m[0]=="string"&&N&&Q(N.address,m[0])||i(d)};try{(C=g.on)==null||C.call(g,f,E),o.push({event:f,handler:E,provider:g})}catch{}}))}),()=>{o.forEach(({event:s,handler:d,provider:g})=>{var u;try{(u=g.off)==null||u.call(g,s,d)}catch{}})}}function It(t){var e;return((e=fe(t))==null?void 0:e.entries.map(n=>n.chain))??[]}const Pe={confirmed:!1,visible:!1,screen:{type:"CHAINS"},chains:{},selectedWallets:{},requiredChainIds:[]},Ke=h.createContext(Pe);function En(t,e){return Object.keys(t).reduce((n,i)=>(e.has(i)&&(n[i]=t[i]),n),{})}function wt({children:t,chains:e,requiredChainIds:n,storage:i}){const[r,o]=h.useState(()=>({...Pe,chains:e.reduce((a,l)=>({...a,[l.id]:l}),{}),requiredChainIds:[...n]})),c=n.some(a=>!r.requiredChainIds.includes(a)),s=h.useMemo(()=>({...r,confirmed:c?!1:r.confirmed,requiredChainIds:[...n]}),[n,c,r]),d=h.useRef(n);h.useInsertionEffect(()=>{d.current=n},[n]),h.useEffect(()=>{o(a=>{const l=e.reduce((y,m)=>({...y,[m.id]:m}),{}),f=new Set(e.map(y=>y.id)),E=En(a.selectedWallets,f),C=n.some(y=>!a.requiredChainIds.includes(y));return{...a,confirmed:C?!1:a.confirmed,chains:l,selectedWallets:E,requiredChainIds:[...n]}})},[e,n]);const g=h.useMemo(()=>({open:()=>{typeof window<"u"&&window.dispatchEvent(new Event(De)),o(a=>({...a,visible:!0}))},close:()=>{o(a=>({...a,visible:!1}))},reset:()=>{i==null||i.delete(V),o(({chains:a,requiredChainIds:l})=>({...Pe,chains:a,requiredChainIds:l}))},displayLoader:(a="",l="")=>{o(f=>({...f,screen:{type:"LOADER",params:{message:a,description:l}}}))},displayChains:()=>{o(a=>({...a,screen:{type:"CHAINS"}}))},displayWallets:a=>{o(l=>({...l,screen:{type:"WALLETS",params:{chain:a}}}))},displayError:a=>{o(l=>({...l,screen:{type:"ERROR",params:a}}))},selectWallet:(a,l)=>{o(f=>({...f,selectedWallets:{...f.selectedWallets,[a]:l}}))},removeWallet:a=>{const l=d.current.includes(a);l&&(i==null||i.delete(V)),o(f=>({...f,confirmed:l?!1:f.confirmed,confirmationReceipt:l?void 0:f.confirmationReceipt,selectedWallets:{...f.selectedWallets,[a]:void 0}}))},confirm:a=>{o(l=>({...l,confirmed:!0,confirmationReceipt:a}))},unconfirm:(a=!1)=>{o(l=>({...l,confirmed:!1,confirmationReceipt:a?l.confirmationReceipt:void 0}))}}),[i]),u=h.useMemo(()=>({...s,...g}),[s,g]);return p.jsx(Ke.Provider,{value:u,children:t})}const We={BTC:null,BBN:null,ETH:null},Nt=h.createContext(We);function pn({persistent:t,storage:e,children:n,context:i,config:r,onError:o,disabledWallets:c,requiredChains:s,metadata:d}){const[g,u]=h.useState(We),a=h.useCallback(async()=>{const C=r.filter(m=>d[m.chain]).map(async({chain:m,config:N})=>{const w=d[m];if(!w)return null;try{return await pt({persistent:t,metadata:w,context:i,config:N,accountStorage:e,disabledWallets:c})}catch(x){throw console.error("[ChainProvider] failed to create connector for chain:",m,x instanceof Error?x.message:"Unknown error"),x}});return(await Promise.all(C)).reduce((m,N)=>N?{...m,[N.id]:N}:m,{...We})},[t,r,i,e,c,d]);h.useEffect(()=>{a().then(E=>{u(E)}).catch(E=>{console.error("[ChainProvider] init failed with error:",E instanceof Error?E.message:"Unknown error"),o==null||o(E)})},[u,a,o]),on({connectors:g,setConnectors:u,config:r,context:i,storage:e,disabledWallets:c,persistent:t,metadata:d}),h.useEffect(()=>{const E=Object.values(g).filter(Boolean);if(E.length===0)return;const C=()=>u(m=>({...m})),y=E.flatMap(m=>[m.on("connect",C),m.on("disconnect",C)]);return()=>y.forEach(m=>m())},[g]);const l=h.useMemo(()=>Object.values(g).filter(E=>!!E),[g]),f=h.useMemo(()=>s===void 0?r.filter(E=>d[E.chain]).map(E=>E.chain):[...s],[r,d,s]);return p.jsx(cn,{context:i,children:p.jsx(wt,{chains:l,requiredChainIds:f,storage:e,children:p.jsx(Nt.Provider,{value:g,children:n})})})}const he=()=>h.useContext(Nt),Tt=h.createContext({});function gn({children:t,value:e}){const n=h.useMemo(()=>e??{},[e]);return p.jsx(Tt.Provider,{value:n,children:t})}const At=()=>h.useContext(Tt),ae="baby-connected-wallet-accounts";function Ie(t,e){const n=e==null?void 0:e[t];return n?`${t}:${n}`:t}function we(){const t=localStorage.getItem(ae);if(!t)return{};try{const e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?(localStorage.removeItem(ae),{}):e}catch(e){return console.error("[account-storage] Failed to parse accounts map, clearing corrupted entry:",e),localStorage.removeItem(ae),{}}}function Xe(t){try{localStorage.setItem(ae,JSON.stringify(t))}catch(e){console.error("[account-storage] Failed to write accounts map, clearing entry:",e),localStorage.removeItem(ae)}}const mn=(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 d=Date.now();return s<0||s>d+t?!0:d-s>t}return{get:r=>{const o=we(),c=Ie(r,e);if(!i(o,c))return o[c]},has:r=>{const o=we(),c=Ie(r,e);return i(o,c)?!1:!!o[c]},set:(r,o)=>{const c=we(),s=Ie(r,e),d=n(c);c[s]=o,c._timestamps={...d,[s]:Date.now()},Xe(c)},delete:r=>{const o=we(),c=Ie(r,e),s=n(o),d=Reflect.deleteProperty(o,c);return delete s[c],o._timestamps=s,Xe(o),d}}},_t="#000000",Cn="#1FE121",yt="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",de="babylon:open-appkit",Fe="appkit-eth-connector",vt="appkit-btc-connector",Ze="bigint",qe="function",In="AppKit configuration cannot be serialized.",wn=1,Qe=new WeakMap;let Nn=wn;function Tn(t){const e=Qe.get(t);if(e)return e;const n=Nn++;return Qe.set(t,n),n}function Je(t){const e=JSON.stringify(t,(n,i)=>typeof i===Ze?{type:Ze,value:i.toString()}:typeof i===qe?{type:qe,value:Tn(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(In);return e}function Rt({projectId:t,metadata:e,ethChain:n,btcNetwork:i}){return Object.freeze({projectId:t,metadataFingerprint:Je(e),ethFingerprint:n?Je(n):void 0,btcNetwork:i})}let X=null,St=null;const Ae=new Set;function H(t,e){throw new oe({code:re.WALLET_INITIALIZATION_FAILED,message:t,chainId:e})}function Re(){return X}function _e(){return(X==null?void 0:X.modal)??St}function xt(t,e){X&&H(`Cannot set a manual ${t} AppKit configuration after AppKit initialization. Use the canonical AppKit state.`),Ae.add(t),e&&(St=e)}function Ot(t){return t?(Ae.size>0&&H(`Cannot initialize AppKit after a manual ${[...Ae].join(" and ")} configuration was set. Use only one initialization method.`),!0):(X&&H("AppKit is already initialized. A project ID is required to validate the requested configuration."),!1)}function Lt(t){return X&&H("AppKit is already initialized. Reuse the shared AppKit state instead of replacing it."),Ae.size>0&&H("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&&H("AppKit was already initialized with a different project ID. A page can use only one AppKit configuration."),t.metadataFingerprint!==e.metadataFingerprint&&H("AppKit was already initialized with different metadata. A page can use only one AppKit configuration."),e.ethFingerprint&&(t.ethFingerprint||H("AppKit was already initialized without Ethereum support. A page that needs Ethereum must initialize AppKit with Ethereum first.","ETH"),t.ethFingerprint!==e.ethFingerprint&&H("AppKit was already initialized with a different Ethereum chain configuration.","ETH")),e.btcNetwork&&(t.btcNetwork||H("AppKit was already initialized without Bitcoin support. A page that needs Bitcoin must initialize AppKit with Bitcoin first.","BTC"),t.btcNetwork!==e.btcNetwork&&H("AppKit was already initialized with a different Bitcoin network.","BTC"))}const An="Ethereum",_n="Shared wagmi config is being replaced. This might indicate multiple initializations.";let ie=null;function yn(t){xt(An),ie&&ie!==t&&console.warn(_n),ie=t}function ke(){const t=Re();if(t)return t.wagmiConfig||H("AppKit was initialized without Ethereum support. Initialize it with Ethereum support.","ETH"),t.wagmiConfig;if(!ie)throw new Error("Shared wagmi config not initialized. Initialize AppKit with Ethereum support, or use setSharedWagmiConfig() as an exclusive manual alternative.");return ie}function Te(){const t=Re();return t?t.wagmiConfig!==void 0:ie!==null}function Dt(){var n;const t=_e();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 vn=1500,et="Wallet not connected",Rn="Ethereum Wallet",Sn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=";class xn{constructor(e){b(this,"config");b(this,"address");b(this,"chainId");b(this,"eventHandlers",new Map);b(this,"unwatchFunctions",[]);this.config=e,this.ensureEventWatchers()}ensureEventWatchers(){this.unwatchFunctions.length>0||Te()&&this.setupEventWatchers()}getWagmiConfig(){if(!Te())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 ke()}setupEventWatchers(){const e=this.getWagmiConfig(),n=W.getAccount(e);n.address&&n.status==="connected"&&(this.address=n.address,this.chainId=n.chainId,setTimeout(()=>{this.emit("accountsChanged",[n.address])},100));const i=W.watchAccount(e,{onChange:o=>{const c=this.address;this.address=o.address,this.chainId=o.chainId,c!==o.address&&this.emit("accountsChanged",o.address?[o.address]:[])}}),r=W.watchChainId(e,{onChange:o=>{const c=this.chainId;this.chainId=o,c!==o&&this.emit("chainChanged",`0x${o.toString(16)}`)}});this.unwatchFunctions.push(i,r)}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=W.getAccount(e);if(n.address){this.address=n.address,this.chainId=n.chainId;return}if(typeof window<"u"){await new Promise((s,d)=>{let g=!1,u;const a=()=>{clearTimeout(l),u&&clearTimeout(u),f(),C==null||C()},l=setTimeout(()=>{a(),d(new Error("Connection timeout"))},6e4),f=W.watchAccount(e,{onChange:y=>{y.address&&(this.address=y.address,this.chainId=y.chainId,a(),s())}}),E=_e(),C=E==null?void 0:E.subscribeState(y=>{if(y.open)g=!0,u&&(clearTimeout(u),u=void 0);else if(g){const m=W.getAccount(e);if(m.address){this.address=m.address,this.chainId=m.chainId,a(),s();return}u=setTimeout(()=>{const N=W.getAccount(e);N.address?(this.address=N.address,this.chainId=N.chainId,a(),s()):(a(),d(new Error("Connection cancelled")))},vn)}});window.dispatchEvent(new CustomEvent(de))});return}const i=ft.env.NEXT_PUBLIC_REOWN_PROJECT_ID;if(!i)throw new Error("NEXT_PUBLIC_REOWN_PROJECT_ID environment variable is required");const r=ct.walletConnect({projectId:i,metadata:{name:"Babylon Vault",description:"",url:"",icons:[""]}}),o=await W.connect(e,{connector:r});this.address=o.accounts[0],this.chainId=o.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"&&Dt())throw new oe({code:re.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 W.disconnect(this.getWagmiConfig()),this.address=void 0,this.chainId=void 0}async getAddress(){const e=this.getWagmiConfig(),n=W.getAccount(e);if(n.address)return this.address=n.address,this.chainId=n.chainId,this.address;if(this.address)return this.address;throw new Error(et)}async getPublicKeyHex(){return this.getAddress()}async signMessage(e){try{const n=this.getWagmiConfig(),i=await this.getAddress();return await W.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 W.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 W.sendTransaction(n,{account:i,to:e.to,value:e.value?Oe.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 W.estimateGas(n,{account:i,to:e.to,value:e.value?Oe.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=W.getAccount(e);if(n.chainId)return this.chainId=n.chainId,this.chainId;throw new Error(et)}async switchChain(e){try{const n=this.getWagmiConfig();if(![1,11155111,31337].includes(e))throw new Error(`Unsupported chain ID: ${e}`);await W.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 W.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 W.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=_e())==null?void 0:n.getWalletInfo("eip155");if(e!=null&&e.name||e!=null&&e.icon)return{name:e.name,icon:e.icon};if(Te())try{const{connector:i}=W.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:Rn}getWalletProviderIcon(){var n;const e=(n=this.getActiveConnectorIdentity())==null?void 0:n.icon;return e!=null&&e.trim()?e:Sn}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 On="AppKit",Ln={id:Fe,name:On,icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=",docs:"https://docs.reown.com/appkit/overview",wallet:void 0,createProvider:(t,e)=>new xn(e),networks:[U.MAINNET,U.TESTNET,U.SIGNET],label:"Connect ETH Wallet"},bn="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",Dn={chain:"ETH",name:"Ethereum",icon:bn,wallets:[Ln]};function Pt(t,e){const n=t.rpcUrls.default.http[0];return new kt.WagmiAdapter({networks:[t],projectId:e,ssr:!1,storage:Ye.createStorage({storage:Ye.cookieStorage}),connectors:[ct.baseAccount({preference:{telemetry:!1}})],transports:{[t.id]:Oe.http(n)}})}function Pn(t){if(!Ot(t.projectId))return null;const{chain:e}=t.eth,n=Rt({projectId:t.projectId,metadata:t.metadata,ethChain:e}),i=Re();if(i)return bt(i,n),{modal:i.modal,wagmiConfig:ke()};Ve.modal&&H("Reown AppKit was initialized outside this package. Use only this package to initialize it.");const r=Pt(e,t.projectId),o=Ve.createAppKit({adapters:[r],networks:[e],projectId:t.projectId,metadata:t.metadata});return{modal:Lt({modal:o,...n,wagmiConfig:r.wagmiConfig}).modal,wagmiConfig:r.wagmiConfig}}const Wn=()=>{h.useEffect(()=>{const t=()=>{try{const e=_e();e&&e.open()}catch(e){console.warn("AppKit modal not available:",e)}};return window.addEventListener(de,t),()=>window.removeEventListener(de,t)},[])};function Wt(t){const e=he();return(e==null?void 0:e[t])??null}const jn=[{match:/okx/i,icon:yt,iconBackground:_t}];function Mn(t){return jn.find(({match:e})=>e.test(t))}const J=()=>h.useContext(Ke);async function tt(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=Mn(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 Bn=new Set([re.INCOMPATIBLE_WALLET_VERSION]);function Hn({persistent:t,accountStorage:e,onError:n,btcValidation:i}){const r=he(),{confirmed:o,confirmationReceipt:c,visible:s,selectWallet:d,removeWallet:g,displayLoader:u,displayChains:a,displayError:l,confirm:f,unconfirm:E,requiredChainIds:C=[]}=J(),{verifyBTCAddress:y}=At(),m=h.useRef(0),N=h.useRef(C),w=c??(t&&!s?e.get(V):void 0),x=h.useRef(),M=h.useRef(new Set),P=C.every(v=>{var _;return(_=r[v])==null?void 0:_.connectedWallet}),O=h.useRef(new Set),S=async v=>{O.current.add(v.id),g==null||g(v.id),t&&e.delete(v.id);try{await v.disconnect("chain")}catch(_){le(_)||console.error("Failed to disconnect rejected wallet:",_ instanceof Error?_.message:"Unknown error"),await v.disconnect("local")}finally{O.current.delete(v.id)}};h.useEffect(()=>{if(!s)return;const _=Object.values(r).filter(Boolean).map(T=>T.on("connecting",(I,A)=>{u==null||u(I,A)}));return()=>_.forEach(T=>T())},[s,u,r]),h.useEffect(()=>{const v=Object.values(r).filter(Boolean),_={BTC:I=>async A=>{var F,Ee,j,B;try{if(!A||!A.account)return;if(!i)throw new Error("Bitcoin address validation is unavailable");if(d==null||d("BTC",A),t&&((F=A.account)!=null&&F.address)&&e.set(I.id,A.id),!s)return;i.validateAddress(I.config.network,A.account.address);const k=()=>void(a==null?void 0:a());if(!i.validateAddressWithPK(((Ee=A.account)==null?void 0:Ee.address)??"",((j=A.account)==null?void 0:j.publicKeyHex)??"",I.config.network)){l==null||l({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:k,onCancel:()=>{S(I),a==null||a()}});return}if(y&&!await y(((B=A.account)==null?void 0:B.address)??"")){l==null||l({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(I),a==null||a()}});return}k()}catch(k){S(I),l==null||l({title:"Connection Failed",description:k.message,submitButton:"",cancelButton:"Done",onCancel:async()=>{a==null||a()}})}},BBN:I=>A=>{var F;A&&(d==null||d(I.id,A),t&&((F=A.account)!=null&&F.address)&&e.set(I.id,A.id)),a==null||a()},ETH:I=>async A=>{var F;A&&(d==null||d(I.id,await tt(A)),t&&((F=A.account)!=null&&F.address)&&e.set(I.id,A.id)),a==null||a()}},T=v.map(I=>{var A;return I.on("connect",(A=_[I.id])==null?void 0:A.call(_,I))});return v.forEach(I=>{const A=O.current.has(I.id)?null:I.connectedWallet;if(I.id==="ETH"&&A){tt(A).then(F=>d==null?void 0:d(I.id,F));return}d==null||d(I.id,A)}),()=>T.forEach(I=>I())},[n,d,g,a,l,y,i,e,r,t,s]),h.useLayoutEffect(()=>{const _=Object.values(r).filter(Boolean).map(T=>T.on("disconnect",I=>{I&&(C.includes(T.id)&&(m.current+=1,e.delete(V)),g==null||g(T.id),a==null||a(),t&&e.delete(T.id))}));return()=>_.forEach(T=>T())},[g,a,r,t,e,C]),h.useEffect(()=>{const _=Object.values(r).filter(Boolean).map(T=>T.on("error",I=>{if(n==null||n(I),I instanceof oe&&Bn.has(I.code)&&l){const A=I.wallet??"your wallet";l({title:`Update ${A}`,description:I.message||`${A} needs to be updated before you can connect.`,submitButton:"",cancelButton:"Done",onCancel:()=>{a==null||a()}});return}a==null||a()}));return()=>_.forEach(T=>T())},[n,a,l,r]);const R=h.useCallback(async()=>{const v=++m.current;if(!w||!c&&!P)return;const _=await hn(w,C,r);if(v===m.current){if(!_){e.delete(V),E==null||E();return}if(!o&&!s){f==null||f(w),a==null||a();return}t&&o&&e.set(V,w)}},[e,w,c,o,f,r,a,t,C,P,E,s]);return h.useEffect(()=>{R()},[R]),h.useLayoutEffect(()=>{const v=x.current;(!w||v&&v!==w)&&M.current.clear(),x.current=w},[w]),h.useLayoutEffect(()=>{m.current+=1;const v=C.filter(T=>!N.current.includes(T));if(N.current=C,!w)return;const _=Ct(w,It(w),r,T=>{if(!C.includes(T)){M.current.add(T);return}m.current+=1,e.delete(V),E==null||E()});if(!c&&!P)return _;if(!fn(w,C,r)||v.some(T=>M.current.has(T))||c&&v.length>0&&!un(w,v,r)){_(),e.delete(V),E==null||E();return}return c&&v.length>0&&(E==null||E(!0)),_},[e,w,c,r,C,P,E]),h.useEffect(()=>()=>{m.current+=1},[]),{connect:h.useCallback(async(v,_)=>{const T=r[v.id];await(T==null?void 0:T.connect(_.id))},[r])}}function Kn(t,e,n){const i=h.useCallback((r,o)=>p.jsx(p.Fragment,{children:o.map(({id:c,widget:s})=>p.jsx(s,{id:c,connector:t[r],createWallet:Et,onError:n},c))}),[t,n]);return h.useMemo(()=>e.reduce((r,o)=>({...r,[o.chain]:i(o.chain,o.connectors??[])}),{}),[i,e])}function Ue(){const{confirmed:t,chains:e,requiredChainIds:n,selectedWallets:i,open:r,displayChains:o,displayError:c,displayWallets:s,reset:d}=J(),g=he(),u=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(g,f)){try{await((E=g[f])==null?void 0:E.disconnect("chain"))}catch(C){throw le(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(g))C&&await C.disconnect("all");d==null||d()},[g,o,c,d]),l=h.useMemo(()=>n.every(f=>!!i[f]),[n,i]);return{selected:l,connected:l&&t,open:u,disconnect:a}}function Fn({className:t,alt:e,logo:n,title:i,children:r,onClick:o}){const c=typeof n=="string"?p.jsx(L.Avatar,{url:n,alt:e}):p.jsx(L.Avatar,{children:n}),s=()=>{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 p.jsxs(L.Text,{as:"button",className:Y.twMerge("flex w-full cursor-pointer flex-col gap-4 rounded-lg bg-neutral-200 p-4 text-accent-primary",t),onClick:o,"data-testid":s(),children:[p.jsxs("div",{className:"flex w-full items-center gap-2.5",children:[p.jsx("div",{className:"flex items-center",children:c}),i,p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",className:"ml-auto block text-accent-secondary",children:p.jsx("path",{d:"M8.58984 16.59L13.1698 12L8.58984 7.41L9.99984 6L15.9998 12L9.99984 18L8.58984 16.59Z",fill:"currentColor"})})]}),r&&p.jsx("div",{className:"w-full",children:r})]})}const kn=36,nt=14;function Un(t){return t.length<=kn?t:`${t.slice(0,nt)}…${t.slice(-nt)}`}const Gn=h.memo(({className:t,logo:e,logoBackground:n,address:i})=>{const{isCopied:r,copyToClipboard:o}=L.useCopy(),c=r(i),s=d=>{d.stopPropagation(),o(i,i)};return p.jsxs("div",{className:Y.twMerge("flex items-center gap-2.5 rounded-lg bg-neutral-200 p-2",t),children:[p.jsx(L.WalletIcon,{size:"small",className:"shrink-0",url:e,background:n}),p.jsx(L.Text,{as:"div",variant:"caption",title:i,className:"min-w-0 flex-1 truncate text-left font-mono text-accent-secondary",children:Un(i)}),p.jsx("span",{role:"button",tabIndex:0,"aria-label":c?"Address copied":"Copy address",onClick:s,onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&s(d)},className:"flex shrink-0 cursor-pointer items-center text-accent-secondary hover:text-accent-primary",children:c?p.jsx(L.CheckIcon,{size:16,variant:"success"}):p.jsx(L.CopyIcon,{size:16})})]})}),zn="disabled:!bg-[#CCCCCC] dark:disabled:!bg-secondary-strokeDark",Vn="Select ",Yn=" Wallet",$n=" (Optional)",Xn=h.memo(({disabled:t=!1,chains:e,requiredChainIds:n,selectedWallets:i={},className:r,onConfirm:o,onSelectChain:c})=>p.jsxs("div",{className:Y.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight text-accent-primary",r),children:[p.jsx("div",{className:"border-b border-secondary-strokeLight p-6",children:p.jsx(L.Heading,{variant:"h5",className:"text-accent-primary",children:"Connect Wallets"})}),p.jsxs("div",{className:"flex flex-col gap-4 p-6",children:[p.jsxs("div",{className:"flex flex-col gap-2",children:[e.map(s=>{var u;const d=i[s.id],g=n!==void 0&&!n.includes(s.id);return p.jsx(Fn,{title:`${Vn}${s.name}${Yn}${g?$n:""}`,logo:s.icon,alt:s.name,onClick:()=>void(c==null?void 0:c(s)),children:d&&p.jsx(Gn,{logo:d.icon,logoBackground:d.iconBackground,address:((u=d.account)==null?void 0:u.address)??""})},s.id)}),p.jsx(L.Button,{color:"secondary",disabled:t,fluid:!0,onClick:o,className:Y.twMerge("text-sm disabled:!opacity-100",zn),"data-testid":"chains-connect-button",children:"Connect"})]}),p.jsxs(L.Text,{variant:"body2",className:"text-center text-accent-secondary",children:["By clicking Connect you agree with the"," ",p.jsx("a",{href:"https://babylonlabs.io/terms-of-use",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Terms of Use"})," ","and"," ",p.jsx("a",{href:"https://babylonlabs.io/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline",children:"Privacy Policy"}),"."]})]})]}));function Zn(){typeof window<"u"&&window.dispatchEvent(new Event(de))}function qn(t){const{chains:e,requiredChainIds:n,selectedWallets:i,displayWallets:r}=J(),{selected:o,disconnect:c}=Ue(),s=he(),d=h.useMemo(()=>Object.values(e),[e]),g=h.useCallback(async u=>{if(u.id==="ETH"||u.id==="BTC"){const a=s[u.id],l=u.id==="ETH"?Fe:vt,f=a==null?void 0:a.wallets.find(E=>E.id===l);if(f&&(a==null?void 0:a.wallets.length)===1){const E=!!a.connectedWallet;try{E?u.id==="ETH"&&!Dt()?Zn():await c(u.id):await a.connect(f.id)}catch(C){le(C)||console.error(`Failed to ${E?"disconnect":"connect"} AppKit ${u.id}:`,C instanceof Error?C.message:"Unknown error")}return}}r==null||r(u.id)},[r,s,c]);return p.jsx(Xn,{disabled:!o,chains:d,requiredChainIds:n,selectedWallets:i,onSelectChain:g,...t})}const Qn=p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"52",height:"52",viewBox:"0 0 52 52",fill:"none",children:p.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 Jn({className:t,icon:e=Qn,title:n,description:i,cancelButton:r="Cancel",submitButton:o=p.jsxs(p.Fragment,{children:["Continue ",p.jsx("span",{className:"hidden md:inline",children:"Anyway"})]}),onCancel:c,onSubmit:s}){return p.jsxs("div",{className:t,children:[p.jsxs(L.DialogBody,{className:"py-16 text-center",children:[p.jsx("div",{className:"mb-6 inline-flex size-20 items-center justify-center bg-primary-contrast text-primary-light",children:e}),p.jsx(L.Heading,{variant:"h4",className:"mb-4 text-accent-primary",children:n}),p.jsx(L.Text,{as:"div",className:"text-accent-secondary",children:i})]}),p.jsxs(L.DialogFooter,{className:"flex gap-4",children:[r&&p.jsx(L.Button,{variant:"outlined",fluid:!0,onClick:c,children:r}),o&&p.jsx(L.Button,{fluid:!0,onClick:s,"data-testid":"error-continue-button",children:o})]})]})}function ei({className:t}){const{screen:e}=J(),{icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:d}=e.params??{};return p.jsx(Jn,{className:t,icon:n,title:i,description:r,cancelButton:o,submitButton:c,onCancel:s,onSubmit:d})}function ti({className:t,title:e,description:n}){return p.jsxs("div",{className:Y.twMerge("flex flex-col items-center justify-center gap-6",t),children:[p.jsx("div",{className:"flex items-center justify-center bg-primary-contrast p-6",children:p.jsx(L.Loader,{className:"text-primary-light"})}),(e||n)&&p.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[e&&p.jsx(L.Heading,{variant:"h4",className:"capitalize text-accent-primary",children:e}),n&&p.jsx(L.Text,{as:"div",className:"text-accent-secondary",children:n})]})]})}const ni="text-[#15B768] dark:text-[#00E676]",ii="bg-[#15B768] dark:bg-[#00E676]",ri="text-[#FFB300]",oi="bg-[#FFB300]";function si({className:t,disabled:e=!1,name:n,logo:i,logoBackground:r,fallbackLink:o,installed:c=!0,hardware:s=!1,label:d,onClick:g}){const a=c||s?{as:"button",disabled:e,onClick:g}:{as:"a",href:o,target:"_blank",rel:"noopener noreferrer"},l=()=>{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 p.jsxs(L.Text,{variant:"body2",className:Y.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":l(),children:[p.jsx(L.WalletIcon,{className:"shrink-0",alt:n,url:i,background:r}),p.jsx("span",{className:Y.twMerge("min-w-0 flex-1 truncate text-left",!c&&"text-accent-secondary"),children:n}),p.jsxs(L.Chip,{className:Y.twMerge("flex shrink-0 items-center gap-1.5 rounded-full",c?"bg-neutral-100":"bg-neutral-200"),children:[(s||c)&&p.jsx("span",{className:Y.twMerge("size-2 rounded-full",s?oi:ii)}),p.jsx("span",{className:s?ri:c?ni:"text-accent-secondary",children:s?d:c?"Installed":"Uninstalled"})]})]})}const ci={[U.MAINNET]:"bc1p",[U.TESTNET]:"tb1p",[U.SIGNET]:"tb1p"},ai="https://tbv-faucet.testnet.babylonlabs.io/",it=t=>t.installed&&!t.hardware?0:t.hardware?1:2,di=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,d)=>it(s)-it(d)),[t]),o=h.useMemo(()=>{var g;if(t.id!=="BTC")return null;const s=(g=t.config)==null?void 0:g.network,d=s?ci[s]:void 0;return d?{prefix:d,showFaucet:s!==U.MAINNET}:null},[t]),c=h.useCallback(async s=>{i==null||i(t,s)},[t,i]);return p.jsxs("div",{className:Y.twMerge("flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight",e),children:[p.jsxs("div",{className:"flex flex-col gap-2 border-b border-secondary-strokeLight p-6",children:[p.jsx(L.Heading,{variant:"h5",className:"text-accent-primary",children:`Select ${t.name} Wallet`}),o&&p.jsxs(L.Text,{variant:"body2",className:"text-accent-secondary",children:[`To continue, connect a ${t.name} wallet with a `,p.jsx("span",{className:"text-accent-primary",children:`${o.prefix} (Taproot)`})," address.",o.showFaucet&&p.jsxs("span",{className:"block",children:[" Don't have testnet BTC yet? Get it from ",p.jsx("a",{href:ai,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary underline underline-offset-2 transition-opacity hover:opacity-80",children:"Faucet"}),"."]})]})]}),p.jsxs("div",{className:"flex flex-col gap-2 p-6",children:[r.map(s=>p.jsx(si,{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 li({widgets:t={},...e}){var s;const{chains:n,screen:i}=J(),r=((s=i.params)==null?void 0:s.chain)??"",o=n==null?void 0:n[r],c=t==null?void 0:t[r];return p.jsx(di,{append:c,chain:o,...e})}const rt={CHAINS:({onConfirm:t})=>p.jsx(qn,{onConfirm:t}),WALLETS:({widgets:t,onSelectWallet:e})=>p.jsx(li,{widgets:t,onSelectWallet:e}),LOADER:({current:t})=>{var e,n;return p.jsx(ti,{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:()=>p.jsx(ei,{}),EMPTY:()=>p.jsx("div",{})};function ui(t){const e=rt[t.current.type]??rt.EMPTY;return p.jsx(e,{...t})}const te="Wallet changed while confirming",fi="Wallet did not report its network",hi="Wallet network does not match the configured network",Ei="Connected wallet has no provider";function pi(t,e){for(const n of e){const i=t.find(({chain:r})=>r===n);if(i)return i}return t[0]}function je(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 ot(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 gi(t,e,n){return t.every(({chain:i,wallet:r,provider:o,receipt:c})=>{const s=e.find(d=>d.chain===i);return s?s.wallet===r&&s.provider===o&&s.receipt===c:!n.includes(i)})}async function st(t,e,n){const i=t(),r=je(i).map(l=>({connection:l,provider:l.wallet.provider,receipt:ce([l],i)})),c=(await Promise.all(r.map(async l=>{var C,y;const{chain:f}=l.connection,{provider:E}=l;try{if(!E)throw new Error(`${Ei}: ${f}`);if(((C=E.isIdentityCurrent)==null?void 0:C.call(E))===!1)throw new Error(te);let m;if(f==="ETH"||f==="BTC"){if(m=f==="ETH"?await E.getChainId():await E.getNetwork(),m==null||!String(m))throw new Error(fi);if(ce([l.connection],i,{[f]:m})!==l.receipt)throw new Error(hi)}const[N,w]=await Promise.all([E.getAddress(),E.getPublicKeyHex()]);if(!N||!w||!Q(N,l.connection.account.address)||!Q(w,l.connection.account.publicKeyHex))throw new Error(te);if(((y=E.isIdentityCurrent)==null?void 0:y.call(E))===!1)throw new Error(te);return{...l,connection:{...l.connection,account:{address:N,publicKeyHex:w}}}}catch(m){if(e.includes(f))throw m;return n==null||n(m instanceof Error?m:new Error("Optional wallet verification failed")),null}}))).filter(l=>l!==null),s=t(),d=je(s),g=c.flatMap(l=>{const{connection:f,receipt:E}=l,C=d.find(({chain:m})=>m===f.chain);if(!!(C&&C.wallet===f.wallet&&C.wallet.provider===l.provider&&ce([C],s)===E))return[l];if(e.includes(f.chain))throw new Error(te);return n==null||n(new Error(te)),[]}),u=g.map(({connection:l})=>l),a=g.map(({connection:l,provider:f,receipt:E})=>({chain:l.chain,wallet:l.wallet,provider:f,receipt:E}));return{receipt:ce(u,s),connections:u,identities:Object.freeze(a)}}function mi({persistent:t,storage:e,config:n,onError:i,btcValidation:r,actions:o,closeButtonClassName:c,actionsClassName:s}){const{visible:d,screen:g,confirmed:u,requiredChainIds:a,close:l,confirm:f,unconfirm:E,displayChains:C,displayError:y}=J(),{acceptTermsOfService:m,onConfirm:N}=At(),w=he(),x=Kn(w,n,i),{connect:M}=Hn({persistent:t,accountStorage:e,onError:i,btcValidation:r}),P=h.useRef(w),O=h.useRef(0),S=h.useRef(null),R=h.useRef(null),K=h.useRef(!1),v=h.useRef(d),_=h.useRef(u),T=h.useRef({persistent:t,requiredChainIds:[...a],storage:e}),I=h.useCallback(()=>{const j=R.current;R.current=null,O.current+=1,S.current=null,j==null||j()},[]);h.useLayoutEffect(()=>{P.current=w,(v.current&&!d||!_.current&&u)&&I(),v.current=d,_.current=u},[u,w,I,d]),h.useLayoutEffect(()=>(K.current=!0,()=>{K.current=!1,I()}),[I]),h.useLayoutEffect(()=>{const j=T.current,B=j.requiredChainIds.length!==a.length||j.requiredChainIds.some((k,pe)=>k!==a[pe]);(j.persistent!==t||j.storage!==e||B)&&I(),T.current={persistent:t,requiredChainIds:[...a],storage:e}},[I,t,a,e]);const A=h.useCallback(()=>{I(),l==null||l()},[l,I]),F=h.useCallback(async()=>{if(S.current!==null||!K.current||!v.current)return;const j=O.current+1;O.current=j,S.current=j;const B=()=>S.current===j&&O.current===j&&K.current&&v.current;let k=()=>{},pe=!1;try{if(!u){const ee=P.current,se=ce(je(ee),ee),Bt=Ct(se,It(se),ee,()=>{I(),e.delete(V),E==null||E()});let Ge=!0;if(k=()=>{Ge&&(Ge=!1,Bt())},!B()){k();return}R.current=k;const ge=await st(()=>P.current,a,i);if(!B())return;const{connections:me}=ge,Se=a.filter(xe=>!me.some(({chain:Ht})=>Ht===xe));if(Se.length>0)throw new Error(`No connected account for required chain${Se.length>1?"s":""}: ${Se.join(", ")}`);const Ce=pi(me,a),ze=async()=>{if(!B())return!1;const xe=await st(()=>P.current,a,i);if(!B())return!1;if(!gi(ge.identities,xe.identities,a))throw new Error(te);return!0};if(Ce&&(await(m==null?void 0:m({address:Ce.account.address,public_key:Ce.account.publicKeyHex,chain:Ce.chain,connections:ot(me)})),!await ze())||(await(N==null?void 0:N(ot(me))),!await ze())||(t&&e.set(V,ge.receipt),!B())||(f==null||f(ge.receipt),!B()))return;pe=!!f}if(!B())return;l==null||l()}catch(ee){if(!B())return;const se=ee instanceof Error?ee:new Error("Wallet confirmation failed");if(i==null||i(se),!B())return;y==null||y({title:"Connection Failed",description:se.message,submitButton:"",cancelButton:"Done",onCancel:C})}finally{pe||(k(),R.current===k&&(R.current=null),O.current===j&&S.current===j&&(S.current=null))}},[m,l,f,u,C,y,I,N,i,t,a,e,E]),Ee=g.type==="WALLETS"?C:void 0;return p.jsx(L.FullScreenDialog,{open:d,onClose:A,onBack:Ee,className:"items-center justify-center p-6",actions:o,closeButtonClassName:c,actionsClassName:s,children:p.jsx("div",{className:"mx-auto w-full max-w-[612px]",children:p.jsx(ui,{current:g,widgets:x,onConfirm:F,onSelectWallet:M})})})}function jt(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 Mt=h.createContext({loading:!0,connected:!1,address:void 0,disconnect:()=>{},open:()=>{}}),Ci=({children:t,callbacks:e})=>{const[n,i]=h.useState(!0),[r,o]=h.useState(),[c,s]=h.useState(null),{open:d,disconnect:g}=Ue(),u=Wt("ETH"),a=h.useCallback(async()=>{try{await(u==null?void 0:u.disconnect("local"))}catch(m){console.error("Failed to disconnect ETH connector:",m instanceof Error?m.message:"Unknown error")}},[u]),l=h.useCallback(async m=>{var N,w;try{o(m),i(!1),await((N=e==null?void 0:e.onConnect)==null?void 0:N.call(e,m))}catch(x){i(!1),(w=e==null?void 0:e.onError)==null||w.call(e,x instanceof Error?x:new Error("ETH connection failed"),{address:m})}},[e]);h.useEffect(()=>{if(i(!1),!u)return;(async()=>{var O;try{if((O=u.connectedWallet)!=null&&O.provider&&!r){const S=u.connectedWallet.provider,R=await S.getAddress();R&&(s(S),l(R));return}if(!r&&u.wallets.length>0){const S=u.wallets[0];if(S.provider)try{await S.provider.getAddress()&&await u.connect(S)}catch{}}}catch{}})();const N=u.on("connect",async O=>{if(O.provider)try{const S=await O.provider.getAddress();S&&(s(O.provider),l(S))}catch(S){console.error("Error getting ETH address:",S instanceof Error?S.message:"Unknown error")}}),w=u.wallets[0],x=w==null?void 0:w.provider;let M=!1;const P=O=>{!(O!=null&&O[0])||r||M||(M=!0,u.connect(w).then(S=>{S||(M=!1)}).catch(S=>{M=!1,console.error("ETH late reconnect failed:",S instanceof Error?S.message:"Unknown error")}))};return x&&typeof x.on=="function"&&x.on("accountsChanged",P),()=>{N(),x&&typeof x.off=="function"&&x.off("accountsChanged",P)}},[u,l,r]),h.useEffect(()=>{if(u)return u.on("disconnect",async()=>{var m;o(void 0),s(null);try{await((m=e==null?void 0:e.onDisconnect)==null?void 0:m.call(e))}catch(N){console.error("Error in onDisconnect callback:",N instanceof Error?N.message:"Unknown error")}})},[u,e]);const f=h.useRef(void 0),E=h.useRef(!1);h.useEffect(()=>{f.current=r},[r]),h.useEffect(()=>{if(!c)return;const m=async N=>{var M,P;if(E.current)return;const w=N[0],x=f.current;if(w&&w.toLowerCase()!==(x==null?void 0:x.toLowerCase())){E.current=!0,f.current=w,o(w);try{await((M=e==null?void 0:e.onAddressChange)==null?void 0:M.call(e,w))}catch(O){(P=e==null?void 0:e.onError)==null||P.call(e,O instanceof Error?O:new Error("ETH address change failed"),{address:w})}finally{E.current=!1}}else!w&&x&&a()};return typeof c.on=="function"&&c.on("accountsChanged",m),()=>{typeof c.off=="function"&&c.off("accountsChanged",m)}},[c,e,a]);const C=h.useCallback(async()=>{var m;if(c)try{const N=await c.getAddress();N?N.toLowerCase()!==(r==null?void 0:r.toLowerCase())&&(f.current=N,o(N),await((m=e==null?void 0:e.onAddressChange)==null?void 0:m.call(e,N))):a()}catch(N){console.error("ETH wallet connection check failed:",N instanceof Error?N.message:"Unknown error"),a()}},[c,r,e,a]);jt(C,{enabled:!!(c&&r)});const y=h.useMemo(()=>!!r,[r]);return p.jsx(Mt.Provider,{value:{loading:n,connected:y,address:r,disconnect:()=>g("ETH"),open:d},children:t})},Ii=()=>h.useContext(Mt);exports.ACCOUNT_CHANGE_EVENTS=ht;exports.APPKIT_BTC_CONNECTOR_ID=vt;exports.APPKIT_ETH_CONNECTOR_ID=Fe;exports.APPKIT_OPEN_EVENT=de;exports.COSMOS_KEYSTORE_CHANGE_EVENTS=Xt;exports.ChainProvider=pn;exports.DISCONNECT_EVENT=Be;exports.ERROR_CODES=re;exports.ETHWalletProvider=Ci;exports.LifeCycleHooksProvider=gn;exports.MONOCHROME_MARK_BACKGROUND=_t;exports.NETWORK_CHANGE_EVENT=Me;exports.Network=U;exports.ONEKEY_BRAND_GREEN=Cn;exports.ONE_HOUR=qt;exports.StateContext=Ke;exports.StateProvider=wt;exports.WalletDialog=mi;exports.WalletError=oe;exports.assertAppKitCapabilities=bt;exports.createAccountStorage=mn;exports.createAppKitCapabilities=Rt;exports.createETHWagmiAdapter=Pt;exports.createExternalWallet=Et;exports.failInitialization=H;exports.getAppKitState=Re;exports.getSharedWagmiConfig=ke;exports.hasSharedWagmiConfig=Te;exports.initializeAppKitModal=Pn;exports.isAccountChangeEvent=Yt;exports.isSharedSessionRefusal=le;exports.isUserRejectionMessage=Jt;exports.metadata=Dn;exports.okxLogo=yt;exports.process$1=ft;exports.registerManualAppKitConfig=xt;exports.removeProviderListener=Zt;exports.setAppKitState=Lt;exports.setSharedWagmiConfig=yn;exports.trackProviderIdentityChanges=$t;exports.useAppKitOpenListener=Wn;exports.useChainConnector=Wt;exports.useETHWallet=Ii;exports.useInscriptionProvider=an;exports.useVisibilityCheck=jt;exports.useWalletConnect=Ue;exports.useWidgetState=J;exports.validateAppKitInitialization=Ot;
|
|
2
|
+
//# sourceMappingURL=ETHWalletProvider-B1utrSWQ.cjs.map
|