@nexus-cross/connect-kit-react 1.4.0-beta.5 → 1.4.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var gt="1.4.0-beta.5";var It="__nexusCrossAppLauncherRuntime";function yo(){if(typeof window>"u")return null;let e=window;return e[It]??(e[It]={mode:"dapp-ui"}),e[It]}function bo(e){if(e.scheduled)return;e.scheduled=!0;let t=()=>{if(e.scheduled=!1,e.loggedMode!==e.mode){if(e.mode==="connect-kit-react"){let n=e.connectKitVersion??gt;console.info(`[CROSSx App Launcher] connect-kit-react v${n} \uCD08\uAE30\uD654 \uC644\uB8CC (dapp-ui v${gt}, \uC0AC\uC6A9 \uBAA8\uB4DC: connect-kit)`)}else console.info(`[CROSSx App Launcher] dapp-ui v${gt} \uCD08\uAE30\uD654 \uC644\uB8CC (\uC0AC\uC6A9 \uBAA8\uB4DC: dapp-ui only)`);e.loggedMode=e.mode}};typeof queueMicrotask=="function"?queueMicrotask(t):Promise.resolve().then(t)}function an(){let e=yo();e&&(e.mode="connect-kit-react",e.connectKitVersion=gt,bo(e))}import{useCallback as _e,useEffect as oe,useMemo as We,useRef as be,useState as Qe}from"react";import{WagmiProvider as vo,useAccount as Po,useChainId as So,useConnect as Ro,useDisconnect as Ao,useSwitchChain as Bo}from"wagmi";import{QueryClient as _o,QueryClientProvider as Eo}from"@tanstack/react-query";import{clearWalletSessionStorage as mn,onOpenOtherWallets as Oo,pickInitialState as No,resolveCurrentWallet as Wo}from"@nexus-cross/connect-kit-wagmi";import{resolveThemeMode as Fo}from"@nexus-cross/connect-kit-core";import{buildDesignSystemCss as Do}from"@nexus-cross/crossx-design-system";import{OnRampProvider as Lo}from"@nexus-cross/onramp/react";import{KycProvider as Go}from"@nexus-cross/kyc/react";import{createContext as ho,useContext as wo}from"react";var Dt=ho(null);function Be(){let e=wo(Dt);if(!e)throw new Error("useCrossConnectKit must be used within <CrossConnectKitProvider>");return e}import{createContext as Co,useContext as cn}from"react";var xt=Co(null);function ko(){let e=cn(xt);if(!e)throw new Error("useCrossConnectKitTheme must be used within <CrossConnectKitProvider>");return e}function yt(){return cn(xt)}import{createContext as To}from"react";var vt=To(null);function dn(){let e=new Set,t=n=>{for(let i of[...e])try{i(n)}catch(o){console.debug("[crossx-kit] analytics handler threw",o)}};return{track:t,emit:n=>t({...n,timestamp:Date.now()}),subscribe:n=>(e.add(n),()=>{e.delete(n)})}}import{useCallback as Io,useMemo as ln}from"react";import{WalletConnectModal as un}from"@nexus-cross/dapp-ui";import{jsx as pn}from"react/jsx-runtime";var xo=new Set(["cross_wallet","cross_extension","metamask","binance"]);function Lt({open:e,onOpenChange:t}){let{connect:n,availableWallets:i,oauth:o,extraWallets:c,walletAllowlist:g,kitConfig:y}=Be(),r=yt()?.mode??"dark",m=ln(()=>{let p=g?new Set(g):null,k={};for(let x of i){if(!xo.has(x.walletId)||p&&!p.has(x.walletId))continue;let v=x.walletId;k[v]=()=>{n(x.walletId)}}for(let[x,v]of Object.entries(c))v&&(p&&!p.has(x)||(k[x]=v));return k},[i,n,c,g]),h=ln(()=>{if(o)return{apple:()=>{o.signIn("apple")},google:()=>{o.signIn("google")}}},[o]),C=Io(p=>t(p),[t]);return pn(un,{wallets:m,socialProviders:h,termsUrl:y.legal?.termsUrl,privacyUrl:y.legal?.privacyUrl,theme:r,open:e,onOpenChange:C,children:pn(un.Content,{})})}import{jsx as ze,jsxs as yn}from"react/jsx-runtime";var Mo=new _o,Gt="crossx-kit:last-wallet-intent",Uo=15e3,Ko=1500,$o=3;function fn(e,t){return Promise.race([e.then(()=>{},()=>{}),new Promise(n=>setTimeout(n,t))])}function qo(e){let t=[],n=e,i=0;for(;n&&i<5;){let o=n;typeof o.message=="string"&&t.push(o.message),n=o.cause,i+=1}return t.some(o=>/external wallet connection/i.test(o))}function Ho(){if(typeof window>"u")return null;try{return window.localStorage.getItem(Gt)??null}catch{return null}}function gn(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Gt,e):window.localStorage.removeItem(Gt)}catch{}}function Vo(e,t){if(typeof window>"u")return t;try{let n=window.localStorage.getItem(e);return n==="cross"||n==="reown"?n:t}catch{return t}}function jo(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}function Qo({children:e,config:t,activeProvider:n,onRequestProviderSwap:i,pendingConnectWalletId:o,clearPending:c,themeMode:g,themeTokens:y,extraWallets:u,walletAllowlist:r,emit:m}){let[h,C]=Qe(!1),[p,k]=Qe(()=>Ho()),[x,v]=Qe(null),{address:W,isConnected:I,isConnecting:U,isReconnecting:D,connector:O}=Po(),{connectors:q,connectAsync:$}=Ro(),{disconnectAsync:z}=Ao(),{kitConfig:L,connectorRegistry:K,crossProvider:Re,reownProvider:de}=t,N=n==="cross"?Re:de,A=We(()=>!I||!O?null:Wo(K,O.id,p),[I,O,K,p]),Y=We(()=>K.entries.filter(l=>l.type!=="embedded"),[K]),V=_e(l=>K.getEntry(l)?.type??"external",[K]),ce=be(null);ce.current=x;let Ie=be(A);Ie.current=A;let qe=be(W);qe.current=W;let Oe=L.embeddedProjectId?.trim()||L.crossProjectId?.trim(),xe=!!L.onRampEnabled&&!!Oe,He=We(()=>!xe||!Oe?null:{projectId:Oe,walletState:{getAddress:()=>qe.current}},[xe,Oe]),we=be(O);we.current=O;let le=L.embeddedProjectId?.trim()||L.crossProjectId?.trim(),Ge=!!L.kycEnabled&&!!le,et=We(()=>!Ge||!le?null:{projectId:le,getAccessToken:async()=>{let l=we.current;if(!(!l||typeof l.getProvider!="function"))try{return(await(await l.getProvider())?.sdk?.getUserInfo?.())?.data?.accessToken||void 0}catch{return}}},[Ge,le]);oe(()=>Oo(()=>C(!0)),[]),oe(()=>{if(!h||typeof document>"u")return;let l=setTimeout(()=>{document.querySelectorAll("#__crossx-confirm-overlay").forEach(b=>b.remove())},50);return()=>clearTimeout(l)},[h]);let ye=be(I),ct=be(I);ye.current=I;let tt=be(!1);oe(()=>{console.debug("[crossx-kit] state",{activeProvider:n,isConnected:I,isConnecting:U,isReconnecting:D,activeConnectorId:O?.id,currentWallet:A,lastIntent:p})},[n,I,U,D,O?.id,A,p]),oe(()=>{I&&!ct.current&&N?.closeModal?.({kitConfig:L}),ct.current=I},[I,N,L]),oe(()=>{I&&v(null)},[I]);let Ae=So(),{switchChainAsync:ve}=Bo(),ue=be(null);oe(()=>{if(!L.enforceDefaultNetworkOnConnect)return;let l=L.defaultNetwork?.id;if(!l)return;if(!I||!W||!O){ue.current=null;return}let b=`${O.id}:${W}`;ue.current!==b&&(ue.current=b,Ae!==l&&ve({chainId:l}).catch(()=>{}))},[L.enforceDefaultNetworkOnConnect,L.defaultNetwork,I,W,O,Ae,ve]);let Me=be(h);oe(()=>{h&&!Me.current?m({name:"connect_modal_opened"}):!h&&Me.current&&m({name:"connect_modal_closed",completed:ye.current}),Me.current=h},[h,m]);let dt=be(I);oe(()=>{if(I&&!dt.current){let l=ce.current;l&&m({name:"connect_succeeded",walletId:l,walletType:V(l),chainId:Ae})}dt.current=I},[I,Ae,m,V]);let s=_e(l=>q.find(b=>b.id===l),[q]);oe(()=>{let l=K.getEntry("cross_embedded");if(!l)return;let b=s(l.connectorId);if(!b)return;let T=!1;return(async()=>{try{let P=await b.getProvider();if(T)return;P?.sdk?.applyTheme?.(g,y??void 0)}catch(P){console.debug("[crossx-kit] applyTheme skipped:",P)}})(),()=>{T=!0}},[K,s,g,y]);let a=_e(l=>{k(l),gn(l)},[]),d=_e(()=>{k(null),gn(null),v(null)},[]);oe(()=>{if(!N?.subscribeModalState)return;let l=!1;return N.subscribeModalState({kitConfig:L},b=>{if(tt.current=b,b){l=!0;return}l&&(l=!1,setTimeout(()=>{if(ye.current)return;let T=ce.current;T&&m({name:"connect_cancelled",walletId:T,stage:"popup"}),(async()=>{try{await z()}catch{}d()})()},250))})},[N,L,z,d,m]),oe(()=>{if(!x||I||typeof window>"u"||x==="cross_embedded")return;let l=typeof document<"u"&&!document.hasFocus(),b=null,T=()=>{l=!0},P=()=>{l&&(b&&clearTimeout(b),b=setTimeout(()=>{if(ye.current||tt.current)return;let B=ce.current;B&&m({name:"connect_cancelled",walletId:B,stage:"popup"}),(async()=>{try{await z()}catch{}d()})()},1e3))};return window.addEventListener("blur",T),window.addEventListener("focus",P),()=>{window.removeEventListener("blur",T),window.removeEventListener("focus",P),b&&clearTimeout(b)}},[x,I,z,d,m]);let f=_e(async l=>{console.debug("[crossx-kit] runConnect enter",{walletId:l,activeProvider:n,isConnected:I,activeConnectorId:O?.id});let b=K.getEntry(l);if(!b){if((l==="metamask"||l==="binance")&&!de){console.error(`[crossx-kit] "${l}" requires the Reown adapter, but it is not configured. Pass \`reownProjectId\` (and ensure \`reown\` is not set to \`false\`) when calling createConnectKitConfig() or createCrossxConfig() to enable WalletConnect-based wallets.`);return}console.error(`[crossx-kit] Unknown walletId: "${l}"`);return}if(v(l),b.providerKind!==n){console.debug("[crossx-kit] provider swap needed",{from:n,to:b.providerKind,walletId:l}),a(l);try{await z()}catch{}await new Promise(B=>setTimeout(B,0)),i(b.providerKind,l);return}let T=V(l);if(m({name:"wallet_selected",walletId:l,walletType:T}),m({name:"connect_started",walletId:l,walletType:T}),a(l),N?.beforeConnect)try{let B=await N.beforeConnect({kitConfig:L,themeMode:g},l);if(console.debug("[crossx-kit] beforeConnect result",{walletId:l,result:B}),B==="handled")return}catch(B){console.warn('[crossx-kit] adapter.beforeConnect threw for "%s":',l,B)}let P=s(b.connectorId);if(console.debug("[crossx-kit] findConnector",{lookupId:b.connectorId,found:P?.id,availableIds:q.map(B=>B.id)}),!P){console.error(`[crossx-kit] Connector "${b.connectorId}" not found on provider "${b.providerKind}". Available: ${q.map(B=>B.id).join(", ")}`),m({name:"connect_failed",walletId:l,reason:"connector_not_found"}),d();return}try{console.debug("[crossx-kit] connectAsync start",{connectorId:P.id});let B=await $({connector:P});console.debug("[crossx-kit] connectAsync resolved",{accountsLen:B.accounts.length,chainId:B.chainId});return}catch(B){let pe=qo(B);if(!pe){console.error('[crossx-kit] connectAsync error for "%s":',l,B);try{await z()}catch{}}if(!b.fallbackConnectorId){pe||m({name:"connect_failed",walletId:l,reason:"connector_error"}),d();return}}if(b.fallbackConnectorId){let B=s(b.fallbackConnectorId);if(B)try{await $({connector:B})}catch(pe){console.error('[crossx-kit] Fallback connect failed for "%s":',l,pe);try{await z()}catch{}m({name:"connect_failed",walletId:l,reason:"fallback_failed"}),d()}else m({name:"connect_failed",walletId:l,reason:"fallback_failed"}),d()}},[K,q,s,$,z,a,d,N,n,L,i,g,m,V]);oe(()=>{if(!o)return;let l=o;c(),f(l)},[o,n]);let w=_e(async()=>{C(!0)},[]),_=_e(async()=>{m({name:"disconnected",walletId:Ie.current});try{await z()}catch(l){console.error("[crossx-kit] wagmi disconnect error:",l)}if(N?.teardown)try{await N.teardown({kitConfig:L})}catch(l){console.error("[crossx-kit] adapter teardown error:",l)}mn(),d()},[z,N,L,d,m]),E=_e(async()=>{await fn(z(),3e3);try{let l=K.getEntry("cross_embedded"),b=l&&s(l.connectorId);if(b?.getProvider){let T=await Promise.race([b.getProvider(),new Promise(B=>setTimeout(B,3e3))]),P=T?.sdk?.signOut;typeof P=="function"&&await fn(P.call(T.sdk),3e3)}}catch{}mn()},[K,s,z]),R=_e(async()=>{let l=K.getEntry("cross_embedded");if(!l)return null;let b=s(l.connectorId);if(!b)return null;try{let T=await b.getProvider(),P=T?.sdk;if(!P?.selectWallet)return null;let B=await P.selectWallet(P.currentAddress??void 0);return B?.address&&T.notifyAccountsChanged&&T.notifyAccountsChanged([B.address]),B&&m({name:"wallet_switched",index:B.index}),B}catch{return null}},[K,s,m]),G=We(()=>{let l=t.oauth;return l?{signIn:async b=>{v("cross_embedded"),m({name:"wallet_selected",walletId:"cross_embedded",walletType:"embedded"}),m({name:"connect_started",walletId:"cross_embedded",walletType:"embedded"});try{await l.signIn(b)}catch(T){throw m({name:"connect_cancelled",walletId:"cross_embedded",stage:"popup"}),v(null),T}}}:null},[t.oauth,m]),Z=be(!1);oe(()=>{if(n!=="cross"||I||U||D||x!=null||Z.current)return;let l=K.getEntry("cross_embedded");if(!l)return;let b=s(l.connectorId);if(!b)return;Z.current=!0;let T=!1;return(async()=>{try{let P=await b.isAuthorized?.();if(T||!P)return;await $({connector:b})}catch{}})(),()=>{T=!0}},[n,I,U,D,x,K,s,$]);let S=be(0);oe(()=>{if(n!=="cross"||I||!U&&!D||S.current>=$o)return;let l=K.getEntry("cross_embedded");if(!l)return;let b=s(l.connectorId);if(!b)return;let T=!1,P=setInterval(()=>{(async()=>{if(T||ye.current)return;let B=await Promise.resolve(b.isAuthorized?.()).catch(()=>!1);if(!(T||!B||ye.current)){S.current+=1,console.warn("[crossx-kit] wagmi reconnect stalled while the SDK holds a session \u2014 forcing an explicit connect to realign");try{await $({connector:b})}catch{}}})()},Ko);return()=>{T=!0,clearInterval(P)}},[n,I,U,D,K,s,$]),oe(()=>{if(x!=="cross_embedded"||I||typeof window>"u")return;let l=!document.hasFocus(),b=()=>{l=!0};window.addEventListener("blur",b);let T=setTimeout(()=>{ye.current||l||(console.warn("[crossx-kit] embedded sign-in stalled before the OAuth popup opened \u2014 clearing the stale session so a retry starts clean"),m({name:"connect_cancelled",walletId:"cross_embedded",stage:"stalled"}),d(),E())},Uo);return()=>{window.removeEventListener("blur",b),clearTimeout(T)}},[x,I,d,E,m]);let F=x!=null&&!I,j=We(()=>({kitConfig:L,connectorRegistry:K,availableWallets:Y,connect:f,connectWallet:w,disconnect:_,selectWallet:R,currentWallet:A,lastIntent:p,isConnecting:F,connectingWalletId:x,openOtherWallets:()=>C(!0),closeOtherWallets:()=>C(!1),otherWalletsOpen:h,oauth:G,extraWallets:u,walletAllowlist:r,onRampEnabled:xe}),[L,K,Y,f,w,_,R,A,p,F,x,h,G,u,r,xe]),H=yn(Dt.Provider,{value:j,children:[e,ze(Lt,{open:h,onOpenChange:C})]});return et&&(H=ze(Go,{config:et,children:H})),He&&(H=ze(Lo,{config:He,children:H})),H}var zo=[/Connection interrupted while trying to subscribe/i,/No matching key\. subscription:/i,/Proposal expired/i];function Xo(e){let t=e?.message;return typeof t!="string"?!1:zo.some(n=>n.test(t))}var Yo={};function Zo(e){return e&&{...e,connections:new Map,current:null}}function Jo({children:e,config:t,initialState:n,extraWallets:i=Yo,walletAllowlist:o}){let[c,g]=Qe(()=>Vo(t.activeProviderStorageKey,t.defaultProvider)),[y,u]=Qe(null),r=be(!1),m=be(null);m.current||(m.current=dn());let h=m.current,C=We(()=>({subscribe:h.subscribe}),[h]),{kitConfig:p}=t,[k,x]=Qe(null),[v,W]=Qe(null),[I,U]=Qe(0),D=We(()=>Fo(p.theme,p.autoDetectTheme),[p.theme,p.autoDetectTheme,I]),O=k??D,q=v??p.themeTokens;oe(()=>{if(!p.autoDetectTheme||k||typeof window>"u"||!window.matchMedia)return;let A=window.matchMedia("(prefers-color-scheme: dark)"),Y=()=>U(V=>V+1);try{return A.addEventListener("change",Y),()=>A.removeEventListener("change",Y)}catch{return A.addListener(Y),()=>A.removeListener(Y)}},[p.autoDetectTheme,k]),oe(()=>{if(typeof document>"u")return;let A=document.documentElement,Y=A.getAttribute("data-ds-theme"),V=A.getAttribute("data-theme");return A.setAttribute("data-ds-theme",O),V||A.setAttribute("data-theme",O),()=>{Y==null?A.removeAttribute("data-ds-theme"):A.setAttribute("data-ds-theme",Y),V==null&&A.removeAttribute("data-theme")}},[O]);let $=We(()=>Do(t.designSystem),[t.designSystem]),z=We(()=>({mode:O,tokens:q,setThemeMode:A=>x(A),setThemeTokens:A=>W(A)}),[O,q]);oe(()=>{if(typeof window>"u")return;let A=Y=>{Xo(Y.reason)&&Y.preventDefault()};return window.addEventListener("unhandledrejection",A),()=>window.removeEventListener("unhandledrejection",A)},[]);let L=_e((A,Y)=>{r.current||(r.current=!0,u(Y),g(A),jo(t.activeProviderStorageKey,A),queueMicrotask(()=>{r.current=!1}))},[t.activeProviderStorageKey]),K=_e(()=>u(null),[]),Re=c==="cross"?t.crossWagmiConfig:t.reownWagmiConfig,de=Zo(No(n,c));if(!Re){if(!(c==="cross"?t.reownWagmiConfig:t.crossWagmiConfig))throw new Error("[crossx-kit] createCrossxConfig returned no wagmi Config for either side");let Y=c==="cross"?"reown":"cross";queueMicrotask(()=>g(Y))}let N=Re??(c==="cross"?t.reownWagmiConfig:t.crossWagmiConfig);return ze(vt.Provider,{value:C,children:yn(xt.Provider,{value:z,children:[ze("style",{"data-crossx-design-system":"",children:$}),ze(vo,{config:N,initialState:de,children:ze(Eo,{client:Mo,children:ze(Qo,{config:t,activeProvider:c,onRequestProviderSwap:L,pendingConnectWalletId:y,clearPending:K,themeMode:O,themeTokens:q,extraWallets:i,walletAllowlist:o??t.kitConfig.wallets??null,emit:h.emit,children:e})})},c)]})})}import{useCallback as Ze,useEffect as rs,useMemo as Et}from"react";import{useQueryClient as ss}from"@tanstack/react-query";import{useAccount as is,useChainId as as,useConfig as cs,useSendTransaction as ds,useSwitchChain as ls}from"wagmi";import{getPublicClient as Vt,readContracts as Kn}from"wagmi/actions";import{WalletInfo as jt,ConnectorId as Je,resolveEnvironment as us,WALLET_REGISTRY as ps}from"@nexus-cross/dapp-ui";import{useOptionalOnRamp as ms,useOptionalOnRampEligibility as fs}from"@nexus-cross/onramp/react";import{APPLE_ICON as Yt,BINANCE_ICON as Hn,CROSSX_ICON as Xt,EXTENSION_ICON as gs,GOOGLE_ICON as Vn,METAMASK_ICON as jn}from"@nexus-cross/connect-kit-wagmi";import{WALLET_LABELS as kt}from"@nexus-cross/crossx-design-system";import{useCallback as re,useMemo as Te,useRef as er}from"react";import{useQueries as wn,useQuery as Xe}from"@tanstack/react-query";import{encodeFunctionData as bt,formatUnits as _t,parseSignature as tr,parseUnits as nr}from"viem";import{getChainId as Mt,getPublicClient as On,readContract as Ee,signTypedData as or,switchChain as Cn,waitForTransactionReceipt as rr,writeContract as kn}from"wagmi/actions";import{useConfig as sr}from"wagmi";async function Pt(e,t,n){if(!(!n||t===void 0))try{if(e.getChainId()===t)return;await e.switchChain(t)}catch{}}var ut=10000n;function bn(e){let t=e==="auto"?1:Number(e||"1");return!Number.isFinite(t)||t<0?100n:BigInt(Math.min(1e4,Math.floor(t*100)))}function St(e,t){let n=bn(t);return n>=ut?0n:e*(ut-n)/ut}function hn(e,t){let n=bn(t);return(e*(ut+n)+(ut-1n))/ut}function ir(e){return e!=="bridge"}var $e="0x0000000000000000000000000000000000000000",Se=100,mt=18,ar=180000n,cr=500000n,Nn=new Set([56,97]),dr=130n,lr=100n,ur={dev:"https://stg-contents.crosstoken.io/frontend/game-token/json/hidden-path.json",stage:"https://stg-contents.crosstoken.io/frontend/game-token/json/hidden-path.json",production:"https://contents.crosstoken.io/frontend/game-token/json/hidden-path.json"},pr={dev:"dev",stage:"stg",production:"prod"};function mr(e,t){let n=e?.[pr[t]]?.hiddenPairs;if(!Array.isArray(n))return null;let i=n.filter(o=>!!o&&typeof o=="object"&&typeof o.fromKey=="string"&&typeof o.toKey=="string");return i.length>0?i:null}var fr={dev:"https://stg-contents.crosstoken.io/frontend/common/app-launcher/contracts.json",stage:"https://stg-contents.crosstoken.io/frontend/common/app-launcher/contracts.json",production:"https://contents.crosstoken.io/frontend/common/app-launcher/contracts.json"},gr=["BSC_CROSS","W_CROSS","NATIVE_CROSS","USDTX","CROSSD","USDTB","SWAP_BRIDGE_ROUTER"],yr={BSC_CROSS:$e,W_CROSS:$e,NATIVE_CROSS:$e,USDTX:$e,CROSSD:$e,USDTB:$e,SWAP_BRIDGE_ROUTER:$e},br=/^0x[0-9a-fA-F]{40}$/;function hr(e,t){let n=typeof e=="string"?e:e?.[t];return typeof n=="string"&&br.test(n)?n:null}function wr(e,t){if(!e?.bridge)return null;let n=e.envToNetwork?.[t]??(t==="production"?"mainnet":"testnet"),i={};for(let o of gr){let c=hr(e.bridge[o],n);if(!c)return null;i[o]=c}return i}var Cr={dev:{bridgeApi:"https://stg-bridge-api.crosstoken.io/bridge",walletApi:"https://stg-wallet-server.crosstoken.io/api",chainIds:{cross:612044,bsc:97}},stage:{bridgeApi:"https://stg-bridge-api.crosstoken.io/bridge",walletApi:"https://stg-wallet-server.crosstoken.io/api",chainIds:{cross:612044,bsc:97}},production:{bridgeApi:"https://bridge-api.crosstoken.io/bridge",walletApi:"https://wallet-server.crosstoken.io/api",chainIds:{cross:612055,bsc:56}}},rt=[{type:"function",name:"quoter",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"swapRouter",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"getAmountSwapBridgeOut",stateMutability:"view",inputs:[{name:"toChainID",type:"uint256"},{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"amountIn",type:"uint256"}],outputs:[{name:"ok",type:"bool"},{name:"swapAmountOut",type:"uint256"},{name:"bridgeValue",type:"uint256"},{name:"networkFee",type:"uint256"},{name:"exFee",type:"uint256"}]},{type:"function",name:"getAmountSwapBridgeIn",stateMutability:"view",inputs:[{name:"toChainID",type:"uint256"},{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"bridgeValue",type:"uint256"}],outputs:[{name:"ok",type:"bool"},{name:"amountIn",type:"uint256"},{name:"swapAmountOut",type:"uint256"},{name:"networkFee",type:"uint256"},{name:"exFee",type:"uint256"}]},{type:"function",name:"swapBridgeExactInputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"amountIn",type:"uint256"},{name:"amountOutMinimum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"bridgeParams",type:"tuple",components:[{name:"toChainID",type:"uint256"},{name:"recipient",type:"address"},{name:"extraData",type:"bytes"}]}]},{name:"deadline",type:"uint256"}],outputs:[{name:"amountOut",type:"uint256"}]},{type:"function",name:"swapBridgeExactOutputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"bridgeParams",type:"tuple",components:[{name:"toChainID",type:"uint256"},{name:"recipient",type:"address"},{name:"extraData",type:"bytes"}]}]},{name:"deadline",type:"uint256"}],outputs:[{name:"amountIn",type:"uint256"}]}],Ut=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Tn=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"nonces",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"",type:"uint256"}]}],In=[{type:"function",name:"quoteExactInputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amountIn",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}]}],outputs:[{name:"amountOut",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}]},{type:"function",name:"quoteExactOutputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}]}],outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}]}],kr=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]}],Ue=[{type:"function",name:"exactInputSingle",stateMutability:"payable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"deadline",type:"uint256"},{name:"amountIn",type:"uint256"},{name:"amountOutMinimum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}]}],outputs:[{name:"amountOut",type:"uint256"}]},{type:"function",name:"multicall",stateMutability:"payable",inputs:[{name:"data",type:"bytes[]"}],outputs:[{name:"results",type:"bytes[]"}]},{type:"function",name:"unwrapWETH9",stateMutability:"payable",inputs:[{name:"amountMinimum",type:"uint256"},{name:"recipient",type:"address"}],outputs:[]},{type:"function",name:"refundETH",stateMutability:"payable",inputs:[],outputs:[]}],Tr=[{type:"function",name:"bridgeToken",stateMutability:"payable",inputs:[{name:"toChainID",type:"uint256"},{name:"fromToken",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gasFee",type:"uint256"},{name:"exFee",type:"uint256"},{name:"extraData",type:"bytes"}],outputs:[{name:"",type:"bool"}]}];async function Wn(e){let t="";try{t=await e.text()}catch{}if(t){try{let n=JSON.parse(t),i=typeof n.data=="string"&&n.data||typeof n.message=="string"&&n.message||"";if(i)return`${i} (status ${e.status})`}catch{}return`${t.slice(0,300)} (status ${e.status})`}return`status ${e.status}`}async function Fe(e,t){let n=await fetch(e,{cache:"no-store",signal:t});if(!n.ok)throw new Error(`CrossD bridge adapter request failed: ${await Wn(n)}`);let i=await n.json();if(i&&typeof i=="object"&&"code"in i&&typeof i.code=="number"&&i.code!==200)throw new Error(i.message||`CrossD bridge adapter API error: ${i.code}`);return i&&typeof i=="object"&&"data"in i?i.data:i}async function xn(e,t,n){let i=await fetch(e,{method:"POST",cache:"no-store",signal:n,headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw new Error(`CrossD bridge adapter request failed: ${await Wn(i)}`);let o=await i.json();if(o&&typeof o=="object"&&"code"in o&&typeof o.code=="number"&&o.code!==200)throw new Error(o.message||`CrossD bridge adapter API error: ${o.code}`);return o&&typeof o=="object"&&"data"in o?o.data:o}function Ir(e){return new Promise(t=>setTimeout(t,e))}async function xr(e,t,{attempts:n=60,intervalMs:i=2e3}={}){for(let o=0;o<n;o+=1){try{let c=await Fe(`${e}/permit-hash/${t}`);if(qt(c))return c}catch{}await Ir(i)}return null}function ie(e,t){return`${e}-${t.toLowerCase()}`}function fe(e){return ie(e.chainId,e.address)}function De(e){return e==="swap"||e==="deposit-swap"||e==="swap-withdraw"}function vr(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"",n=t.toLowerCase();return n.includes("quoteexactinputsingle")||n.includes("quoteexactoutputsingle")||n.includes("getamountswapbridgeout")||n.includes("getamountswapbridgein")||n.includes("execution reverted")?"Amount is too large for this route.":t.split(`
|
|
1
|
+
var gt="1.4.0-beta.6";var It="__nexusCrossAppLauncherRuntime";function yo(){if(typeof window>"u")return null;let e=window;return e[It]??(e[It]={mode:"dapp-ui"}),e[It]}function bo(e){if(e.scheduled)return;e.scheduled=!0;let t=()=>{if(e.scheduled=!1,e.loggedMode!==e.mode){if(e.mode==="connect-kit-react"){let n=e.connectKitVersion??gt;console.info(`[CROSSx App Launcher] connect-kit-react v${n} \uCD08\uAE30\uD654 \uC644\uB8CC (dapp-ui v${gt}, \uC0AC\uC6A9 \uBAA8\uB4DC: connect-kit)`)}else console.info(`[CROSSx App Launcher] dapp-ui v${gt} \uCD08\uAE30\uD654 \uC644\uB8CC (\uC0AC\uC6A9 \uBAA8\uB4DC: dapp-ui only)`);e.loggedMode=e.mode}};typeof queueMicrotask=="function"?queueMicrotask(t):Promise.resolve().then(t)}function an(){let e=yo();e&&(e.mode="connect-kit-react",e.connectKitVersion=gt,bo(e))}import{useCallback as _e,useEffect as oe,useMemo as We,useRef as be,useState as Qe}from"react";import{WagmiProvider as vo,useAccount as Po,useChainId as So,useConnect as Ro,useDisconnect as Ao,useSwitchChain as Bo}from"wagmi";import{QueryClient as _o,QueryClientProvider as Eo}from"@tanstack/react-query";import{clearWalletSessionStorage as mn,onOpenOtherWallets as Oo,pickInitialState as No,resolveCurrentWallet as Wo}from"@nexus-cross/connect-kit-wagmi";import{resolveThemeMode as Fo}from"@nexus-cross/connect-kit-core";import{buildDesignSystemCss as Do}from"@nexus-cross/crossx-design-system";import{OnRampProvider as Lo}from"@nexus-cross/onramp/react";import{KycProvider as Go}from"@nexus-cross/kyc/react";import{createContext as ho,useContext as wo}from"react";var Dt=ho(null);function Be(){let e=wo(Dt);if(!e)throw new Error("useCrossConnectKit must be used within <CrossConnectKitProvider>");return e}import{createContext as Co,useContext as cn}from"react";var xt=Co(null);function ko(){let e=cn(xt);if(!e)throw new Error("useCrossConnectKitTheme must be used within <CrossConnectKitProvider>");return e}function yt(){return cn(xt)}import{createContext as To}from"react";var vt=To(null);function dn(){let e=new Set,t=n=>{for(let i of[...e])try{i(n)}catch(o){console.debug("[crossx-kit] analytics handler threw",o)}};return{track:t,emit:n=>t({...n,timestamp:Date.now()}),subscribe:n=>(e.add(n),()=>{e.delete(n)})}}import{useCallback as Io,useMemo as ln}from"react";import{WalletConnectModal as un}from"@nexus-cross/dapp-ui";import{jsx as pn}from"react/jsx-runtime";var xo=new Set(["cross_wallet","cross_extension","metamask","binance"]);function Lt({open:e,onOpenChange:t}){let{connect:n,availableWallets:i,oauth:o,extraWallets:c,walletAllowlist:g,kitConfig:y}=Be(),r=yt()?.mode??"dark",m=ln(()=>{let p=g?new Set(g):null,k={};for(let x of i){if(!xo.has(x.walletId)||p&&!p.has(x.walletId))continue;let v=x.walletId;k[v]=()=>{n(x.walletId)}}for(let[x,v]of Object.entries(c))v&&(p&&!p.has(x)||(k[x]=v));return k},[i,n,c,g]),h=ln(()=>{if(o)return{apple:()=>{o.signIn("apple")},google:()=>{o.signIn("google")}}},[o]),C=Io(p=>t(p),[t]);return pn(un,{wallets:m,socialProviders:h,termsUrl:y.legal?.termsUrl,privacyUrl:y.legal?.privacyUrl,theme:r,open:e,onOpenChange:C,children:pn(un.Content,{})})}import{jsx as ze,jsxs as yn}from"react/jsx-runtime";var Mo=new _o,Gt="crossx-kit:last-wallet-intent",Uo=15e3,Ko=1500,$o=3;function fn(e,t){return Promise.race([e.then(()=>{},()=>{}),new Promise(n=>setTimeout(n,t))])}function qo(e){let t=[],n=e,i=0;for(;n&&i<5;){let o=n;typeof o.message=="string"&&t.push(o.message),n=o.cause,i+=1}return t.some(o=>/external wallet connection/i.test(o))}function Ho(){if(typeof window>"u")return null;try{return window.localStorage.getItem(Gt)??null}catch{return null}}function gn(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Gt,e):window.localStorage.removeItem(Gt)}catch{}}function Vo(e,t){if(typeof window>"u")return t;try{let n=window.localStorage.getItem(e);return n==="cross"||n==="reown"?n:t}catch{return t}}function jo(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}function Qo({children:e,config:t,activeProvider:n,onRequestProviderSwap:i,pendingConnectWalletId:o,clearPending:c,themeMode:g,themeTokens:y,extraWallets:u,walletAllowlist:r,emit:m}){let[h,C]=Qe(!1),[p,k]=Qe(()=>Ho()),[x,v]=Qe(null),{address:W,isConnected:I,isConnecting:U,isReconnecting:D,connector:O}=Po(),{connectors:q,connectAsync:$}=Ro(),{disconnectAsync:z}=Ao(),{kitConfig:L,connectorRegistry:K,crossProvider:Re,reownProvider:de}=t,N=n==="cross"?Re:de,A=We(()=>!I||!O?null:Wo(K,O.id,p),[I,O,K,p]),Y=We(()=>K.entries.filter(l=>l.type!=="embedded"),[K]),V=_e(l=>K.getEntry(l)?.type??"external",[K]),ce=be(null);ce.current=x;let Ie=be(A);Ie.current=A;let qe=be(W);qe.current=W;let Oe=L.embeddedProjectId?.trim()||L.crossProjectId?.trim(),xe=!!L.onRampEnabled&&!!Oe,He=We(()=>!xe||!Oe?null:{projectId:Oe,walletState:{getAddress:()=>qe.current}},[xe,Oe]),we=be(O);we.current=O;let le=L.embeddedProjectId?.trim()||L.crossProjectId?.trim(),Ge=!!L.kycEnabled&&!!le,et=We(()=>!Ge||!le?null:{projectId:le,getAccessToken:async()=>{let l=we.current;if(!(!l||typeof l.getProvider!="function"))try{return(await(await l.getProvider())?.sdk?.getUserInfo?.())?.data?.accessToken||void 0}catch{return}}},[Ge,le]);oe(()=>Oo(()=>C(!0)),[]),oe(()=>{if(!h||typeof document>"u")return;let l=setTimeout(()=>{document.querySelectorAll("#__crossx-confirm-overlay").forEach(b=>b.remove())},50);return()=>clearTimeout(l)},[h]);let ye=be(I),ct=be(I);ye.current=I;let tt=be(!1);oe(()=>{console.debug("[crossx-kit] state",{activeProvider:n,isConnected:I,isConnecting:U,isReconnecting:D,activeConnectorId:O?.id,currentWallet:A,lastIntent:p})},[n,I,U,D,O?.id,A,p]),oe(()=>{I&&!ct.current&&N?.closeModal?.({kitConfig:L}),ct.current=I},[I,N,L]),oe(()=>{I&&v(null)},[I]);let Ae=So(),{switchChainAsync:ve}=Bo(),ue=be(null);oe(()=>{if(!L.enforceDefaultNetworkOnConnect)return;let l=L.defaultNetwork?.id;if(!l)return;if(!I||!W||!O){ue.current=null;return}let b=`${O.id}:${W}`;ue.current!==b&&(ue.current=b,Ae!==l&&ve({chainId:l}).catch(()=>{}))},[L.enforceDefaultNetworkOnConnect,L.defaultNetwork,I,W,O,Ae,ve]);let Me=be(h);oe(()=>{h&&!Me.current?m({name:"connect_modal_opened"}):!h&&Me.current&&m({name:"connect_modal_closed",completed:ye.current}),Me.current=h},[h,m]);let dt=be(I);oe(()=>{if(I&&!dt.current){let l=ce.current;l&&m({name:"connect_succeeded",walletId:l,walletType:V(l),chainId:Ae})}dt.current=I},[I,Ae,m,V]);let s=_e(l=>q.find(b=>b.id===l),[q]);oe(()=>{let l=K.getEntry("cross_embedded");if(!l)return;let b=s(l.connectorId);if(!b)return;let T=!1;return(async()=>{try{let P=await b.getProvider();if(T)return;P?.sdk?.applyTheme?.(g,y??void 0)}catch(P){console.debug("[crossx-kit] applyTheme skipped:",P)}})(),()=>{T=!0}},[K,s,g,y]);let a=_e(l=>{k(l),gn(l)},[]),d=_e(()=>{k(null),gn(null),v(null)},[]);oe(()=>{if(!N?.subscribeModalState)return;let l=!1;return N.subscribeModalState({kitConfig:L},b=>{if(tt.current=b,b){l=!0;return}l&&(l=!1,setTimeout(()=>{if(ye.current)return;let T=ce.current;T&&m({name:"connect_cancelled",walletId:T,stage:"popup"}),(async()=>{try{await z()}catch{}d()})()},250))})},[N,L,z,d,m]),oe(()=>{if(!x||I||typeof window>"u"||x==="cross_embedded")return;let l=typeof document<"u"&&!document.hasFocus(),b=null,T=()=>{l=!0},P=()=>{l&&(b&&clearTimeout(b),b=setTimeout(()=>{if(ye.current||tt.current)return;let B=ce.current;B&&m({name:"connect_cancelled",walletId:B,stage:"popup"}),(async()=>{try{await z()}catch{}d()})()},1e3))};return window.addEventListener("blur",T),window.addEventListener("focus",P),()=>{window.removeEventListener("blur",T),window.removeEventListener("focus",P),b&&clearTimeout(b)}},[x,I,z,d,m]);let f=_e(async l=>{console.debug("[crossx-kit] runConnect enter",{walletId:l,activeProvider:n,isConnected:I,activeConnectorId:O?.id});let b=K.getEntry(l);if(!b){if((l==="metamask"||l==="binance")&&!de){console.error(`[crossx-kit] "${l}" requires the Reown adapter, but it is not configured. Pass \`reownProjectId\` (and ensure \`reown\` is not set to \`false\`) when calling createConnectKitConfig() or createCrossxConfig() to enable WalletConnect-based wallets.`);return}console.error(`[crossx-kit] Unknown walletId: "${l}"`);return}if(v(l),b.providerKind!==n){console.debug("[crossx-kit] provider swap needed",{from:n,to:b.providerKind,walletId:l}),a(l);try{await z()}catch{}await new Promise(B=>setTimeout(B,0)),i(b.providerKind,l);return}let T=V(l);if(m({name:"wallet_selected",walletId:l,walletType:T}),m({name:"connect_started",walletId:l,walletType:T}),a(l),N?.beforeConnect)try{let B=await N.beforeConnect({kitConfig:L,themeMode:g},l);if(console.debug("[crossx-kit] beforeConnect result",{walletId:l,result:B}),B==="handled")return}catch(B){console.warn('[crossx-kit] adapter.beforeConnect threw for "%s":',l,B)}let P=s(b.connectorId);if(console.debug("[crossx-kit] findConnector",{lookupId:b.connectorId,found:P?.id,availableIds:q.map(B=>B.id)}),!P){console.error(`[crossx-kit] Connector "${b.connectorId}" not found on provider "${b.providerKind}". Available: ${q.map(B=>B.id).join(", ")}`),m({name:"connect_failed",walletId:l,reason:"connector_not_found"}),d();return}try{console.debug("[crossx-kit] connectAsync start",{connectorId:P.id});let B=await $({connector:P});console.debug("[crossx-kit] connectAsync resolved",{accountsLen:B.accounts.length,chainId:B.chainId});return}catch(B){let pe=qo(B);if(!pe){console.error('[crossx-kit] connectAsync error for "%s":',l,B);try{await z()}catch{}}if(!b.fallbackConnectorId){pe||m({name:"connect_failed",walletId:l,reason:"connector_error"}),d();return}}if(b.fallbackConnectorId){let B=s(b.fallbackConnectorId);if(B)try{await $({connector:B})}catch(pe){console.error('[crossx-kit] Fallback connect failed for "%s":',l,pe);try{await z()}catch{}m({name:"connect_failed",walletId:l,reason:"fallback_failed"}),d()}else m({name:"connect_failed",walletId:l,reason:"fallback_failed"}),d()}},[K,q,s,$,z,a,d,N,n,L,i,g,m,V]);oe(()=>{if(!o)return;let l=o;c(),f(l)},[o,n]);let w=_e(async()=>{C(!0)},[]),_=_e(async()=>{m({name:"disconnected",walletId:Ie.current});try{await z()}catch(l){console.error("[crossx-kit] wagmi disconnect error:",l)}if(N?.teardown)try{await N.teardown({kitConfig:L})}catch(l){console.error("[crossx-kit] adapter teardown error:",l)}mn(),d()},[z,N,L,d,m]),E=_e(async()=>{await fn(z(),3e3);try{let l=K.getEntry("cross_embedded"),b=l&&s(l.connectorId);if(b?.getProvider){let T=await Promise.race([b.getProvider(),new Promise(B=>setTimeout(B,3e3))]),P=T?.sdk?.signOut;typeof P=="function"&&await fn(P.call(T.sdk),3e3)}}catch{}mn()},[K,s,z]),R=_e(async()=>{let l=K.getEntry("cross_embedded");if(!l)return null;let b=s(l.connectorId);if(!b)return null;try{let T=await b.getProvider(),P=T?.sdk;if(!P?.selectWallet)return null;let B=await P.selectWallet(P.currentAddress??void 0);return B?.address&&T.notifyAccountsChanged&&T.notifyAccountsChanged([B.address]),B&&m({name:"wallet_switched",index:B.index}),B}catch{return null}},[K,s,m]),G=We(()=>{let l=t.oauth;return l?{signIn:async b=>{v("cross_embedded"),m({name:"wallet_selected",walletId:"cross_embedded",walletType:"embedded"}),m({name:"connect_started",walletId:"cross_embedded",walletType:"embedded"});try{await l.signIn(b)}catch(T){throw m({name:"connect_cancelled",walletId:"cross_embedded",stage:"popup"}),v(null),T}}}:null},[t.oauth,m]),Z=be(!1);oe(()=>{if(n!=="cross"||I||U||D||x!=null||Z.current)return;let l=K.getEntry("cross_embedded");if(!l)return;let b=s(l.connectorId);if(!b)return;Z.current=!0;let T=!1;return(async()=>{try{let P=await b.isAuthorized?.();if(T||!P)return;await $({connector:b})}catch{}})(),()=>{T=!0}},[n,I,U,D,x,K,s,$]);let S=be(0);oe(()=>{if(n!=="cross"||I||!U&&!D||S.current>=$o)return;let l=K.getEntry("cross_embedded");if(!l)return;let b=s(l.connectorId);if(!b)return;let T=!1,P=setInterval(()=>{(async()=>{if(T||ye.current)return;let B=await Promise.resolve(b.isAuthorized?.()).catch(()=>!1);if(!(T||!B||ye.current)){S.current+=1,console.warn("[crossx-kit] wagmi reconnect stalled while the SDK holds a session \u2014 forcing an explicit connect to realign");try{await $({connector:b})}catch{}}})()},Ko);return()=>{T=!0,clearInterval(P)}},[n,I,U,D,K,s,$]),oe(()=>{if(x!=="cross_embedded"||I||typeof window>"u")return;let l=!document.hasFocus(),b=()=>{l=!0};window.addEventListener("blur",b);let T=setTimeout(()=>{ye.current||l||(console.warn("[crossx-kit] embedded sign-in stalled before the OAuth popup opened \u2014 clearing the stale session so a retry starts clean"),m({name:"connect_cancelled",walletId:"cross_embedded",stage:"stalled"}),d(),E())},Uo);return()=>{window.removeEventListener("blur",b),clearTimeout(T)}},[x,I,d,E,m]);let F=x!=null&&!I,j=We(()=>({kitConfig:L,connectorRegistry:K,availableWallets:Y,connect:f,connectWallet:w,disconnect:_,selectWallet:R,currentWallet:A,lastIntent:p,isConnecting:F,connectingWalletId:x,openOtherWallets:()=>C(!0),closeOtherWallets:()=>C(!1),otherWalletsOpen:h,oauth:G,extraWallets:u,walletAllowlist:r,onRampEnabled:xe}),[L,K,Y,f,w,_,R,A,p,F,x,h,G,u,r,xe]),H=yn(Dt.Provider,{value:j,children:[e,ze(Lt,{open:h,onOpenChange:C})]});return et&&(H=ze(Go,{config:et,children:H})),He&&(H=ze(Lo,{config:He,children:H})),H}var zo=[/Connection interrupted while trying to subscribe/i,/No matching key\. subscription:/i,/Proposal expired/i];function Xo(e){let t=e?.message;return typeof t!="string"?!1:zo.some(n=>n.test(t))}var Yo={};function Zo(e){return e&&{...e,connections:new Map,current:null}}function Jo({children:e,config:t,initialState:n,extraWallets:i=Yo,walletAllowlist:o}){let[c,g]=Qe(()=>Vo(t.activeProviderStorageKey,t.defaultProvider)),[y,u]=Qe(null),r=be(!1),m=be(null);m.current||(m.current=dn());let h=m.current,C=We(()=>({subscribe:h.subscribe}),[h]),{kitConfig:p}=t,[k,x]=Qe(null),[v,W]=Qe(null),[I,U]=Qe(0),D=We(()=>Fo(p.theme,p.autoDetectTheme),[p.theme,p.autoDetectTheme,I]),O=k??D,q=v??p.themeTokens;oe(()=>{if(!p.autoDetectTheme||k||typeof window>"u"||!window.matchMedia)return;let A=window.matchMedia("(prefers-color-scheme: dark)"),Y=()=>U(V=>V+1);try{return A.addEventListener("change",Y),()=>A.removeEventListener("change",Y)}catch{return A.addListener(Y),()=>A.removeListener(Y)}},[p.autoDetectTheme,k]),oe(()=>{if(typeof document>"u")return;let A=document.documentElement,Y=A.getAttribute("data-ds-theme"),V=A.getAttribute("data-theme");return A.setAttribute("data-ds-theme",O),V||A.setAttribute("data-theme",O),()=>{Y==null?A.removeAttribute("data-ds-theme"):A.setAttribute("data-ds-theme",Y),V==null&&A.removeAttribute("data-theme")}},[O]);let $=We(()=>Do(t.designSystem),[t.designSystem]),z=We(()=>({mode:O,tokens:q,setThemeMode:A=>x(A),setThemeTokens:A=>W(A)}),[O,q]);oe(()=>{if(typeof window>"u")return;let A=Y=>{Xo(Y.reason)&&Y.preventDefault()};return window.addEventListener("unhandledrejection",A),()=>window.removeEventListener("unhandledrejection",A)},[]);let L=_e((A,Y)=>{r.current||(r.current=!0,u(Y),g(A),jo(t.activeProviderStorageKey,A),queueMicrotask(()=>{r.current=!1}))},[t.activeProviderStorageKey]),K=_e(()=>u(null),[]),Re=c==="cross"?t.crossWagmiConfig:t.reownWagmiConfig,de=Zo(No(n,c));if(!Re){if(!(c==="cross"?t.reownWagmiConfig:t.crossWagmiConfig))throw new Error("[crossx-kit] createCrossxConfig returned no wagmi Config for either side");let Y=c==="cross"?"reown":"cross";queueMicrotask(()=>g(Y))}let N=Re??(c==="cross"?t.reownWagmiConfig:t.crossWagmiConfig);return ze(vt.Provider,{value:C,children:yn(xt.Provider,{value:z,children:[ze("style",{"data-crossx-design-system":"",children:$}),ze(vo,{config:N,initialState:de,children:ze(Eo,{client:Mo,children:ze(Qo,{config:t,activeProvider:c,onRequestProviderSwap:L,pendingConnectWalletId:y,clearPending:K,themeMode:O,themeTokens:q,extraWallets:i,walletAllowlist:o??t.kitConfig.wallets??null,emit:h.emit,children:e})})},c)]})})}import{useCallback as Ze,useEffect as rs,useMemo as Et}from"react";import{useQueryClient as ss}from"@tanstack/react-query";import{useAccount as is,useChainId as as,useConfig as cs,useSendTransaction as ds,useSwitchChain as ls}from"wagmi";import{getPublicClient as Vt,readContracts as Kn}from"wagmi/actions";import{WalletInfo as jt,ConnectorId as Je,resolveEnvironment as us,WALLET_REGISTRY as ps}from"@nexus-cross/dapp-ui";import{useOptionalOnRamp as ms,useOptionalOnRampEligibility as fs}from"@nexus-cross/onramp/react";import{APPLE_ICON as Yt,BINANCE_ICON as Hn,CROSSX_ICON as Xt,EXTENSION_ICON as gs,GOOGLE_ICON as Vn,METAMASK_ICON as jn}from"@nexus-cross/connect-kit-wagmi";import{WALLET_LABELS as kt}from"@nexus-cross/crossx-design-system";import{useCallback as re,useMemo as Te,useRef as er}from"react";import{useQueries as wn,useQuery as Xe}from"@tanstack/react-query";import{encodeFunctionData as bt,formatUnits as _t,parseSignature as tr,parseUnits as nr}from"viem";import{getChainId as Mt,getPublicClient as On,readContract as Ee,signTypedData as or,switchChain as Cn,waitForTransactionReceipt as rr,writeContract as kn}from"wagmi/actions";import{useConfig as sr}from"wagmi";async function Pt(e,t,n){if(!(!n||t===void 0))try{if(e.getChainId()===t)return;await e.switchChain(t)}catch{}}var ut=10000n;function bn(e){let t=e==="auto"?1:Number(e||"1");return!Number.isFinite(t)||t<0?100n:BigInt(Math.min(1e4,Math.floor(t*100)))}function St(e,t){let n=bn(t);return n>=ut?0n:e*(ut-n)/ut}function hn(e,t){let n=bn(t);return(e*(ut+n)+(ut-1n))/ut}function ir(e){return e!=="bridge"}var $e="0x0000000000000000000000000000000000000000",Se=100,mt=18,ar=180000n,cr=500000n,Nn=new Set([56,97]),dr=130n,lr=100n,ur={dev:"https://stg-contents.crosstoken.io/frontend/game-token/json/hidden-path.json",stage:"https://stg-contents.crosstoken.io/frontend/game-token/json/hidden-path.json",production:"https://contents.crosstoken.io/frontend/game-token/json/hidden-path.json"},pr={dev:"dev",stage:"stg",production:"prod"};function mr(e,t){let n=e?.[pr[t]]?.hiddenPairs;if(!Array.isArray(n))return null;let i=n.filter(o=>!!o&&typeof o=="object"&&typeof o.fromKey=="string"&&typeof o.toKey=="string");return i.length>0?i:null}var fr={dev:"https://stg-contents.crosstoken.io/frontend/common/app-launcher/contracts.json",stage:"https://stg-contents.crosstoken.io/frontend/common/app-launcher/contracts.json",production:"https://contents.crosstoken.io/frontend/common/app-launcher/contracts.json"},gr=["BSC_CROSS","W_CROSS","NATIVE_CROSS","USDTX","CROSSD","USDTB","SWAP_BRIDGE_ROUTER"],yr={BSC_CROSS:$e,W_CROSS:$e,NATIVE_CROSS:$e,USDTX:$e,CROSSD:$e,USDTB:$e,SWAP_BRIDGE_ROUTER:$e},br=/^0x[0-9a-fA-F]{40}$/;function hr(e,t){let n=typeof e=="string"?e:e?.[t];return typeof n=="string"&&br.test(n)?n:null}function wr(e,t){if(!e?.bridge)return null;let n=e.envToNetwork?.[t]??(t==="production"?"mainnet":"testnet"),i={};for(let o of gr){let c=hr(e.bridge[o],n);if(!c)return null;i[o]=c}return i}var Cr={dev:{bridgeApi:"https://stg-bridge-api.crosstoken.io/bridge",walletApi:"https://stg-wallet-server.crosstoken.io/api",chainIds:{cross:612044,bsc:97}},stage:{bridgeApi:"https://stg-bridge-api.crosstoken.io/bridge",walletApi:"https://stg-wallet-server.crosstoken.io/api",chainIds:{cross:612044,bsc:97}},production:{bridgeApi:"https://bridge-api.crosstoken.io/bridge",walletApi:"https://wallet-server.crosstoken.io/api",chainIds:{cross:612055,bsc:56}}},rt=[{type:"function",name:"quoter",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"swapRouter",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"getAmountSwapBridgeOut",stateMutability:"view",inputs:[{name:"toChainID",type:"uint256"},{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"amountIn",type:"uint256"}],outputs:[{name:"ok",type:"bool"},{name:"swapAmountOut",type:"uint256"},{name:"bridgeValue",type:"uint256"},{name:"networkFee",type:"uint256"},{name:"exFee",type:"uint256"}]},{type:"function",name:"getAmountSwapBridgeIn",stateMutability:"view",inputs:[{name:"toChainID",type:"uint256"},{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"bridgeValue",type:"uint256"}],outputs:[{name:"ok",type:"bool"},{name:"amountIn",type:"uint256"},{name:"swapAmountOut",type:"uint256"},{name:"networkFee",type:"uint256"},{name:"exFee",type:"uint256"}]},{type:"function",name:"swapBridgeExactInputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"amountIn",type:"uint256"},{name:"amountOutMinimum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"bridgeParams",type:"tuple",components:[{name:"toChainID",type:"uint256"},{name:"recipient",type:"address"},{name:"extraData",type:"bytes"}]}]},{name:"deadline",type:"uint256"}],outputs:[{name:"amountOut",type:"uint256"}]},{type:"function",name:"swapBridgeExactOutputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"bridgeParams",type:"tuple",components:[{name:"toChainID",type:"uint256"},{name:"recipient",type:"address"},{name:"extraData",type:"bytes"}]}]},{name:"deadline",type:"uint256"}],outputs:[{name:"amountIn",type:"uint256"}]}],Ut=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Tn=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"nonces",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"",type:"uint256"}]}],In=[{type:"function",name:"quoteExactInputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amountIn",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}]}],outputs:[{name:"amountOut",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}]},{type:"function",name:"quoteExactOutputSingle",stateMutability:"nonpayable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}]}],outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}]}],kr=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]}],Ue=[{type:"function",name:"exactInputSingle",stateMutability:"payable",inputs:[{name:"params",type:"tuple",components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"deadline",type:"uint256"},{name:"amountIn",type:"uint256"},{name:"amountOutMinimum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}]}],outputs:[{name:"amountOut",type:"uint256"}]},{type:"function",name:"multicall",stateMutability:"payable",inputs:[{name:"data",type:"bytes[]"}],outputs:[{name:"results",type:"bytes[]"}]},{type:"function",name:"unwrapWETH9",stateMutability:"payable",inputs:[{name:"amountMinimum",type:"uint256"},{name:"recipient",type:"address"}],outputs:[]},{type:"function",name:"refundETH",stateMutability:"payable",inputs:[],outputs:[]}],Tr=[{type:"function",name:"bridgeToken",stateMutability:"payable",inputs:[{name:"toChainID",type:"uint256"},{name:"fromToken",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"gasFee",type:"uint256"},{name:"exFee",type:"uint256"},{name:"extraData",type:"bytes"}],outputs:[{name:"",type:"bool"}]}];async function Wn(e){let t="";try{t=await e.text()}catch{}if(t){try{let n=JSON.parse(t),i=typeof n.data=="string"&&n.data||typeof n.message=="string"&&n.message||"";if(i)return`${i} (status ${e.status})`}catch{}return`${t.slice(0,300)} (status ${e.status})`}return`status ${e.status}`}async function Fe(e,t){let n=await fetch(e,{cache:"no-store",signal:t});if(!n.ok)throw new Error(`CrossD bridge adapter request failed: ${await Wn(n)}`);let i=await n.json();if(i&&typeof i=="object"&&"code"in i&&typeof i.code=="number"&&i.code!==200)throw new Error(i.message||`CrossD bridge adapter API error: ${i.code}`);return i&&typeof i=="object"&&"data"in i?i.data:i}async function xn(e,t,n){let i=await fetch(e,{method:"POST",cache:"no-store",signal:n,headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw new Error(`CrossD bridge adapter request failed: ${await Wn(i)}`);let o=await i.json();if(o&&typeof o=="object"&&"code"in o&&typeof o.code=="number"&&o.code!==200)throw new Error(o.message||`CrossD bridge adapter API error: ${o.code}`);return o&&typeof o=="object"&&"data"in o?o.data:o}function Ir(e){return new Promise(t=>setTimeout(t,e))}async function xr(e,t,{attempts:n=60,intervalMs:i=2e3}={}){for(let o=0;o<n;o+=1){try{let c=await Fe(`${e}/permit-hash/${t}`);if(qt(c))return c}catch{}await Ir(i)}return null}function ie(e,t){return`${e}-${t.toLowerCase()}`}function fe(e){return ie(e.chainId,e.address)}function De(e){return e==="swap"||e==="deposit-swap"||e==="swap-withdraw"}function vr(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"",n=t.toLowerCase();return n.includes("quoteexactinputsingle")||n.includes("quoteexactoutputsingle")||n.includes("getamountswapbridgeout")||n.includes("getamountswapbridgein")||n.includes("execution reverted")?"Amount is too large for this route.":t.split(`
|
|
2
2
|
`)[0]?.trim()||"Failed to quote bridge."}function vn(e){return e===56||e===97?"BSC":e===612044||e===612055?"ONEchain":`Chain ${e}`}function se(e,t){return t?t.toLowerCase()===e.contracts.NATIVE_CROSS.toLowerCase()?e.contracts.W_CROSS:t:$e}function st(e){let t=_t(e,mt);return t.includes(".")?t.replace(/\.?0+$/,""):t}function wt(e){return nr(e||"0",mt)}function he(e){try{return wt(e||"0")}catch{return 0n}}function Ye(e){if(typeof e=="bigint")return e;if(typeof e=="number")return BigInt(Math.trunc(e));if(!e)return 0n;try{return BigInt(e)}catch{return 0n}}function Kt(e){let t=_t(e,9);return(t.includes(".")?t.replace(/\.?0+$/,""):t)||"0"}function Rt(e){return e==="bridge"?ar:cr}function Pn(e,t){if(!e||!t)return"0";let n=e*e;if(n===0n)return"0";let i=t*t,o=i>n?i-n:n-i;if(o===0n)return"0";let c=(o*100000000n+n/2n)/n;if(c>=100000000n)return"100";let g=c/1000000n,y=(c%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return y?`${g}.${y}`:`${g}`}function Pr(e){if(!e||Number(e)===0)return"0%";let[t,n=""]=e.split("."),i=n.length>4?n.slice(0,4):n;return i?`${t}.${i}%`:`${t}%`}async function Sn(e,t,n,i,o,c=!1){let g=On(e,{chainId:t}),y=n;try{let r=await g?.estimateContractGas?.({account:o.account,address:o.address,abi:o.abi,functionName:o.functionName,args:o.args,value:o.value});typeof r=="bigint"&&r>0n&&(y=i?r*dr/lr:r)}catch{}let u={gas:y};if(Nn.has(t))try{let r=await g?.getGasPrice?.();typeof r=="bigint"&&r>0n&&(u.gasPrice=r)}catch{}else if(c)try{let r=await g?.estimateFeesPerGas?.();typeof r?.maxFeePerGas=="bigint"&&(u.maxFeePerGas=r.maxFeePerGas),typeof r?.maxPriorityFeePerGas=="bigint"&&(u.maxPriorityFeePerGas=r.maxPriorityFeePerGas)}catch{}return u}function ht(){return BigInt(Math.floor(Date.now()/1e3)+1800)}var Sr={100:"0.01%",500:"0.05%",3e3:"0.3%",1e4:"1%"};function Rr(e){return Sr[e]??`${e/1e4}%`}function Ar(e,t){let n=Number(e||"0");return!Number.isFinite(n)||n<=0?"0":(n*t/1e6).toFixed(8).replace(/\.?0+$/,"")}function Rn(e){return st(e)}function An(e,t){let n=Number(t??"0");return!Number.isFinite(n)||n<=0?0n:e*BigInt(Math.floor(n))/1000n}function At(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(i=>i.toLowerCase()===n)}function Br(e,t,n){return[{from:[e.contracts.USDTX],to:[e.contracts.CROSSD]},{from:[e.contracts.BSC_CROSS],to:[e.contracts.NATIVE_CROSS,e.contracts.W_CROSS]},{from:[e.contracts.NATIVE_CROSS,e.contracts.W_CROSS],to:[e.contracts.CROSSD]}].some(o=>At(t,o.from)&&At(n,o.to)||At(t,o.to)&&At(n,o.from))}function _r(e){if(De(e.type))return null;if(e.type==="swap-bridge"){let t=e.steps.find(n=>n.type==="bridge");return t?{from:t.fromChain,to:t.toChain,token:t.fromToken}:null}if(e.type==="bridge-swap"){let t=e.steps.find(n=>n.type==="bridge");return t?{from:t.fromChain,to:t.toChain,token:t.fromToken}:null}return{from:e.from.chainId,to:e.to.chainId,token:e.from.address}}function Er({input:e,path:t,config:n}){if(!n||De(t.type))return"";let i=Ye(n.minimumValue),o=Ye(n.gasFee??n.gas_fee),c=t.type==="swap-bridge"?i+o*12n/10n:i;return c<=0n?"":e.fromAmount&&he(e.fromAmount)<c&&t.type!=="swap"?`Minimum ${Rn(c)}`:t.type==="swap-bridge"&&e.toAmount&&he(e.toAmount)<c?`Available ${Rn(c)} or more.`:""}function Or({input:e,path:t,config:n}){if(!n||t.type!=="bridge"&&t.type!=="bridge-swap")return"";let i=Ye(n.gasFee??n.gas_fee);if(i<=0n||!e.fromAmount)return"";let o=he(e.fromToken.balance||"0"),c=he(e.fromAmount);return o-i<c?`Insufficient network fee(${e.fromToken.symbol})`:""}function Nr(e,t){let n=new Set;return e?.list?.forEach(i=>{let o=i.localChain??i.local_chain;o&&Object.entries(i.pairs||{}).forEach(([c,g])=>{g.forEach(y=>{y.localToken&&n.add(ie(o,y.localToken)),y.remoteToken&&n.add(ie(Number(c),y.remoteToken))})})}),Object.entries(t?.swapPools||t?.swap_pools||{}).forEach(([i,o])=>{o.forEach(c=>{c.token0&&n.add(ie(Number(i),c.token0)),c.token1&&n.add(ie(Number(i),c.token1))})}),n}function Wr(e,t){return!e||!t?null:ie(e,t)}function Fr({envConfig:e,bridgePairList:t,swapPools:n,tokenInfo:i,tokenStats:o}){let c=Nr(t,n),g=new Map;o?.forEach(u=>{let r=Wr(Number(u.chainId??u.chain_id),u.address);r&&g.set(r,u)});let y={};return c.forEach(u=>{let[r,m]=u.split("-"),h=Number(r),C=i?.find(k=>Number(k.chainId??k.chain_id)===h&&k.address?.toLowerCase()===m);if(!C?.symbol||!C.name)return;let p=g.get(u);y[u]={key:u,chainId:h,address:m,symbol:C.symbol,name:C.name,decimals:C.decimals||mt,image:C.image||C.icon_url,price:p?.price?Number(p.price):void 0,isNativeToken:m.toLowerCase()===e.contracts.NATIVE_CROSS.toLowerCase()}}),y}function Fn(e,t){return t?.list?.find(n=>(n.localChain??n.local_chain)===e)?.bridge||""}function Dn(e,t,n){let[i,o]=e.split("-"),[c,g]=t.split("-"),y=Number(i),u=Number(c);for(let r of n?.list||[]){if((r.localChain??r.local_chain)!==y)continue;let m=r.pairs?.[c];if(m){for(let h of m)if(h.localToken?.toLowerCase()===o&&h.remoteToken?.toLowerCase()===g)return{type:"bridge",fromChain:y,fromToken:o,toChain:u,toToken:g,bridgeAddress:Fn(y,n)}}}return null}function Ln(e,t,n,i){let o,c=1/0;for(let g of e||[]){let y=i(g.token0),u=i(g.token1);if(y===t&&u===n||u===t&&y===n){let r=g.fee??Se;r<c&&(o=g,c=r)}}return o?{fee:c,poolAddress:o.poolAddress||o.pool_address||""}:null}function Gn(e,t,n,i){let[o,c]=e.split("-"),[g,y]=t.split("-");if(o!==g)return null;let u=Number(o),r=(n?.swapPools||n?.swap_pools)?.[o];if(!r)return null;let m=i.contracts.W_CROSS.toLowerCase(),h=i.contracts.NATIVE_CROSS.toLowerCase(),p=Ln(r,c,y,x=>x?.toLowerCase()===m?h:x?.toLowerCase());if(!p)return null;let k="swap";return u===i.chainIds.cross&&(c===h&&(k="deposit-swap"),y===h&&(k="swap-withdraw")),{pathType:k,step:{type:"swap",chain:u,fromToken:c,toToken:y,fee:p.fee,poolAddress:p.poolAddress}}}function Dr(e,t,n,i){let[o,c]=e.split("-"),[g]=t.split("-");if(o===g)return null;let y=(n?.swapPools||n?.swap_pools)?.[o]||[],u=r=>r?.toLowerCase();for(let r of y){let m=u(r.token0),h=u(r.token1),C=m===c?h:h===c?m:null;if(!C)continue;let p=Dn(ie(Number(o),C),t,i);if(!p)continue;let k=Ln(y,c,C,u);return[{type:"swap",chain:Number(o),fromToken:c,toToken:C,fee:k?.fee??Se,poolAddress:k?.poolAddress??""},p]}return null}function Lr(e,t,n,i,o){let[c,g]=e.split("-"),[y]=t.split("-");if(c===y)return null;for(let u of n?.list||[])if((u.localChain??u.local_chain)===Number(c))for(let r of u.pairs?.[y]||[]){if(r.localToken?.toLowerCase()!==g)continue;let m=r.remoteToken?.toLowerCase();if(!m)continue;let h=Gn(ie(Number(y),m),t,i,o);if(h)return[{type:"bridge",fromChain:Number(c),fromToken:g,toChain:Number(y),toToken:m,bridgeAddress:Fn(Number(c),n)},h.step]}return null}function Gr({envConfig:e,bridgePairList:t,swapPools:n,enrichedTokens:i}){return(o,c)=>{let g=i[o],y=i[c];if(!g||!y||o===c)return null;let u=Dn(o,c,t);if(u)return{type:"bridge",steps:[u],from:g,to:y};let r=Gn(o,c,n,e);if(r)return{type:r.pathType,steps:[r.step],from:g,to:y};let m=Dr(o,c,n,t);if(m)return{type:"swap-bridge",steps:m,from:g,to:y};let h=Lr(o,c,t,n,e);return h?{type:"bridge-swap",steps:h,from:g,to:y}:null}}function Bn(e,t){return{name:e.name,symbol:e.symbol,chainId:e.chainId,address:e.address,decimals:e.decimals,balance:t.get(e.key)||"0",iconUrl:e.image,priceUsd:e.price}}function Mr(e){return e.length<=10?e:`${e.slice(0,6)}...${e.slice(-4)}`}function Ur(e){return e.includes(".")?e.replace(/\.?0+$/,"")||"0":e}function Kr(e,t){let n=e.startsWith("-"),i=n?e.slice(1):e,[o,c=""]=i.split("."),g=c.slice(0,t).replace(/0+$/,""),y=g?`${o}.${g}`:o;return n?`-${y}`:y}function $r(e){let t=e.startsWith("-"),n=t?e.slice(1):e,[i,o]=n.split("."),c=i.replace(/\B(?=(\d{3})+(?!\d))/g,","),g=o?`${c}.${o}`:c;return t?`-${g}`:g}function $t(e){if(e==null||e==="")return"0";let t=String(e),n=Number(t);return!Number.isFinite(n)||n===0?"0":$r(Kr(t,4))}function _n(e,t){if(e==null||e==="")return"0";try{return Ur(_t(BigInt(String(e)),t.decimals))}catch{return"0"}}function qt(e){return!!(e&&/^0x[0-9a-fA-F]+$/.test(e))}function qr(e){return e?new Date(e*1e3).toISOString():new Date().toISOString()}function Hr(e,t){return t.toLowerCase()===e.contracts.W_CROSS.toLowerCase()?e.contracts.NATIVE_CROSS:t}function Vr(e,t){let n=Mr(t);return{name:n,symbol:n,chainId:e,address:t,decimals:mt,balance:"0"}}function En({envConfig:e,tokenByBridgeKey:t,chainId:n,address:i}){if(!i)return null;let o=Hr(e,i);return t.get(ie(n,o))||t.get(ie(n,i))||Vr(n,o)}function Bt(e){return e?.toLowerCase()||""}function jr(e){if(e.source==="swap")return"swap";let t=Bt(e.fromToken??e.from_token),n=Bt(e.toToken??e.to_token),i=Bt(e.swapTokenIn??e.swap_token_in),o=Bt(e.swapTokenOut??e.swap_token_out);return n&&i&&n===i?"bridge-swap":t&&o&&t===o?"swap-bridge":"bridge"}function Qr(e,t){let n=e.status??0,i=e.extracallSuccess??e.extracall_success??!1;return t==="bridge-swap"&&n===1&&!i?"failed":n===1?"success":"pending"}function zr({envConfig:e,item:t,tokenByBridgeKey:n}){let i=Number(t.fromChainID??t.from_chain_id??0),o=Number(t.toChainID??t.to_chain_id??0);if(!i||!o)return null;let c=jr(t),g=t.swapTokenIn??t.swap_token_in,y=t.swapTokenOut??t.swap_token_out,u=t.swapAmountIn??t.swap_amount_in,r=t.swapAmountOut??t.swap_amount_out,m=t.fromToken??t.from_token,h=t.toToken??t.to_token,C=t.value,p=t.value;c==="swap"?(m=g,h=y,C=u,p=r):c==="swap-bridge"?(m=g,C=u,p=t.value):c==="bridge-swap"&&(h=y,C=u,p=r);let k=En({envConfig:e,tokenByBridgeKey:n,chainId:i,address:m}),x=En({envConfig:e,tokenByBridgeKey:n,chainId:o,address:h}),v=t.initiatedTxHash??t.initiated_tx_hash;return!k||!x||!qt(v)?null:{id:`${v}-${t.index??""}`,timestamp:qr(t.initiatedTime??t.initiated_time),txHash:v,fromToken:k,toToken:x,fromAmount:_n(C,k),toAmount:_n(p,x),summary:{pathType:c},status:Qr(t,c)}}function Xr(e){let t=new Map;return e.flat().forEach(n=>{let i=Number(n.chainId??n.chain_id),o=n.address?.toLowerCase();if(!i||!o)return;let c=n.quantity?.numeric??n.balance??"0",g=n.quantity?.decimals??n.decimals??mt;try{t.set(ie(i,o),_t(BigInt(c||"0"),g))}catch{t.set(ie(i,o),"0")}}),t}function Ke(e,t="first"){let n=e.steps.filter(i=>i.type==="swap");return t==="last"?n[n.length-1]:n[0]}function Yr(e,t){let n=(e?.swapPools||e?.swap_pools)?.[String(t.chainIds.cross)];if(!n?.length)return"";let i=t.contracts.CROSSD.toLowerCase(),o=t.contracts.USDTX.toLowerCase(),c=n.find(g=>{let y=g.token0?.toLowerCase(),u=g.token1?.toLowerCase();return y===i&&u===o||y===o&&u===i});return c?.poolAddress||c?.pool_address||""}function Zr(e,t){return e.from.chainId===t.chainIds.cross&&e.from.address.toLowerCase()===t.contracts.CROSSD.toLowerCase()&&e.to.chainId===t.chainIds.bsc&&e.to.address.toLowerCase()===t.contracts.USDTB.toLowerCase()}function Jr(e){if(e===void 0)return;let t=10n**BigInt(mt),n=e>=50000n*t?"normal":e>10000n*t?"low":"rebalancing",i=Number(e>0n?e*100n/(100000n*t):0n);return{label:"Available Liquidity",status:n,percentage:Math.min(i,100)}}function pt(e,t,n,i){let o=[e.from,e.to].find(c=>c.chainId===t&&c.address.toLowerCase()===n.toLowerCase())??i?.[ie(t,n)];return{symbol:o?.symbol||n.slice(0,6),iconUrl:o?.image}}function es(e,t){let n=[];for(let o of e.steps)o.type==="swap"?(n.push({chain:o.chain,address:o.fromToken}),n.push({chain:o.chain,address:o.toToken})):(n.push({chain:o.fromChain,address:o.fromToken}),n.push({chain:o.toChain,address:o.toToken}));let i=n.filter((o,c)=>c===0||!(o.chain===n[c-1].chain&&o.address.toLowerCase()===n[c-1].address.toLowerCase()));return i.length===0?[{symbol:e.from.symbol,iconUrl:e.from.image},{symbol:e.to.symbol,iconUrl:e.to.image}]:i.map(o=>pt(e,o.chain,o.address,t))}function ts({input:e,path:t,amountData:n,gasInfo:i,liquidity:o,enrichedTokens:c,priceImpact:g}){let y=e.fromAmount||"0",u=e.toAmount||"0",r=Ke(t),m=t.steps.find(U=>U.type==="bridge"),h=t.type!=="bridge",C=!De(t.type),p=r?Ar(y,r.fee):"0",k=Number(y)>0||Number(u)>0,x=r?pt(t,r.chain,r.fromToken,c):{symbol:e.fromToken.symbol,iconUrl:e.fromToken.iconUrl},v=r?pt(t,r.chain,r.toToken,c):{symbol:e.toToken.symbol,iconUrl:e.toToken.iconUrl},W=m?pt(t,m.fromChain,m.fromToken,c):void 0,I=(U,D,O)=>k?D&&D>0n?{label:U,value:st(D),tone:"default",valueToken:O}:{label:U,value:"Free",tone:"accent"}:{label:U,value:"0"};return{pathType:t.type,priceImpact:g,liquidity:o,bridgeInfo:C&&m?[{label:"Route",value:`${vn(m.fromChain)} \u2192 ${vn(m.toChain)}`},I("Validator Fee",n?.exFee,W),I("Network Fee",n?.networkFee,W)]:void 0,swapInfo:h&&r?[{label:"Route",value:"",routeTokens:[pt(t,r.chain,r.fromToken,c),pt(t,r.chain,r.toToken,c)]},{label:"Price Impact",value:Pr(g)},{label:"In Amount",value:$t(y),valueToken:x},{label:r&&De(t.type)?`Swap Fee (${Rr(r.fee??Se)})`:"Swap Fee",value:$t(p),valueToken:x},{label:"Out Amount",value:$t(u),valueToken:v}]:void 0,txFee:[...i?.gasPrice?[{label:"Gas Price",value:`${i.gasPrice} Gwei`}]:[{label:"Priority Fee Per Gas",value:`${i?.priorityFeePerGas||"0"} Gwei`},{label:"Max Fee Per Gas",value:`${i?.maxFeePerGas||"0"} Gwei`}],{label:"Gas Limit",value:i?.gasLimit||"0"}],txFeeInfo:i?{estTxFee:i.estTxFee,isDelegateFee:i.isDelegateFee,tokenIconUrl:i.gasCurrencyIconUrl,tokenSymbol:i.gasCurrencySymbol}:{estTxFee:"0",isDelegateFee:!1}}}function Ct({env:e,walletAddress:t,enabled:n=!0,restoreChainAfterSwitch:i=!0}){let o=sr(),c=er(new Map),y=Xe({queryKey:["crossd-bridge-adapter",e,"remote-contracts"],queryFn:async({signal:s})=>{let a=wr(await Fe(fr[e],s),e);if(!a)throw new Error("CrossD bridge adapter: invalid contracts.json");return a},enabled:n,staleTime:5*6e4}).data??null,u=n&&!!y,r=Te(()=>({...Cr[e],contracts:y??yr}),[e,y]),m=Xe({queryKey:["crossd-bridge-adapter",e,"pairs"],queryFn:({signal:s})=>Fe(`${r.bridgeApi}/pairs`,s),enabled:u,staleTime:3e4}),h=Xe({queryKey:["crossd-bridge-adapter",e,"swap-pools"],queryFn:({signal:s})=>Fe(`${r.bridgeApi}/swap-pools`,s),enabled:u,staleTime:3e4}),C=Te(()=>Yr(h.data,r),[r,h.data]),p=Xe({queryKey:["crossd-bridge-adapter",e,"available-liquidity",C],queryFn:async()=>await Ee(o,{address:r.contracts.USDTX,abi:Ut,functionName:"balanceOf",args:[C],chainId:r.chainIds.cross}),enabled:u&&!!C,staleTime:3e4}),k=Xe({queryKey:["crossd-bridge-adapter",e,"token-info"],queryFn:({signal:s})=>Fe(`${r.walletApi}/v1/public/token/info`,s),enabled:u,staleTime:3e4}),x=Xe({queryKey:["crossd-bridge-adapter",e,"token-stats"],queryFn:({signal:s})=>Fe(`${r.walletApi}/v1/public/token/stats`,s),enabled:u,staleTime:3e4}),v=wn({queries:[r.chainIds.cross,r.chainIds.bsc].map(s=>({queryKey:["crossd-bridge-adapter",e,"balance",t,s],queryFn:({signal:a})=>{let d=new URLSearchParams({networkId:`eip155:${s}`,account:t||""});return Fe(`${r.walletApi}/v1/public/token/balance?${d}`,a)},enabled:u&&!!t,staleTime:0,refetchInterval:u&&t?5e3:!1}))}),W=wn({queries:[r.chainIds.cross,r.chainIds.bsc].map(s=>({queryKey:["crossd-bridge-adapter",e,"gas-suggestion",s],queryFn:async({signal:a})=>{try{let w=await On(o,{chainId:s})?.estimateFeesPerGas?.();if(w?.maxFeePerGas||w?.gasPrice)return{fast:{maxFee:w.maxFeePerGas?.toString()||w.gasPrice?.toString(),maxPriorityFee:w.maxPriorityFeePerGas?.toString()||"0"}}}catch{}let d=new URLSearchParams({chain_id:String(s),without_gas_limit:"false"});return Fe(`${r.walletApi}/v1/public/transaction/gas-suggestion/dynamic?${d}`,a)},enabled:u,staleTime:1e4,retry:1}))}),I=Xe({queryKey:["crossd-bridge-adapter",e,"hidden-pairs"],queryFn:async({signal:s})=>mr(await Fe(ur[e],s),e),enabled:u,staleTime:5*6e4,retry:1}),U=Te(()=>I.data??[],[I.data]),D=Te(()=>Fr({envConfig:r,bridgePairList:m.data,swapPools:h.data,tokenInfo:k.data,tokenStats:x.data}),[m.data,r,h.data,k.data,x.data]),O=Te(()=>Gr({envConfig:r,bridgePairList:m.data,swapPools:h.data,enrichedTokens:D}),[m.data,D,r,h.data]),q=Te(()=>Xr(v.map(s=>s.data).filter(s=>Array.isArray(s))),[v]),$=Te(()=>{let s=new Map;return Object.values(D).forEach(a=>{let d=Bn(a,q);s.set(a.key,d)}),s},[q,D]),z=Te(()=>{let s=new Map,a=$.get(ie(r.chainIds.cross,r.contracts.NATIVE_CROSS));a&&s.set(r.chainIds.cross,{symbol:a.symbol,iconUrl:a.iconUrl});let d=k.data?.find(f=>Number(f.chainId??f.chain_id)===r.chainIds.bsc&&(f.symbol??"").toUpperCase()==="BNB");return d&&s.set(r.chainIds.bsc,{symbol:d.symbol??"BNB",iconUrl:d.image??d.icon_url}),s},[r,$,k.data]),L=Xe({queryKey:["crossd-bridge-adapter",e,"history",t],queryFn:({signal:s})=>xn(`${r.bridgeApi}/history`,{owner:t,page:1,size:20,sort:"desc",status:"all"},s),enabled:u&&!!t,staleTime:0,refetchInterval:u&&t?5e3:!1}),K=Te(()=>(L.data?.histories||[]).map(s=>zr({envConfig:r,item:s,tokenByBridgeKey:$})).filter(s=>!!s),[L.data?.histories,r,$]),Re=Te(()=>Jr(p.data),[p.data]),de=W[0]?.data,N=W[1]?.data,A=Te(()=>{let s=new Map;return de&&s.set(r.chainIds.cross,de),N&&s.set(r.chainIds.bsc,N),s},[N,de,r.chainIds.bsc,r.chainIds.cross]),Y=re((s,a,d)=>{let f=A.get(s.from.chainId)?.fast,w=a?d?.gasLimit??Rt(s.type):0n,_=d?.gasPrice&&d.gasPrice>0n?d.gasPrice:0n,E=d?.maxFeePerGas&&d.maxFeePerGas>0n?d.maxFeePerGas:0n,R=d?.maxPriorityFeePerGas&&d.maxPriorityFeePerGas>0n?d.maxPriorityFeePerGas:0n,G=Ye(f?.maxFee??f?.max_fee),Z=Ye(f?.maxPriorityFee??f?.max_priority_fee),S=E>0n?E:G>0n?G:_,F=R>0n?R:Z>0n?Z:S,j=_>0n?_:S,X=Nn.has(s.from.chainId)&&j>0n,l=w*(X?j:S),b=$.get(ie(s.from.chainId,r.contracts.NATIVE_CROSS)),T=s.type!=="swap-bridge",P=z.get(s.from.chainId);return{estTxFee:a?st(l):"0",priorityFeePerGas:a&&!X?Kt(F):"0",maxFeePerGas:a&&!X?Kt(S):"0",gasLimit:a?w.toString():"0",gasPrice:a&&X?Kt(j):void 0,isDelegateFee:s.type==="swap-bridge"?!1:Br(r,s.from.address,s.to.address),tokenIconUrl:T?b?.iconUrl:void 0,tokenSymbol:T?b?.symbol:void 0,gasCurrencyIconUrl:P?.iconUrl,gasCurrencySymbol:P?.symbol}},[r,A,z,$]),V=re(async s=>{let a=_r(s);if(!a)return null;let d=`${e}:${a.from}:${a.to}:${a.token.toLowerCase()}`,f=c.current.get(d);if(f)return f;let w=(async()=>{let _=new URLSearchParams({from:String(a.from),to:String(a.to),token:a.token});try{return(await Fe(`${r.bridgeApi}/token-config?${_}`)).config??null}catch{return null}})();return c.current.set(d,w),w},[e,r.bridgeApi]),ce=Te(()=>{let s=Object.values(D).map(d=>Bn(d,q)),a=ie(r.chainIds.cross,r.contracts.CROSSD);return s.sort((d,f)=>{let w=fe(d).toLowerCase()===a.toLowerCase(),_=fe(f).toLowerCase()===a.toLowerCase();return w!==_?w?-1:1:fe(d).localeCompare(fe(f))})},[q,D,r]),Ie=Te(()=>{if(y)return{target:{chainId:r.chainIds.cross,address:r.contracts.CROSSD},swap:{from:{chainId:r.chainIds.cross,address:r.contracts.NATIVE_CROSS},feeDelegated:!0},bridge:{from:[{chainId:r.chainIds.bsc,address:r.contracts.USDTB},{chainId:r.chainIds.cross,address:r.contracts.USDTX}]}}},[r,y]),qe=re(s=>{let a=fe(s),d=a.toLowerCase(),f=[];Object.keys(D).forEach(E=>{let R=E.toLowerCase();if(d===R||U.some(S=>S.fromKey===d&&S.toKey===R))return;let G=O(a,E);if(!G)return;let Z=$.get(E);Z&&f.push({token:Z,path:G})});let w=ie(r.chainIds.cross,r.contracts.CROSSD),_=ie(r.chainIds.cross,r.contracts.NATIVE_CROSS);return f.sort((E,R)=>{if(d===w.toLowerCase()){let j=fe(E.token).toLowerCase()===_.toLowerCase(),X=fe(R.token).toLowerCase()===_.toLowerCase();if(j!==X)return j?-1:1}let G=De(E.path.type),Z=De(R.path.type);if(G!==Z)return G?-1:1;let S=E.token.chainId===s.chainId,F=R.token.chainId===s.chainId;return S!==F?S?-1:1:fe(E.token).localeCompare(fe(R.token))}),f.map(E=>E.token)},[D,r,O,U,$]),Oe=re(async s=>await Ee(o,{address:r.contracts.SWAP_BRIDGE_ROUTER,abi:rt,functionName:"quoter",chainId:s}),[r.contracts.SWAP_BRIDGE_ROUTER,o]),xe=re(async s=>{Mt(o)!==s&&await Cn(o,{chainId:s})},[o]),He=re(s=>Pt({getChainId:()=>Mt(o),switchChain:a=>Cn(o,{chainId:a})},s,i),[i,o]),we=re(async s=>await Ee(o,{address:r.contracts.SWAP_BRIDGE_ROUTER,abi:rt,functionName:"swapRouter",chainId:s}),[r.contracts.SWAP_BRIDGE_ROUTER,o]),le=re(async({path:s,step:a,amount:d,source:f})=>{let w=await Oe(a.chain),_=a.poolAddress?Ee(o,{address:a.poolAddress,abi:kr,functionName:"slot0",chainId:a.chain}).then(G=>G?.[0]).catch(()=>{}):Promise.resolve(void 0);if(f==="from"){let G=await Ee(o,{address:w,abi:In,functionName:"quoteExactInputSingle",args:[{tokenIn:se(r,a.fromToken),tokenOut:se(r,a.toToken),amountIn:wt(d),fee:a.fee??Se,sqrtPriceLimitX96:0n}],chainId:a.chain}),Z=Pn(await _,G[1]);return{amount:st(G[0]),path:s,priceImpact:Z}}let E=await Ee(o,{address:w,abi:In,functionName:"quoteExactOutputSingle",args:[{tokenIn:se(r,a.fromToken),tokenOut:se(r,a.toToken),amount:wt(d),fee:a.fee??Se,sqrtPriceLimitX96:0n}],chainId:a.chain}),R=Pn(await _,E[1]);return{amount:st(E[0]),path:s,priceImpact:R}},[r,Oe,o]),Ge=re(async(s,a)=>{if(!t)throw new Error("Wallet is not connected.");let d=Rt(a.type);if(De(a.type)){let S=Ke(a,"first");if(!S)throw new Error("Swap route is not available.");let F=he(s.fromAmount),j=he(s.toAmount);if(F<=0n)throw new Error("Bridge amount is empty.");if(j<=0n)throw new Error("Bridge quote is not ready.");let X=await we(S.chain),H=St(j,s.slippage),l=a.type==="swap-withdraw"?$e:t,b={tokenIn:se(r,S.fromToken),tokenOut:se(r,S.toToken),fee:S.fee??Se,recipient:l,deadline:ht(),amountIn:F,amountOutMinimum:H,sqrtPriceLimitX96:0n};if(a.type==="swap-withdraw"){let T=bt({abi:Ue,functionName:"exactInputSingle",args:[b]}),P=bt({abi:Ue,functionName:"unwrapWETH9",args:[H,t]});return{address:X,abi:Ue,functionName:"multicall",args:[[T,P]],chainId:S.chain,fallbackGasLimit:d}}if(a.type==="deposit-swap"){let T=bt({abi:Ue,functionName:"exactInputSingle",args:[b]}),P=bt({abi:Ue,functionName:"refundETH",args:[]});return{address:X,abi:Ue,functionName:"multicall",args:[[T,P]],value:F,chainId:S.chain,fallbackGasLimit:d}}return{address:X,abi:Ue,functionName:"exactInputSingle",args:[b],chainId:S.chain,fallbackGasLimit:d}}if(a.type==="swap-bridge"){let S=Ke(a,"first");if(!S)throw new Error("Swap bridge route is not available.");let F=he(s.fromAmount),j=he(s.toAmount);if(F<=0n)throw new Error("Bridge amount is empty.");if(j<=0n)throw new Error("Bridge quote is not ready.");let X=r.contracts.SWAP_BRIDGE_ROUTER,H=ht(),l={toChainID:BigInt(a.to.chainId),recipient:t,extraData:"0x"},b={tokenIn:se(r,a.from.address),tokenOut:se(r,S.toToken),fee:S.fee??Se,sqrtPriceLimitX96:0n,bridgeParams:l};if(s.lastChangedBy==="to"){let P={...b,amountOut:j,amountInMaximum:hn(F,s.slippage)};return{address:X,abi:rt,functionName:"swapBridgeExactOutputSingle",args:[P,H],value:a.from.isNativeToken?P.amountInMaximum:void 0,chainId:a.from.chainId,fallbackGasLimit:d}}let T={...b,amountIn:F,amountOutMinimum:St(j,s.slippage)};return{address:X,abi:rt,functionName:"swapBridgeExactInputSingle",args:[T,H],value:a.from.isNativeToken?F:void 0,chainId:a.from.chainId,fallbackGasLimit:d}}let f=a.steps.find(S=>S.type==="bridge");if(!f?.bridgeAddress)throw new Error("Bridge route is not available.");let w=he(s.fromAmount);if(w<=0n)throw new Error("Bridge amount is empty.");let _=await V(a),E=Ye(_?.gasFee??_?.gas_fee),R=An(w,_?.exFeeRate??_?.ex_fee_rate),G="0x";if(a.type==="bridge-swap"){let S=Ke(a,"last");if(!S)throw new Error("Bridge swap route is not available.");let F=he(s.toAmount);if(F<=0n)throw new Error("Bridge quote is not ready.");let j=await we(a.to.chainId),X=St(F,s.slippage),H=bt({abi:Ue,functionName:"exactInputSingle",args:[{tokenIn:se(r,S.fromToken),tokenOut:se(r,S.toToken),fee:S.fee??Se,recipient:t,deadline:ht(),amountIn:w,amountOutMinimum:X,sqrtPriceLimitX96:0n}]});G=`${j}${H.slice(2)}`}let Z=[BigInt(a.to.chainId),a.from.address,t,w,E,R,G];return{address:f.bridgeAddress,abi:Tr,functionName:"bridgeToken",args:Z,value:a.from.isNativeToken?w+R+E:void 0,chainId:a.from.chainId,fallbackGasLimit:d}},[r,V,we,t]),et=re(async(s,a)=>{if(a.type==="bridge"||a.type==="bridge-swap")return Ge(s,a);if(!t)throw new Error("Wallet is not connected.");let d=he(s.fromAmount);if(d<=0n)throw new Error("Bridge amount is empty.");if(a.type==="swap-bridge"){let E=Ke(a,"first");if(!E)throw new Error("Swap bridge route is not available.");let R=r.contracts.SWAP_BRIDGE_ROUTER,G={tokenIn:se(r,a.from.address),tokenOut:se(r,E.toToken),fee:E.fee??Se,sqrtPriceLimitX96:0n,bridgeParams:{toChainID:BigInt(a.to.chainId),recipient:t,extraData:"0x"},amountIn:d,amountOutMinimum:0n};return{address:R,abi:rt,functionName:"swapBridgeExactInputSingle",args:[G,ht()],value:a.from.isNativeToken?d:void 0,chainId:a.from.chainId,fallbackGasLimit:Rt(a.type)}}let f=Ke(a,"first");if(!f)throw new Error("Swap route is not available.");let w=await we(f.chain),_={tokenIn:se(r,f.fromToken),tokenOut:se(r,f.toToken),fee:f.fee??Se,recipient:t,deadline:ht(),amountIn:d,amountOutMinimum:0n,sqrtPriceLimitX96:0n};return{address:w,abi:Ue,functionName:"exactInputSingle",args:[_],value:a.from.isNativeToken?d:void 0,chainId:f.chain,fallbackGasLimit:Rt(a.type)}},[Ge,r,we,t]),ye=re(async(s,a)=>{if(!t)return null;try{let d=await et(s,a),f=De(a.type)||a.type==="swap-bridge",w=await Sn(o,d.chainId,d.fallbackGasLimit,f,{account:t,address:d.address,abi:d.abi,functionName:d.functionName,args:d.args,value:d.value},!0);return{gasLimit:w.gas,gasPrice:w.gasPrice,maxFeePerGas:w.maxFeePerGas,maxPriorityFeePerGas:w.maxPriorityFeePerGas}}catch{return null}},[et,o,t]),ct=re(async s=>{let a=fe(s.fromToken),d=fe(s.toToken),f=O(a,d);if(!f)return{error:"Route is not available."};let w=s.lastChangedBy==="to"?s.toAmount:s.fromAmount,_=!!w&&Number(w)>0,E=Zr(f,r)?Re:void 0,R=async(H,l,b)=>{let T=_?await ye(H,f):null,P=Y(f,_,T);return ts({input:H,path:f,gasInfo:P,amountData:l,liquidity:E,enrichedTokens:D,priceImpact:b})};if(!w||Number(w)<=0)return{fromAmount:s.fromAmount,toAmount:s.toAmount,summary:await R(s)};let G=await V(f),Z=Ye(G?.gasFee??G?.gas_fee),S=f.type==="bridge"||f.type==="bridge-swap"?{networkFee:Z}:void 0,F=f.type==="bridge"?s.lastChangedBy==="to"?{...s,fromAmount:s.toAmount}:{...s,toAmount:s.fromAmount}:s,j=Er({input:F,path:f,config:G});if(j)return{fromAmount:F.fromAmount,toAmount:F.toAmount,summary:await R(F,S),error:j};let X=Or({input:F,path:f,config:G});if(X)return{fromAmount:F.fromAmount,toAmount:F.toAmount,summary:await R(F,S),error:X};if(f.type==="bridge")return{fromAmount:F.fromAmount,toAmount:F.toAmount,summary:await R(F,S)};try{if(f.type==="swap-bridge"){let T=Ke(f,"first"),P=r.contracts.SWAP_BRIDGE_ROUTER;if(!T)return{error:"Swap bridge route is not ready."};let B=Ne=>le({path:f,step:T,amount:Ne,source:"from"}).then(je=>je.priceImpact).catch(()=>{});if(s.lastChangedBy==="from"){let Ne=await Ee(o,{address:P,abi:rt,functionName:"getAmountSwapBridgeOut",args:[BigInt(f.to.chainId),se(r,f.from.address),se(r,T.toToken),T.fee??Se,wt(s.fromAmount)],chainId:f.from.chainId}),je=st(Ne[1]),Ot={...s,toAmount:je};return{toAmount:je,summary:await R(Ot,{networkFee:Ne[3],exFee:Ne[4]},await B(s.fromAmount))}}let pe=await Ee(o,{address:P,abi:rt,functionName:"getAmountSwapBridgeIn",args:[BigInt(f.to.chainId),se(r,f.from.address),se(r,T.toToken),T.fee??Se,wt(s.toAmount)],chainId:f.from.chainId}),Ve=st(pe[1]),nt={...s,fromAmount:Ve};return{fromAmount:Ve,summary:await R(nt,{networkFee:pe[3],exFee:pe[4]},await B(Ve))}}let H=f.type==="bridge-swap"?Ke(f,"last"):Ke(f,"first");if(!H)return{error:"Swap route is not available."};let l=await le({path:f,step:H,amount:w,source:s.lastChangedBy});if(s.lastChangedBy==="from"){let T={...s,toAmount:l.amount};return{toAmount:l.amount,summary:await R(T,S,l.priceImpact)}}let b={...s,fromAmount:l.amount};return{fromAmount:l.amount,summary:await R(b,S,l.priceImpact)}}catch(H){return{fromAmount:s.fromAmount,toAmount:s.toAmount,summary:await R(s,S),error:vr(H)}}},[Re,Y,D,r,ye,O,V,le,o]),tt=re(async s=>{if(s.from.isNativeToken)return null;if(s.type==="swap"||s.type==="deposit-swap"||s.type==="swap-withdraw")return we(s.from.chainId);if(s.type==="swap-bridge")return r.contracts.SWAP_BRIDGE_ROUTER;let a=s.steps.find(d=>d.type==="bridge");return a?.bridgeAddress?a.bridgeAddress:null},[r.contracts.SWAP_BRIDGE_ROUTER,we]),Ae=re(async s=>{if(!t)throw new Error("Wallet is not connected.");let a=fe(s.fromToken),d=fe(s.toToken),f=O(a,d);if(!f)throw new Error("Route is not available.");if(!De(f.type)&&f.type!=="swap-bridge"||f.from.isNativeToken)return null;let w=he(s.fromAmount);if(w<=0n)return null;let _=await tt(f);return!_||await Ee(o,{address:f.from.address,abi:Ut,functionName:"allowance",args:[t,_],chainId:f.from.chainId})>=w?null:{token:s.fromToken,tokenAddress:f.from.address,spenderAddress:_,amount:s.fromAmount}},[O,tt,o,t]),ve=re(async(s,a)=>{let d=he(a.amount||s.fromAmount);if(d<=0n)throw new Error("Approval amount is empty.");await xe(a.token.chainId);let f=await kn(o,{address:a.tokenAddress,abi:Ut,functionName:"approve",args:[a.spenderAddress,d],chainId:a.token.chainId});await rr(o,{hash:f,chainId:a.token.chainId})},[xe,o]),ue=re(async(s,a)=>{let d=await Ge(s,a);await xe(d.chainId);let f=await Sn(o,d.chainId,d.fallbackGasLimit,ir(a.type),{account:t,address:d.address,abi:d.abi,functionName:d.functionName,args:d.args,value:d.value});return{txHash:await kn(o,{address:d.address,abi:d.abi,functionName:d.functionName,args:d.args,value:d.value,chainId:d.chainId,...f}),fromToken:s.fromToken,toToken:s.toToken,fromAmount:s.fromAmount,toAmount:s.toAmount}},[Ge,xe,o,t]),Me=re(async(s,a)=>{let d=t;if(!d)throw new Error("Wallet is not connected.");let f=a.steps.find(je=>je.type==="bridge");if(!f?.bridgeAddress)throw new Error("Bridge route is not available.");let w=a.from.address,_=a.from.chainId,E=he(s.fromAmount);if(E<=0n)throw new Error("Bridge amount is empty.");let R=await V(a),G=Ye(R?.gasFee??R?.gas_fee),Z=An(E,R?.exFeeRate??R?.ex_fee_rate),S=E+Z+G,[F,j]=await Promise.all([Ee(o,{address:w,abi:Tn,functionName:"name",chainId:_}),Ee(o,{address:w,abi:Tn,functionName:"nonces",args:[d],chainId:_})]),X=BigInt(Math.floor(Date.now()/1e3)+300),H=await or(o,{domain:{name:F,version:"1",chainId:_,verifyingContract:w},types:{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},primaryType:"Permit",message:{owner:d,spender:f.bridgeAddress,value:S,nonce:j,deadline:X}}),{r:l,s:b,v:T,yParity:P}=tr(H),B=T!==void 0?Number(T):P+27,pe={exFee:Z.toString(),from:_,fromToken:w,nonce:Number(j),gasFee:G.toString(),permitArgs:{account:d,deadline:X.toString(),r:l,s:b,token:w,v:B,value:S.toString()},to:d,toChainID:String(a.to.chainId),value:S.toString()},Ve=await xn(`${r.bridgeApi}/permit`,pe),nt=Ve?.requestId??Ve?.request_id;if(!nt)throw new Error("Bridge permit request failed.");let Ne=await xr(r.bridgeApi,nt);if(!qt(Ne))throw new Error("Bridge submitted, but confirmation timed out. Check History shortly.");return{txHash:Ne,fromToken:s.fromToken,toToken:s.toToken,fromAmount:s.fromAmount,toAmount:s.toAmount}},[r,V,o,t]),dt=re(async s=>{let a=Mt(o),d=fe(s.fromToken),f=fe(s.toToken),w=O(d,f);if(!w)throw new Error("Route is not available.");if(!(De(w.type)||w.type==="swap-bridge"||w.type==="bridge-swap"||w.type==="bridge"))throw new Error("This bridge route is not supported yet.");let R=w.type==="bridge"&&w.from.chainId===r.chainIds.bsc&&w.from.address.toLowerCase()===r.contracts.BSC_CROSS.toLowerCase()?await Me(s,w):await ue(s,w);return await He(a),{...R,pathType:w.type,routeTokens:es(w,D)}},[D,r,O,He,Me,ue,o]);return{bridgeTokens:ce,bridgeHistory:K,getBridgeApproval:Ae,approveBridge:ve,getBridgeQuote:ct,getBridgeToTokens:qe,submitBridge:dt,oneUsdPairs:Ie,isLoading:m.isLoading||h.isLoading||k.isLoading||x.isLoading||v.some(s=>s.isLoading)}}import{useEffect as Mn,useRef as ns,useState as Un}from"react";import{useAccount as os}from"wagmi";function Ht(e){let{address:t,connector:n}=os(),{currentWallet:i}=Be(),o=e?.walletId!==void 0?e.walletId:i,c=e?.connector!==void 0?e.connector:n,g=e?.address!==void 0?e.address:t,[y,u]=Un({loginType:null,accountName:null,accounts:[],isResolved:!1}),r=ns(new Map),[m,h]=Un(0);return Mn(()=>{let C=!1;if(o!=="cross_embedded")return u({loginType:null,accountName:null,accounts:[],isResolved:!0}),()=>{C=!0};if(!c)return u({loginType:null,accountName:null,accounts:[],isResolved:!1}),()=>{C=!0};u(v=>({...v,isResolved:!1}));let p=20,k=300,x=async()=>{if(typeof c.getProvider!="function")return"retry";let v;try{v=await c.getProvider()}catch{return"retry"}let W=v?.sdk;if(!W)return"giveup";try{let N=W.getRNBridgeActiveWallet?.(),A=N?.walletName?.trim();N&&A&&r.current.set(N.address.toLowerCase(),A)}catch{}let[I,U]=await Promise.all([W.getUserInfo?.().catch(()=>null)??null,W.getAddresses?.().catch(()=>null)??null]);if(C)return"done";let D=I?.loginType,O=D==="google"||D==="apple"?D:null;if(!O)return"retry";let q=g?.toLowerCase(),$=q&&Array.isArray(U)?U.find(N=>N.address.toLowerCase()===q):null,z=Array.isArray(U)?U.filter(N=>/^0x[a-fA-F0-9]{40}$/.test(N.address)).map(N=>({address:N.address.toLowerCase(),...Number.isFinite(N.index)?{index:N.index}:{},...N.name?.trim()?{name:N.name.trim()}:{}})):[],L=q?r.current.get(q)?.trim():void 0,K=!$&&q&&/^0x[a-fA-F0-9]{40}$/.test(q)?[...z,{address:q,index:z.length,...L?{name:L}:{}}]:z,de=L||$?.name?.trim()||(typeof $?.index=="number"?`Account ${$.index+1}`:g?`${g.slice(0,6)}\u2026${g.slice(-4)}`:null);return u({loginType:O,accountName:de,accounts:K,isResolved:!0}),"done"};return(async()=>{for(let v=0;v<p;v++){if(C)return;let W=await x();if(W==="done")return;if(W==="giveup"){C||u({loginType:null,accountName:null,accounts:[],isResolved:!0});return}await new Promise(I=>setTimeout(I,k))}C||u({loginType:null,accountName:null,accounts:[],isResolved:!0})})(),()=>{C=!0}},[o,c,g,m]),Mn(()=>{if(o!=="cross_embedded"||!c||typeof c.getProvider!="function")return;let C=!1,p;return(async()=>{let k;try{k=await c.getProvider()}catch{return}if(C)return;let x=k?.sdk;x?.on&&(p=x.on("addressChanged",({address:v,walletName:W})=>{let I=W?.trim();I&&(r.current.set(v.toLowerCase(),I),h(U=>U+1))}))})(),()=>{C=!0,p?.()}},[o,c]),y}import{Fragment as qn,jsx as ge,jsxs as it}from"react/jsx-runtime";var ys=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint8"}]}],bs=[{type:"function",name:"earned",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"posaActive",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bool"}]},{type:"function",name:"lastRewardBlock",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"totalStaked",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]}],hs={dev:{poolAddress:"0x0000000c5BB5C7B081237B5efaFC753D61201b94",crossChainId:612044,networkStatsUrl:"https://stg-posa-api.crosstoken.io/api/v1/network/stats"},stage:{poolAddress:"0x0000000c5BB5C7B081237B5efaFC753D61201b94",crossChainId:612044,networkStatsUrl:"https://stg-posa-api.crosstoken.io/api/v1/network/stats"},production:{poolAddress:"0x000000068122d9bB43B4BCF5497A10EdfA9F5E93",crossChainId:612055,networkStatsUrl:"https://posa-api.crosstoken.io/api/v1/network/stats"}},Qt=10n**18n,ws={google:{name:"Google",iconUrl:Vn,connectorId:Je.CROSSx},apple:{name:"Apple",iconUrl:Yt,connectorId:Je.CROSSx},cross:{name:kt.default,iconUrl:Xt,connectorId:Je.CROSSx},metamask:{name:"MetaMask",iconUrl:jn,connectorId:Je.MetaMask},binance:{name:"Binance Wallet",iconUrl:Hn,connectorId:Je.Binance}};function Cs(e){switch(e){case"cross_embedded":return Je.CROSSx;case"metamask":return Je.MetaMask;case"binance":return Je.Binance;default:return}}function ks(e,t){switch(e){case"cross_embedded":return t==="google"?{name:"Google",iconUrl:Vn}:t==="apple"?{name:"Apple",iconUrl:Yt}:{name:kt.default,iconUrl:Xt};case"cross_wallet":return{name:kt.default,iconUrl:Xt};case"cross_extension":return{name:kt.extension,iconUrl:gs};case"metamask":return{name:"MetaMask",iconUrl:jn};case"binance":return{name:"Binance Wallet",iconUrl:Hn};default:return null}}function Ts(e){if(e)return e==="cross_embedded"?kt.default:ps[e]?.name}function Is({label:e="Connect Wallet",className:t,style:n,walletInfoStyle:i,user:o,enablePortfolio:c,portfolio:g,theme:y,accountName:u,connectorId:r,showPortfolio:m,sendAccounts:h,getTransactionReceipt:C,sendTransaction:p,estimateGas:k,onDisconnect:x,onSelectWallet:v,onBuy:W,onRampRedirectUrl:I,bridgeTokens:U,bridgeHistory:D,getBridgeQuote:O,getBridgeToTokens:q,getBridgeApproval:$,approveBridge:z,submitBridge:L,showBalance:K=!0,env:Re,...de}){let{address:N,isConnected:A,connector:Y,chain:V}=is(),ce=cs(),Ie=as(),{switchChainAsync:qe}=ls(),{sendTransactionAsync:Oe}=ds(),{connectWallet:xe,disconnect:He,selectWallet:we,currentWallet:le,isConnecting:Ge,kitConfig:et}=Be(),ye=et?.restoreChainAfterSwitch!==!1,ct=yt(),tt=y??ct?.mode??"dark",Ae=Et(()=>us(Re),[Re]),ve=o?.address??N,ue=o?ws[o.provider]:null,{loginType:Me,accountName:dt,accounts:s}=Ht({walletId:le,connector:Y,address:ve}),a=Et(()=>ue?{name:ue.name,iconUrl:ue.iconUrl}:ks(le,Me),[ue,le,Me]),d=u??o?.name??dt??void 0,f=de.connectorName??(ue?ue.name:Ts(le)),w=ue?ue.connectorId:Cs(le),_=r??w,E=g??m??!!c,R=Ct({env:Ae,walletAddress:ve,enabled:A&&!!ve&&K,restoreChainAfterSwitch:ye}),G=U??R.bridgeTokens,Z=D??R.bridgeHistory,S=O??R.getBridgeQuote,F=q??R.getBridgeToTokens,j=$??R.getBridgeApproval,X=z??R.approveBridge,H=L??R.submitBridge,l=Ze(()=>{xe().catch(M=>{console.error("[crossx-kit] connectWallet error:",M)})},[xe]),b=Ze(()=>{He()},[He]),T=x??b,P=ms(),{eligibility:B}=fs({network:V?String(V.id):void 0}),pe=B?.allowed===!0,Ve=Et(()=>{if(W)return W;if(!(!P||!V||!pe))return()=>P.open({crypto:V.nativeCurrency?.symbol??"USDT",network:String(V.id),...I?{redirectUrl:I}:{}}).then(()=>{}).catch(M=>{throw console.warn("[crossx-kit] onramp open failed:",M),M})},[W,P,V,pe,I]),nt=ss();rs(()=>{if(P?.onStatus)return P.onStatus(()=>{nt.invalidateQueries()})},[P,nt]);let Ne=Et(()=>{if(!W&&!(!P||!V)&&!pe)return"On-ramp is not available in your region."},[W,P,V,pe]),je=de.onBridgeDisabledMessage,Ot=de.onSendDisabledMessage,to=o?o.provider==="google"||o.provider==="apple":le==="cross_embedded",no=Ze(()=>{we().catch(M=>{console.error("[crossx-kit] selectWallet error:",M)})},[we]),tn=v??(to?no:void 0),oo=Ze(async({hash:M,chainId:te})=>{let ne=Vt(ce,te?{chainId:te}:void 0);if(!ne)return null;try{return await ne.getTransactionReceipt({hash:M})}catch{return null}},[ce]),ro=Ze(async M=>{let te=Ie,ne=!1;M.chainId!==void 0&&M.chainId!==Ie&&(await qe({chainId:M.chainId}),ne=!0);let me=M.chainId===56||M.chainId===97?{...M,type:"legacy"}:M,J=await(p??Oe)(me);return await Pt({getChainId:()=>ne?M.chainId:te,switchChain:ke=>qe({chainId:ke})},te,ye),J},[p,Oe,Ie,qe,ye]),so=E||p?ro:void 0,io=Ze(async M=>{let te=M.chainId??Ie,ne=Vt(ce,te?{chainId:te}:void 0);if(!ne)throw new Error(`publicClient for chainId ${te??"unknown"} is not available \u2014 register the chain in createCrossxConfig({ networks }).`);let Ce=te===56||te===97,[me,Pe]=await Promise.all([ne.estimateGas({account:M.from,to:M.to,value:M.value,data:M.data}),(async()=>{if(Ce)return{maxFeePerGas:void 0,maxPriorityFeePerGas:void 0,gasPrice:await ne.getGasPrice()};try{let J=await ne.estimateFeesPerGas();return{maxFeePerGas:J.maxFeePerGas,maxPriorityFeePerGas:J.maxPriorityFeePerGas,gasPrice:void 0}}catch{return{maxFeePerGas:void 0,maxPriorityFeePerGas:void 0,gasPrice:await ne.getGasPrice()}}})()]);return{gasLimit:me,maxFeePerGas:Pe.maxFeePerGas,maxPriorityFeePerGas:Pe.maxPriorityFeePerGas,gasPrice:Pe.gasPrice}},[ce,Ie]),ao=k??io,co=Ze(async M=>{let te={};if(!N||M.length===0)return te;let ne=M.flatMap(me=>{let J={address:me,abi:ys,chainId:Ie};return[{...J,functionName:"balanceOf",args:[N]},{...J,functionName:"totalSupply"},{...J,functionName:"decimals"}]}),Ce;try{Ce=await Kn(ce,{contracts:ne,allowFailure:!0})}catch{return te}return M.forEach((me,Pe)=>{let J=Pe*3,ke=Ce[J],Tt=Ce[J+1],lt=Ce[J+2];!ke||ke.status!=="success"||(te[me.toLowerCase()]={balance:ke.result,totalSupply:Tt&&Tt.status==="success"?Tt.result:void 0,decimals:lt&<.status==="success"?Number(lt.result):void 0})}),te},[ce,N,Ie]),lo=Ze(async M=>{let te={earnedWei:0n,stakedWei:0n};if(!M)return te;let ne=hs[Ae],Ce={address:ne.poolAddress,abi:bs,chainId:ne.crossChainId},me;try{me=await Kn(ce,{allowFailure:!0,contracts:[{...Ce,functionName:"earned",args:[M]},{...Ce,functionName:"balanceOf",args:[M]},{...Ce,functionName:"posaActive"},{...Ce,functionName:"lastRewardBlock"},{...Ce,functionName:"totalStaked"}]})}catch{return te}let Pe=ot=>me[ot]&&me[ot].status==="success"?me[ot].result:0n,J=Pe(0),ke=Pe(1);if(me[2]&&me[2].status==="success"?me[2].result:!1)return{earnedWei:J,stakedWei:ke};let lt=Pe(3),rn=Pe(4);if(rn===0n)return{earnedWei:J,stakedWei:ke};let Nt=0n;try{Nt=await Vt(ce,{chainId:ne.crossChainId})?.getBlockNumber?.()??0n}catch{return{earnedWei:J,stakedWei:ke}}if(Nt<=lt)return{earnedWei:J,stakedWei:ke};let Wt=0n;try{let ot=await fetch(ne.networkStatsUrl).then(Ft=>Ft.json()),sn=ot?.data?.block_reward??ot?.block_reward;if(sn){let[Ft,fo=""]=String(sn).split("."),go=(fo+"0".repeat(18)).slice(0,18);Wt=BigInt(Ft||"0")*Qt+BigInt(go||"0")}}catch{}if(Wt===0n)return{earnedWei:J,stakedWei:ke};let po=(Nt-lt)*Wt*Qt/rn,mo=ke*po/Qt;return{earnedWei:J+mo,stakedWei:ke}},[ce,Ae]),nn=!tn,on=t?`cb-button ${t}`:"cb-button",uo=t?`cb-pill ${t}`:"cb-pill";return Ge&&!A?it(qn,{children:[ge("style",{children:zt}),it("button",{type:"button",disabled:!0,className:on,style:n,"aria-busy":"true",children:[ge("span",{className:"cb-spinner","aria-hidden":"true"}),ge("span",{className:"cb-button-label",children:"Connecting..."})]})]}):A&&ve?it("span",{"data-crossx-wallet-info":nn?"external":"embedded",children:[ge("style",{children:zt}),nn&&ge("style",{children:vs}),it(jt,{...de,env:Ae,theme:tt,showBalance:K,walletAddress:ve,accountName:d,sendAccounts:h??s,connectorName:f,connectorId:_,showPortfolio:E,onDisconnect:T,onSelectWallet:tn,onBuy:Ve,onBuyDisabledMessage:Ne,onBridgeDisabledMessage:je,onSendDisabledMessage:Ot,sendTransaction:so,getTransactionReceipt:C??oo,estimateGas:ao,lpBalanceReader:co,stakingRewardsReader:lo,bridgeTokens:G,bridgeHistory:Z,getBridgeQuote:S,getBridgeToTokens:F,getBridgeApproval:j,approveBridge:X,submitBridge:H,style:i,children:[ge(jt.Trigger,{asChild:!0,children:it("button",{type:"button",className:uo,style:n,"aria-label":`Connected with ${a?.name??"wallet"}: ${$n(ve)}`,children:[a?.iconUrl?ge("img",{src:a.iconUrl,alt:"",width:20,height:20,className:"cb-pill-icon","data-provider":a.iconUrl===Yt?"apple":void 0}):ge("span",{className:"cb-pill-icon-placeholder","aria-hidden":"true"}),ge("span",{className:"cb-pill-address",children:$n(ve)})]})}),ge(jt.Content,{align:"end",sideOffset:8})]})]}):it(qn,{children:[ge("style",{children:zt}),it("button",{type:"button",onClick:l,className:on,style:n,"aria-label":typeof e=="string"?e:"Connect Wallet",children:[ge(xs,{}),ge("span",{className:"cb-button-label",children:e})]})]})}function xs(){return ge("svg",{className:"cb-button-icon",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:ge("path",{d:"M11.4368 10.5007C11.4368 9.9538 11.6544 9.42855 12.041 9.04175C12.4278 8.65492 12.9529 8.4375 13.5 8.4375H15.1875V6.00073L15.1732 5.92822C15.1639 5.90585 15.15 5.88528 15.1326 5.8678C15.0973 5.83263 15.0494 5.81287 14.9996 5.81287H3.74963C3.4787 5.81287 3.21001 5.75949 2.95972 5.65576C2.90937 5.63488 2.86089 5.61017 2.8125 5.58545V14.2504C2.8125 14.4989 2.91141 14.7371 3.08716 14.9128C3.2629 15.0886 3.50109 15.1875 3.74963 15.1875H15.0007C15.0252 15.1875 15.0495 15.1826 15.0721 15.1732C15.0948 15.1638 15.1152 15.1499 15.1326 15.1326C15.1499 15.1152 15.1638 15.0948 15.1732 15.0721C15.1826 15.0495 15.1875 15.0252 15.1875 15.0007V12.5629H13.5C12.9529 12.5629 12.4278 12.3454 12.041 11.9586C11.6545 11.5719 11.4369 11.0475 11.4368 10.5007ZM12.5618 10.5007C12.5619 10.7491 12.6609 10.9875 12.8364 11.1632C13.0123 11.3391 13.2513 11.4379 13.5 11.4379H15.75C15.7998 11.4379 15.8477 11.4182 15.8829 11.3829C15.9182 11.3477 15.9379 11.2998 15.9379 11.25V9.75037C15.9379 9.70054 15.9182 9.65266 15.8829 9.61743C15.8477 9.5822 15.7998 9.5625 15.75 9.5625H13.5C13.2513 9.5625 13.0123 9.66131 12.8364 9.83716C12.6607 10.013 12.5618 10.2522 12.5618 10.5007ZM13.6879 3.00037C13.6879 2.95054 13.6682 2.90266 13.6329 2.86743C13.5977 2.8322 13.5498 2.8125 13.5 2.8125H3.74963C3.50109 2.8125 3.2629 2.91141 3.08716 3.08716C2.91141 3.2629 2.8125 3.50109 2.8125 3.74963L2.81689 3.84192C2.82585 3.93354 2.8486 4.02351 2.88391 4.10889C2.93096 4.22263 3.00015 4.32614 3.08716 4.41321C3.17403 4.50009 3.2769 4.56936 3.39038 4.61646C3.50412 4.66359 3.62651 4.68787 3.74963 4.68787H13.6879V3.00037ZM14.8129 4.68787H14.9996C15.3473 4.68787 15.6808 4.82576 15.9269 5.07129C16.173 5.31702 16.3119 5.65077 16.3125 5.99854V8.56494C16.4469 8.62873 16.5711 8.7148 16.6783 8.82202C16.9246 9.06823 17.0629 9.40217 17.0629 9.75037V11.25C17.0629 11.5982 16.9246 11.9321 16.6783 12.1783C16.5712 12.2855 16.4468 12.3706 16.3125 12.4343V14.9985L16.3059 15.1282C16.2934 15.2564 16.2619 15.3822 16.2125 15.5017C16.1466 15.6612 16.05 15.806 15.928 15.928C15.806 16.05 15.6612 16.1466 15.5017 16.2125C15.3425 16.2783 15.1719 16.3126 14.9996 16.3125H3.74963C3.20272 16.3125 2.67847 16.095 2.29175 15.7083C1.90502 15.3215 1.6875 14.7973 1.6875 14.2504V3.74963C1.6875 3.20272 1.90502 2.67847 2.29175 2.29175C2.67847 1.90502 3.20272 1.6875 3.74963 1.6875H13.5C13.8482 1.6875 14.1821 1.82581 14.4283 2.07202C14.6746 2.31823 14.8129 2.65217 14.8129 3.00037V4.68787Z",fill:"currentColor"})})}var vs=`
|
|
3
3
|
[data-crossx-wallet-info="external"] .wi-select-wallet-btn {
|
|
4
4
|
display: none !important;
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as ie,B as se,C as de,D as pe,E as ce,F as le,G as ue,H as fe,I as Ce,J as we,K as me,L as ge,M as ye,N as Ne,a as S,b as V,c as W,d as X,e as L,f as h,g as j,h as B,i as F,j as D,k as U,l as q,m as z,n as $,o as G,p as H,q as J,r as Q,s as Y,t as Z,u as ee,v as ne,w as te,x as oe,y as re,z as ae}from"./chunk-
|
|
1
|
+
import{A as ie,B as se,C as de,D as pe,E as ce,F as le,G as ue,H as fe,I as Ce,J as we,K as me,L as ge,M as ye,N as Ne,a as S,b as V,c as W,d as X,e as L,f as h,g as j,h as B,i as F,j as D,k as U,l as q,m as z,n as $,o as G,p as H,q as J,r as Q,s as Y,t as Z,u as ee,v as ne,w as te,x as oe,y as re,z as ae}from"./chunk-PEAZQ65Y.js";import{bscMainnetNetwork as v,bscTestnetNetwork as x,createCrossxConfig as E,crossMainnetNetwork as k,crossTestnetNetwork as O}from"@nexus-cross/connect-kit-wagmi";import{toNexusAdapter as A}from"@nexus-cross/connect-kit-wagmi/to-nexus";import{reownAdapter as M}from"@nexus-cross/connect-kit-wagmi/reown";import{embeddedConnectorFactory as P}from"@nexus-cross/connect-kit-wagmi/embedded";import{WALLET_BRAND_NAME as I}from"@nexus-cross/crossx-design-system";function d(e){try{return import.meta.env?.[e]}catch{return}}function p(e){if(!(typeof process>"u"))return process.env?.[e]}function K(){return d("VITE_CROSSX_ENVIRONMENT")??d("NEXT_PUBLIC_CROSSX_ENVIRONMENT")??p("NEXT_PUBLIC_CROSSX_ENVIRONMENT")??p("CROSSX_ENVIRONMENT")}function R(e){switch(e?.toLowerCase()){case"dev":case"development":return"development";case"stage":case"staging":case"stg":return"staging";default:return"production"}}function T(e){return e==="production"?[k,v]:[O,x]}function b(){let e=typeof window<"u"&&window.location?.origin?window.location.origin:"https://example.com";return{name:`${I} DApp`,url:e}}function _(e){let{app:c,appMetadata:l,networks:u,defaultNetwork:f,wallets:n,embedded:C=!0,environment:w,toNexus:t,reown:o,...r}=e,m=R(w??K()),i=u??T(m),a=Array.isArray(n)?null:n??"all",s=a!=="external-only"&&t!==!1,g=a!=="cross-only"&&o!==!1&&!!r.reownProjectId,y=t===!1?void 0:t,N=o===!1?void 0:o;if(a==="external-only"&&!r.reownProjectId)throw new Error('[crossx-kit] createConnectKitConfig({ wallets: "external-only" }) requires `reownProjectId`.');return E({...r,appMetadata:l??c??b(),networks:i,defaultNetwork:f??i[0],...Array.isArray(n)?{wallets:n}:{},...s?{crossProvider:A(y)}:{},...g?{reownProvider:M(N)}:{},...s&&C?{embeddedConnectorFactory:P}:{}})}export{ae as AppLauncher,se as AppLauncherContent,ie as AppLauncherTrigger,B as ConnectButton,ge as ConnectionStatus,re as ConnectorId,L as CrossConnectKitProvider,X as CrossConnectModal,q as CrossGetOneUsd,U as CrossRelayDeposit,z as CrossRelayHistory,$ as CrossRelayRecovery,ue as DEFAULT_TRUSTED_FACTORIES,ne as KycError,ee as KycProvider,me as OnRampError,Q as OnRampProvider,F as OtherWalletsModal,le as RelayApiError,pe as SkillsButton,oe as WalletInfo,_ as createConnectKitConfig,ce as createRelayClient,ye as formatBalance,Ne as formatWei,te as launchKycVerification,G as useConnectKitAnalytics,S as useCrossConnectKit,V as useCrossConnectKitTheme,h as useCrossdBridgeAdapter,j as useCrossxEmbeddedInfo,de as useGlobalMenu,Y as useKyc,H as useOnRamp,J as useOnRampEligibility,W as useOptionalCrossConnectKitTheme,Z as useOptionalKyc,fe as useRelayConfig,Ce as useRelayOrders,we as useRelayRecovery,D as useRelayWalletProps};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-
|
|
1
|
+
import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-PEAZQ65Y.js";export{z as AppLauncher,B as AppLauncherContent,A as AppLauncherTrigger,h as ConnectButton,L as ConnectionStatus,y as ConnectorId,e as CrossConnectKitProvider,d as CrossConnectModal,l as CrossGetOneUsd,k as CrossRelayDeposit,m as CrossRelayHistory,n as CrossRelayRecovery,G as DEFAULT_TRUSTED_FACTORIES,v as KycError,u as KycProvider,K as OnRampError,r as OnRampProvider,i as OtherWalletsModal,F as RelayApiError,D as SkillsButton,x as WalletInfo,E as createRelayClient,M as formatBalance,N as formatWei,w as launchKycVerification,o as useConnectKitAnalytics,a as useCrossConnectKit,b as useCrossConnectKitTheme,f as useCrossdBridgeAdapter,g as useCrossxEmbeddedInfo,C as useGlobalMenu,s as useKyc,p as useOnRamp,q as useOnRampEligibility,c as useOptionalCrossConnectKitTheme,t as useOptionalKyc,H as useRelayConfig,I as useRelayOrders,J as useRelayRecovery,j as useRelayWalletProps};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nexus-cross/connect-kit-react",
|
|
3
|
-
"version": "1.4.0-beta.
|
|
3
|
+
"version": "1.4.0-beta.6",
|
|
4
4
|
"description": "React components and hooks for @nexus-cross/connect-kit wallet connection",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -24,12 +24,12 @@
|
|
|
24
24
|
"access": "public"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@nexus-cross/connect-kit-core": "1.4.0-beta.
|
|
28
|
-
"@nexus-cross/connect-kit-wagmi": "1.4.0-beta.
|
|
29
|
-
"@nexus-cross/crossx-design-system": "1.4.0-beta.
|
|
30
|
-
"@nexus-cross/dapp-ui": "1.4.0-beta.
|
|
31
|
-
"@nexus-cross/
|
|
32
|
-
"@nexus-cross/
|
|
27
|
+
"@nexus-cross/connect-kit-core": "1.4.0-beta.6",
|
|
28
|
+
"@nexus-cross/connect-kit-wagmi": "1.4.0-beta.6",
|
|
29
|
+
"@nexus-cross/crossx-design-system": "1.4.0-beta.6",
|
|
30
|
+
"@nexus-cross/dapp-ui": "1.4.0-beta.6",
|
|
31
|
+
"@nexus-cross/kyc": "1.4.0-beta.6",
|
|
32
|
+
"@nexus-cross/onramp": "1.4.0-beta.6"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@tanstack/react-query": "^5.60.0",
|