@nexus-cross/connect-kit-react 1.3.3 → 1.3.4-beta.10

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.
@@ -0,0 +1,144 @@
1
+ var mt="1.3.4";var wt="__nexusCrossAppLauncherRuntime";function ro(){if(typeof window>"u")return null;let e=window;return e[wt]??(e[wt]={mode:"dapp-ui"}),e[wt]}function so(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??mt;console.info(`[CROSSx App Launcher] connect-kit-react v${n} \uCD08\uAE30\uD654 \uC644\uB8CC (dapp-ui v${mt}, \uC0AC\uC6A9 \uBAA8\uB4DC: connect-kit)`)}else console.info(`[CROSSx App Launcher] dapp-ui v${mt} \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 Zt(){let e=ro();e&&(e.mode="connect-kit-react",e.connectKitVersion=mt,so(e))}import{useCallback as Be,useEffect as le,useMemo as Le,useRef as He,useState as Ve}from"react";import{WagmiProvider as po,useAccount as fo,useChainId as go,useConnect as bo,useDisconnect as yo,useSwitchChain as ho}from"wagmi";import{QueryClient as wo,QueryClientProvider as Co}from"@tanstack/react-query";import{clearWalletSessionStorage as on,onOpenOtherWallets as ko,pickInitialState as To,resolveCurrentWallet as Io}from"@nexus-cross/connect-kit-wagmi";import{resolveThemeMode as xo}from"@nexus-cross/connect-kit-core";import{buildDesignSystemCss as So}from"@nexus-cross/crossx-design-system";import{OnRampProvider as vo}from"@nexus-cross/onramp/react";import{KycProvider as Po}from"@nexus-cross/kyc/react";import{createContext as io,useContext as ao}from"react";var Et=io(null);function We(){let e=ao(Et);if(!e)throw new Error("useCrossConnectKit must be used within <CrossConnectKitProvider>");return e}import{createContext as co,useContext as Jt}from"react";var Ct=co(null);function lo(){let e=Jt(Ct);if(!e)throw new Error("useCrossConnectKitTheme must be used within <CrossConnectKitProvider>");return e}function pt(){return Jt(Ct)}import{useCallback as uo,useMemo as en}from"react";import{WalletConnectModal as tn}from"@nexus-cross/dapp-ui";import{jsx as nn}from"react/jsx-runtime";var mo=new Set(["cross_wallet","cross_extension","metamask","binance"]);function _t({open:e,onOpenChange:t}){let{connect:n,availableWallets:i,oauth:o,extraWallets:c,walletAllowlist:p,kitConfig:b}=We(),r=pt()?.mode??"dark",C=en(()=>{let g=p?new Set(p):null,w={};for(let P of i){if(!mo.has(P.walletId)||g&&!g.has(P.walletId))continue;let v=P.walletId;w[v]=()=>{n(P.walletId)}}for(let[P,v]of Object.entries(c))v&&(g&&!g.has(P)||(w[P]=v));return w},[i,n,c,p]),T=en(()=>{if(o)return{apple:()=>{o.signIn("apple")},google:()=>{o.signIn("google")}}},[o]),I=uo(g=>t(g),[t]);return nn(tn,{wallets:C,socialProviders:T,termsUrl:b.legal?.termsUrl,privacyUrl:b.legal?.privacyUrl,theme:r,open:e,onOpenChange:I,children:nn(tn.Content,{})})}import{jsx as ot,jsxs as an}from"react/jsx-runtime";var Ao=new wo,Ot="crossx-kit:last-wallet-intent",Ro=15e3;function rn(e,t){return Promise.race([e.then(()=>{},()=>{}),new Promise(n=>setTimeout(n,t))])}function Bo(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 Eo(){if(typeof window>"u")return null;try{return window.localStorage.getItem(Ot)??null}catch{return null}}function sn(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Ot,e):window.localStorage.removeItem(Ot)}catch{}}function _o(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 Oo(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}function No({children:e,config:t,activeProvider:n,onRequestProviderSwap:i,pendingConnectWalletId:o,clearPending:c,themeMode:p,themeTokens:b,extraWallets:f,walletAllowlist:r}){let[C,T]=Ve(!1),[I,g]=Ve(()=>Eo()),[w,P]=Ve(null),{address:v,isConnected:x,isConnecting:N,isReconnecting:U,connector:B}=fo(),{connectors:V,connectAsync:j}=bo(),{disconnectAsync:M}=yo(),{kitConfig:F,connectorRegistry:G,crossProvider:ve,reownProvider:O}=t,E=n==="cross"?ve:O,W=Le(()=>!x||!B?null:Io(G,B.id,I),[x,B,G,I]),he=Le(()=>G.entries.filter(u=>u.type!=="embedded"),[G]),Ye=He(v);Ye.current=v;let X=F.embeddedProjectId?.trim()||F.crossProjectId?.trim(),ie=!!F.onRampEnabled&&!!X,we=Le(()=>!ie||!X?null:{projectId:X,walletState:{getAddress:()=>Ye.current}},[ie,X]),Ne=He(B);Ne.current=B;let Ce=F.embeddedProjectId?.trim()||F.crossProjectId?.trim(),Ue=!!F.kycEnabled&&!!Ce,fe=Le(()=>!Ue||!Ce?null:{projectId:Ce,getAccessToken:async()=>{let u=Ne.current;if(!(!u||typeof u.getProvider!="function"))try{return(await(await u.getProvider())?.sdk?.getUserInfo?.())?.data?.accessToken||void 0}catch{return}}},[Ue,Ce]);le(()=>ko(()=>T(!0)),[]),le(()=>{if(!C||typeof document>"u")return;let u=setTimeout(()=>{document.querySelectorAll("#__crossx-confirm-overlay").forEach(l=>l.remove())},50);return()=>clearTimeout(u)},[C]);let xe=He(x),ae=He(x);xe.current=x;let Ze=He(!1);le(()=>{console.debug("[crossx-kit] state",{activeProvider:n,isConnected:x,isConnecting:N,isReconnecting:U,activeConnectorId:B?.id,currentWallet:W,lastIntent:I})},[n,x,N,U,B?.id,W,I]),le(()=>{x&&!ae.current&&E?.closeModal?.({kitConfig:F}),ae.current=x},[x,E,F]),le(()=>{x&&P(null)},[x]);let Je=go(),{switchChainAsync:Ke}=ho(),$e=He(null);le(()=>{if(!F.enforceDefaultNetworkOnConnect)return;let u=F.defaultNetwork?.id;if(!u)return;if(!x||!v||!B){$e.current=null;return}let l=`${B.id}:${v}`;$e.current!==l&&($e.current=l,Je!==u&&Ke({chainId:u}).catch(()=>{}))},[F.enforceDefaultNetworkOnConnect,F.defaultNetwork,x,v,B,Je,Ke]);let ce=Be(u=>V.find(l=>l.id===u),[V]);le(()=>{let u=G.getEntry("cross_embedded");if(!u)return;let l=ce(u.connectorId);if(!l)return;let k=!1;return(async()=>{try{let h=await l.getProvider();if(k)return;h?.sdk?.applyTheme?.(p,b??void 0)}catch(h){console.debug("[crossx-kit] applyTheme skipped:",h)}})(),()=>{k=!0}},[G,ce,p,b]);let Pe=Be(u=>{g(u),sn(u)},[]),q=Be(()=>{g(null),sn(null),P(null)},[]);le(()=>{if(!E?.subscribeModalState)return;let u=!1;return E.subscribeModalState({kitConfig:F},l=>{if(Ze.current=l,l){u=!0;return}u&&(u=!1,setTimeout(()=>{xe.current||(async()=>{try{await M()}catch{}q()})()},250))})},[E,F,M,q]),le(()=>{if(!w||x||typeof window>"u"||w==="cross_embedded")return;let u=typeof document<"u"&&!document.hasFocus(),l=null,k=()=>{u=!0},h=()=>{u&&(l&&clearTimeout(l),l=setTimeout(()=>{xe.current||Ze.current||(async()=>{try{await M()}catch{}q()})()},1e3))};return window.addEventListener("blur",k),window.addEventListener("focus",h),()=>{window.removeEventListener("blur",k),window.removeEventListener("focus",h),l&&clearTimeout(l)}},[w,x,M,q]);let ge=Be(async u=>{console.debug("[crossx-kit] runConnect enter",{walletId:u,activeProvider:n,isConnected:x,activeConnectorId:B?.id});let l=G.getEntry(u);if(!l){if((u==="metamask"||u==="binance")&&!O){console.error(`[crossx-kit] "${u}" 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: "${u}"`);return}if(P(u),l.providerKind!==n){console.debug("[crossx-kit] provider swap needed",{from:n,to:l.providerKind,walletId:u}),Pe(u);try{await M()}catch{}await new Promise(h=>setTimeout(h,0)),i(l.providerKind,u);return}if(Pe(u),E?.beforeConnect)try{let h=await E.beforeConnect({kitConfig:F,themeMode:p},u);if(console.debug("[crossx-kit] beforeConnect result",{walletId:u,result:h}),h==="handled")return}catch(h){console.warn('[crossx-kit] adapter.beforeConnect threw for "%s":',u,h)}let k=ce(l.connectorId);if(console.debug("[crossx-kit] findConnector",{lookupId:l.connectorId,found:k?.id,availableIds:V.map(h=>h.id)}),!k){console.error(`[crossx-kit] Connector "${l.connectorId}" not found on provider "${l.providerKind}". Available: ${V.map(h=>h.id).join(", ")}`),q();return}try{console.debug("[crossx-kit] connectAsync start",{connectorId:k.id});let h=await j({connector:k});console.debug("[crossx-kit] connectAsync resolved",{accountsLen:h.accounts.length,chainId:h.chainId});return}catch(h){if(!Bo(h)){console.error('[crossx-kit] connectAsync error for "%s":',u,h);try{await M()}catch{}}if(!l.fallbackConnectorId){q();return}}if(l.fallbackConnectorId){let h=ce(l.fallbackConnectorId);if(h)try{await j({connector:h})}catch(L){console.error('[crossx-kit] Fallback connect failed for "%s":',u,L);try{await M()}catch{}q()}else q()}},[G,V,ce,j,M,Pe,q,E,n,F,i,p]);le(()=>{if(!o)return;let u=o;c(),ge(u)},[o,n]);let et=Be(async()=>{T(!0)},[]),s=Be(async()=>{try{await M()}catch(u){console.error("[crossx-kit] wagmi disconnect error:",u)}if(E?.teardown)try{await E.teardown({kitConfig:F})}catch(u){console.error("[crossx-kit] adapter teardown error:",u)}on(),q()},[M,E,F,q]),a=Be(async()=>{await rn(M(),3e3);try{let u=G.getEntry("cross_embedded"),l=u&&ce(u.connectorId);if(l?.getProvider){let k=await Promise.race([l.getProvider(),new Promise(L=>setTimeout(L,3e3))]),h=k?.sdk?.signOut;typeof h=="function"&&await rn(h.call(k.sdk),3e3)}}catch{}on()},[G,ce,M]),d=Be(async()=>{let u=G.getEntry("cross_embedded");if(!u)return null;let l=ce(u.connectorId);if(!l)return null;try{let k=await l.getProvider(),h=k?.sdk;if(!h?.selectWallet)return null;let L=await h.selectWallet(h.currentAddress??void 0);return L?.address&&k.notifyAccountsChanged&&k.notifyAccountsChanged([L.address]),L}catch{return null}},[G,ce]),m=Le(()=>{let u=t.oauth;return u?{signIn:async l=>{P("cross_embedded");try{await u.signIn(l)}catch(k){throw P(null),k}}}:null},[t.oauth]),y=He(!1);le(()=>{if(n!=="cross"||x||N||U||w!=null||y.current)return;let u=G.getEntry("cross_embedded");if(!u)return;let l=ce(u.connectorId);if(!l)return;y.current=!0;let k=!1;return(async()=>{try{let h=await l.isAuthorized?.();if(k||!h)return;await j({connector:l})}catch{}})(),()=>{k=!0}},[n,x,N,U,w,G,ce,j]),le(()=>{if(w!=="cross_embedded"||x||typeof window>"u")return;let u=!document.hasFocus(),l=()=>{u=!0};window.addEventListener("blur",l);let k=setTimeout(()=>{xe.current||u||(console.warn("[crossx-kit] embedded sign-in stalled before the OAuth popup opened \u2014 clearing the stale session so a retry starts clean"),q(),a())},Ro);return()=>{window.removeEventListener("blur",l),clearTimeout(k)}},[w,x,q,a]);let A=w!=null&&!x,R=Le(()=>({kitConfig:F,connectorRegistry:G,availableWallets:he,connect:ge,connectWallet:et,disconnect:s,selectWallet:d,currentWallet:W,lastIntent:I,isConnecting:A,connectingWalletId:w,openOtherWallets:()=>T(!0),closeOtherWallets:()=>T(!1),otherWalletsOpen:C,oauth:m,extraWallets:f,walletAllowlist:r,onRampEnabled:ie}),[F,G,he,ge,et,s,d,W,I,A,w,C,m,f,r,ie]),_=an(Et.Provider,{value:R,children:[e,ot(_t,{open:C,onOpenChange:T})]});return fe&&(_=ot(Po,{config:fe,children:_})),we&&(_=ot(vo,{config:we,children:_})),_}var Fo=[/Connection interrupted while trying to subscribe/i,/No matching key\. subscription:/i,/Proposal expired/i];function Wo(e){let t=e?.message;return typeof t!="string"?!1:Fo.some(n=>n.test(t))}var Lo={};function Do(e){return e&&{...e,connections:new Map,current:null}}function Mo({children:e,config:t,initialState:n,extraWallets:i=Lo,walletAllowlist:o}){let[c,p]=Ve(()=>_o(t.activeProviderStorageKey,t.defaultProvider)),[b,f]=Ve(null),r=He(!1),{kitConfig:C}=t,[T,I]=Ve(null),[g,w]=Ve(null),[P,v]=Ve(0),x=Le(()=>xo(C.theme,C.autoDetectTheme),[C.theme,C.autoDetectTheme,P]),N=T??x,U=g??C.themeTokens;le(()=>{if(!C.autoDetectTheme||T||typeof window>"u"||!window.matchMedia)return;let O=window.matchMedia("(prefers-color-scheme: dark)"),E=()=>v(W=>W+1);try{return O.addEventListener("change",E),()=>O.removeEventListener("change",E)}catch{return O.addListener(E),()=>O.removeListener(E)}},[C.autoDetectTheme,T]),le(()=>{if(typeof document>"u")return;let O=document.documentElement,E=O.getAttribute("data-ds-theme"),W=O.getAttribute("data-theme");return O.setAttribute("data-ds-theme",N),W||O.setAttribute("data-theme",N),()=>{E==null?O.removeAttribute("data-ds-theme"):O.setAttribute("data-ds-theme",E),W==null&&O.removeAttribute("data-theme")}},[N]);let B=Le(()=>So(t.designSystem),[t.designSystem]),V=Le(()=>({mode:N,tokens:U,setThemeMode:O=>I(O),setThemeTokens:O=>w(O)}),[N,U]);le(()=>{if(typeof window>"u")return;let O=E=>{Wo(E.reason)&&E.preventDefault()};return window.addEventListener("unhandledrejection",O),()=>window.removeEventListener("unhandledrejection",O)},[]);let j=Be((O,E)=>{r.current||(r.current=!0,f(E),p(O),Oo(t.activeProviderStorageKey,O),queueMicrotask(()=>{r.current=!1}))},[t.activeProviderStorageKey]),M=Be(()=>f(null),[]),F=c==="cross"?t.crossWagmiConfig:t.reownWagmiConfig,G=Do(To(n,c));if(!F){if(!(c==="cross"?t.reownWagmiConfig:t.crossWagmiConfig))throw new Error("[crossx-kit] createCrossxConfig returned no wagmi Config for either side");let E=c==="cross"?"reown":"cross";queueMicrotask(()=>p(E))}let ve=F??(c==="cross"?t.reownWagmiConfig:t.crossWagmiConfig);return an(Ct.Provider,{value:V,children:[ot("style",{"data-crossx-design-system":"",children:B}),ot(po,{config:ve,initialState:G,children:ot(Co,{client:Ao,children:ot(No,{config:t,activeProvider:c,onRequestProviderSwap:j,pendingConnectWalletId:b,clearPending:M,themeMode:N,themeTokens:U,extraWallets:i,walletAllowlist:o??t.kitConfig.wallets??null,children:e})})},c)]})}import{useCallback as ze,useEffect as qr,useMemo as yt}from"react";import{useQueryClient as Hr}from"@tanstack/react-query";import{useAccount as Vr,useChainId as jr,useConfig as Qr,useSendTransaction as zr,useSwitchChain as Xr}from"wagmi";import{getPublicClient as Ut,readContracts as On}from"wagmi/actions";import{WalletInfo as Kt,ConnectorId as Xe,resolveEnvironment as Yr}from"@nexus-cross/dapp-ui";import{useOptionalOnRamp as Zr,useOptionalOnRampEligibility as Jr}from"@nexus-cross/onramp/react";import{APPLE_ICON as Vt,BINANCE_ICON as Wn,CROSSX_ICON as Ht,EXTENSION_ICON as es,GOOGLE_ICON as Ln,METAMASK_ICON as Dn}from"@nexus-cross/connect-kit-wagmi";import{useCallback as te,useMemo as Te,useRef as Go}from"react";import{useQueries as ln,useQuery as je}from"@tanstack/react-query";import{encodeFunctionData as ft,formatUnits as vt,parseSignature as Uo,parseUnits as Ko}from"viem";import{getChainId as Nt,getPublicClient as xn,readContract as Se,signTypedData as $o,switchChain as un,waitForTransactionReceipt as qo,writeContract as mn}from"wagmi/actions";import{useConfig as Ho}from"wagmi";async function kt(e,t,n){if(!(!n||t===void 0))try{if(e.getChainId()===t)return;await e.switchChain(t)}catch{}}var dt=10000n;function cn(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 Tt(e,t){let n=cn(t);return n>=dt?0n:e*(dt-n)/dt}function dn(e,t){let n=cn(t);return(e*(dt+n)+(dt-1n))/dt}function Vo(e){return e!=="bridge"}var Ge="0x0000000000000000000000000000000000000000",Ie=100,ut=18,jo=180000n,Qo=250000n,Sn=new Set([56,97]),zo=130n,Xo=100n,Yo={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"},Zo={dev:"dev",stage:"stg",production:"prod"};function Jo(e,t){let n=e?.[Zo[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 er={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"},tr=["BSC_CROSS","W_CROSS","NATIVE_CROSS","USDTX","CROSSD","USDTB","SWAP_BRIDGE_ROUTER"],nr={BSC_CROSS:Ge,W_CROSS:Ge,NATIVE_CROSS:Ge,USDTX:Ge,CROSSD:Ge,USDTB:Ge,SWAP_BRIDGE_ROUTER:Ge},or=/^0x[0-9a-fA-F]{40}$/;function rr(e,t){let n=typeof e=="string"?e:e?.[t];return typeof n=="string"&&or.test(n)?n:null}function sr(e,t){if(!e?.bridge)return null;let n=e.envToNetwork?.[t]??(t==="production"?"mainnet":"testnet"),i={};for(let o of tr){let c=rr(e.bridge[o],n);if(!c)return null;i[o]=c}return i}var ir={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"}]}],Ft=[{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"}]}],pn=[{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"}]}],fn=[{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"}]}],ar=[{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"}]}],De=[{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:[]}],cr=[{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 vn(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 Ee(e,t){let n=await fetch(e,{cache:"no-store",signal:t});if(!n.ok)throw new Error(`CrossD bridge adapter request failed: ${await vn(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 gn(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 vn(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 dr(e){return new Promise(t=>setTimeout(t,e))}async function lr(e,t,{attempts:n=60,intervalMs:i=2e3}={}){for(let o=0;o<n;o+=1){try{let c=await Ee(`${e}/permit-hash/${t}`);if(Dt(c))return c}catch{}await dr(i)}return null}function oe(e,t){return`${e}-${t.toLowerCase()}`}function ue(e){return oe(e.chainId,e.address)}function _e(e){return e==="swap"||e==="deposit-swap"||e==="swap-withdraw"}function ur(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
+ `)[0]?.trim()||"Failed to quote bridge."}function bn(e){return e===56||e===97?"BSC":e===612044||e===612055?"CROSS":`Chain ${e}`}function ne(e,t){return t?t.toLowerCase()===e.contracts.NATIVE_CROSS.toLowerCase()?e.contracts.W_CROSS:t:Ge}function st(e){let t=vt(e,ut);return t.includes(".")?t.replace(/\.?0+$/,""):t}function bt(e){return Ko(e||"0",ut)}function pe(e){try{return bt(e||"0")}catch{return 0n}}function Qe(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 Wt(e){let t=vt(e,9);return(t.includes(".")?t.replace(/\.?0+$/,""):t)||"0"}function It(e){return e==="bridge"?jo:Qo}function yn(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 p=c/1000000n,b=(c%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return b?`${p}.${b}`:`${p}`}function mr(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 hn(e,t,n,i,o,c=!1){let p=xn(e,{chainId:t}),b=n;try{let r=await p?.estimateContractGas?.({account:o.account,address:o.address,abi:o.abi,functionName:o.functionName,args:o.args,value:o.value});typeof r=="bigint"&&r>0n&&(b=i?r*zo/Xo:r)}catch{}let f={gas:b};if(Sn.has(t))try{let r=await p?.getGasPrice?.();typeof r=="bigint"&&r>0n&&(f.gasPrice=r)}catch{}else if(c)try{let r=await p?.estimateFeesPerGas?.();typeof r?.maxFeePerGas=="bigint"&&(f.maxFeePerGas=r.maxFeePerGas),typeof r?.maxPriorityFeePerGas=="bigint"&&(f.maxPriorityFeePerGas=r.maxPriorityFeePerGas)}catch{}return f}function gt(){return BigInt(Math.floor(Date.now()/1e3)+1800)}var pr={100:"0.01%",500:"0.05%",3e3:"0.3%",1e4:"1%"};function fr(e){return pr[e]??`${e/1e4}%`}function gr(e,t){let n=Number(e||"0");return!Number.isFinite(n)||n<=0?"0":(n*t/1e6).toFixed(8).replace(/\.?0+$/,"")}function wn(e){return st(e)}function Cn(e,t){let n=Number(t??"0");return!Number.isFinite(n)||n<=0?0n:e*BigInt(Math.floor(n))/1000n}function xt(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=>xt(t,o.from)&&xt(n,o.to)||xt(t,o.to)&&xt(n,o.from))}function yr(e){if(_e(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 hr({input:e,path:t,config:n}){if(!n||_e(t.type))return"";let i=Qe(n.minimumValue),o=Qe(n.gasFee??n.gas_fee),c=t.type==="swap-bridge"?i+o*12n/10n:i;return c<=0n?"":e.fromAmount&&pe(e.fromAmount)<c&&t.type!=="swap"?`Minimum ${wn(c)}`:t.type==="swap-bridge"&&e.toAmount&&pe(e.toAmount)<c?`Available ${wn(c)} or more.`:""}function wr({input:e,path:t,config:n}){if(!n||t.type!=="bridge"&&t.type!=="bridge-swap")return"";let i=Qe(n.gasFee??n.gas_fee);if(i<=0n||!e.fromAmount)return"";let o=pe(e.fromToken.balance||"0"),c=pe(e.fromAmount);return o-i<c?`Insufficient network fee(${e.fromToken.symbol})`:""}function Cr(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,p])=>{p.forEach(b=>{b.localToken&&n.add(oe(o,b.localToken)),b.remoteToken&&n.add(oe(Number(c),b.remoteToken))})})}),Object.entries(t?.swapPools||t?.swap_pools||{}).forEach(([i,o])=>{o.forEach(c=>{c.token0&&n.add(oe(Number(i),c.token0)),c.token1&&n.add(oe(Number(i),c.token1))})}),n}function kr(e,t){return!e||!t?null:oe(e,t)}function Tr({envConfig:e,bridgePairList:t,swapPools:n,tokenInfo:i,tokenStats:o}){let c=Cr(t,n),p=new Map;o?.forEach(f=>{let r=kr(Number(f.chainId??f.chain_id),f.address);r&&p.set(r,f)});let b={};return c.forEach(f=>{let[r,C]=f.split("-"),T=Number(r),I=i?.find(w=>Number(w.chainId??w.chain_id)===T&&w.address?.toLowerCase()===C);if(!I?.symbol||!I.name)return;let g=p.get(f);b[f]={key:f,chainId:T,address:C,symbol:I.symbol,name:I.name,decimals:I.decimals||ut,image:I.image||I.icon_url,price:g?.price?Number(g.price):void 0,isNativeToken:C.toLowerCase()===e.contracts.NATIVE_CROSS.toLowerCase()}}),b}function Pn(e,t){return t?.list?.find(n=>(n.localChain??n.local_chain)===e)?.bridge||""}function An(e,t,n){let[i,o]=e.split("-"),[c,p]=t.split("-"),b=Number(i),f=Number(c);for(let r of n?.list||[]){if((r.localChain??r.local_chain)!==b)continue;let C=r.pairs?.[c];if(C){for(let T of C)if(T.localToken?.toLowerCase()===o&&T.remoteToken?.toLowerCase()===p)return{type:"bridge",fromChain:b,fromToken:o,toChain:f,toToken:p,bridgeAddress:Pn(b,n)}}}return null}function Rn(e,t,n,i){let o,c=1/0;for(let p of e||[]){let b=i(p.token0),f=i(p.token1);if(b===t&&f===n||f===t&&b===n){let r=p.fee??Ie;r<c&&(o=p,c=r)}}return o?{fee:c,poolAddress:o.poolAddress||o.pool_address||""}:null}function Bn(e,t,n,i){let[o,c]=e.split("-"),[p,b]=t.split("-");if(o!==p)return null;let f=Number(o),r=(n?.swapPools||n?.swap_pools)?.[o];if(!r)return null;let C=i.contracts.W_CROSS.toLowerCase(),T=i.contracts.NATIVE_CROSS.toLowerCase(),g=Rn(r,c,b,P=>P?.toLowerCase()===C?T:P?.toLowerCase());if(!g)return null;let w="swap";return f===i.chainIds.cross&&(c===T&&(w="deposit-swap"),b===T&&(w="swap-withdraw")),{pathType:w,step:{type:"swap",chain:f,fromToken:c,toToken:b,fee:g.fee,poolAddress:g.poolAddress}}}function Ir(e,t,n,i){let[o,c]=e.split("-"),[p]=t.split("-");if(o===p)return null;let b=(n?.swapPools||n?.swap_pools)?.[o]||[],f=r=>r?.toLowerCase();for(let r of b){let C=f(r.token0),T=f(r.token1),I=C===c?T:T===c?C:null;if(!I)continue;let g=An(oe(Number(o),I),t,i);if(!g)continue;let w=Rn(b,c,I,f);return[{type:"swap",chain:Number(o),fromToken:c,toToken:I,fee:w?.fee??Ie,poolAddress:w?.poolAddress??""},g]}return null}function xr(e,t,n,i,o){let[c,p]=e.split("-"),[b]=t.split("-");if(c===b)return null;for(let f of n?.list||[])if((f.localChain??f.local_chain)===Number(c))for(let r of f.pairs?.[b]||[]){if(r.localToken?.toLowerCase()!==p)continue;let C=r.remoteToken?.toLowerCase();if(!C)continue;let T=Bn(oe(Number(b),C),t,i,o);if(T)return[{type:"bridge",fromChain:Number(c),fromToken:p,toChain:Number(b),toToken:C,bridgeAddress:Pn(Number(c),n)},T.step]}return null}function Sr({envConfig:e,bridgePairList:t,swapPools:n,enrichedTokens:i}){return(o,c)=>{let p=i[o],b=i[c];if(!p||!b||o===c)return null;let f=An(o,c,t);if(f)return{type:"bridge",steps:[f],from:p,to:b};let r=Bn(o,c,n,e);if(r)return{type:r.pathType,steps:[r.step],from:p,to:b};let C=Ir(o,c,n,t);if(C)return{type:"swap-bridge",steps:C,from:p,to:b};let T=xr(o,c,t,n,e);return T?{type:"bridge-swap",steps:T,from:p,to:b}:null}}function kn(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 vr(e){return e.length<=10?e:`${e.slice(0,6)}...${e.slice(-4)}`}function Pr(e){return e.includes(".")?e.replace(/\.?0+$/,"")||"0":e}function Ar(e,t){let n=e.startsWith("-"),i=n?e.slice(1):e,[o,c=""]=i.split("."),p=c.slice(0,t).replace(/0+$/,""),b=p?`${o}.${p}`:o;return n?`-${b}`:b}function Rr(e){let t=e.startsWith("-"),n=t?e.slice(1):e,[i,o]=n.split("."),c=i.replace(/\B(?=(\d{3})+(?!\d))/g,","),p=o?`${c}.${o}`:c;return t?`-${p}`:p}function Lt(e){if(e==null||e==="")return"0";let t=String(e),n=Number(t);return!Number.isFinite(n)||n===0?"0":Rr(Ar(t,4))}function Tn(e,t){if(e==null||e==="")return"0";try{return Pr(vt(BigInt(String(e)),t.decimals))}catch{return"0"}}function Dt(e){return!!(e&&/^0x[0-9a-fA-F]+$/.test(e))}function Br(e){return e?new Date(e*1e3).toISOString():new Date().toISOString()}function Er(e,t){return t.toLowerCase()===e.contracts.W_CROSS.toLowerCase()?e.contracts.NATIVE_CROSS:t}function _r(e,t){let n=vr(t);return{name:n,symbol:n,chainId:e,address:t,decimals:ut,balance:"0"}}function In({envConfig:e,tokenByBridgeKey:t,chainId:n,address:i}){if(!i)return null;let o=Er(e,i);return t.get(oe(n,o))||t.get(oe(n,i))||_r(n,o)}function St(e){return e?.toLowerCase()||""}function Or(e){if(e.source==="swap")return"swap";let t=St(e.fromToken??e.from_token),n=St(e.toToken??e.to_token),i=St(e.swapTokenIn??e.swap_token_in),o=St(e.swapTokenOut??e.swap_token_out);return n&&i&&n===i?"bridge-swap":t&&o&&t===o?"swap-bridge":"bridge"}function Nr(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 Fr({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=Or(t),p=t.swapTokenIn??t.swap_token_in,b=t.swapTokenOut??t.swap_token_out,f=t.swapAmountIn??t.swap_amount_in,r=t.swapAmountOut??t.swap_amount_out,C=t.fromToken??t.from_token,T=t.toToken??t.to_token,I=t.value,g=t.value;c==="swap"?(C=p,T=b,I=f,g=r):c==="swap-bridge"?(C=p,I=f,g=t.value):c==="bridge-swap"&&(T=b,I=f,g=r);let w=In({envConfig:e,tokenByBridgeKey:n,chainId:i,address:C}),P=In({envConfig:e,tokenByBridgeKey:n,chainId:o,address:T}),v=t.initiatedTxHash??t.initiated_tx_hash;return!w||!P||!Dt(v)?null:{id:`${v}-${t.index??""}`,timestamp:Br(t.initiatedTime??t.initiated_time),txHash:v,fromToken:w,toToken:P,fromAmount:Tn(I,w),toAmount:Tn(g,P),summary:{pathType:c},status:Nr(t,c)}}function Wr(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",p=n.quantity?.decimals??n.decimals??ut;try{t.set(oe(i,o),vt(BigInt(c||"0"),p))}catch{t.set(oe(i,o),"0")}}),t}function Me(e,t="first"){let n=e.steps.filter(i=>i.type==="swap");return t==="last"?n[n.length-1]:n[0]}function Lr(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(p=>{let b=p.token0?.toLowerCase(),f=p.token1?.toLowerCase();return b===i&&f===o||b===o&&f===i});return c?.poolAddress||c?.pool_address||""}function Dr(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 Mr(e){if(e===void 0)return;let t=10n**BigInt(ut),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 lt(e,t,n,i){let o=[e.from,e.to].find(c=>c.chainId===t&&c.address.toLowerCase()===n.toLowerCase())??i?.[oe(t,n)];return{symbol:o?.symbol||n.slice(0,6),iconUrl:o?.image}}function Gr(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=>lt(e,o.chain,o.address,t))}function Ur({input:e,path:t,amountData:n,gasInfo:i,liquidity:o,enrichedTokens:c,priceImpact:p}){let b=e.fromAmount||"0",f=e.toAmount||"0",r=Me(t),C=t.steps.find(U=>U.type==="bridge"),T=t.type!=="bridge",I=!_e(t.type),g=r?gr(b,r.fee):"0",w=Number(b)>0||Number(f)>0,P=r?lt(t,r.chain,r.fromToken,c):{symbol:e.fromToken.symbol,iconUrl:e.fromToken.iconUrl},v=r?lt(t,r.chain,r.toToken,c):{symbol:e.toToken.symbol,iconUrl:e.toToken.iconUrl},x=C?lt(t,C.fromChain,C.fromToken,c):void 0,N=(U,B,V)=>w?B&&B>0n?{label:U,value:st(B),tone:"default",valueToken:V}:{label:U,value:"Free",tone:"accent"}:{label:U,value:"0"};return{pathType:t.type,priceImpact:p,liquidity:o,bridgeInfo:I&&C?[{label:"Route",value:`${bn(C.fromChain)} \u2192 ${bn(C.toChain)}`},N("Validator Fee",n?.exFee,x),N("Network Fee",n?.networkFee,x)]:void 0,swapInfo:T&&r?[{label:"Route",value:"",routeTokens:[lt(t,r.chain,r.fromToken,c),lt(t,r.chain,r.toToken,c)]},{label:"Price Impact",value:mr(p)},{label:"In Amount",value:Lt(b),valueToken:P},{label:r&&_e(t.type)?`Swap Fee (${fr(r.fee??Ie)})`:"Swap Fee",value:Lt(g),valueToken:P},{label:"Out Amount",value:Lt(f),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 Mt({env:e,walletAddress:t,enabled:n=!0,restoreChainAfterSwitch:i=!0}){let o=Ho(),c=Go(new Map),b=je({queryKey:["crossd-bridge-adapter",e,"remote-contracts"],queryFn:async({signal:s})=>{let a=sr(await Ee(er[e],s),e);if(!a)throw new Error("CrossD bridge adapter: invalid contracts.json");return a},enabled:n,staleTime:5*6e4}).data??null,f=n&&!!b,r=Te(()=>({...ir[e],contracts:b??nr}),[e,b]),C=je({queryKey:["crossd-bridge-adapter",e,"pairs"],queryFn:({signal:s})=>Ee(`${r.bridgeApi}/pairs`,s),enabled:f,staleTime:3e4}),T=je({queryKey:["crossd-bridge-adapter",e,"swap-pools"],queryFn:({signal:s})=>Ee(`${r.bridgeApi}/swap-pools`,s),enabled:f,staleTime:3e4}),I=Te(()=>Lr(T.data,r),[r,T.data]),g=je({queryKey:["crossd-bridge-adapter",e,"available-liquidity",I],queryFn:async()=>await Se(o,{address:r.contracts.USDTX,abi:Ft,functionName:"balanceOf",args:[I],chainId:r.chainIds.cross}),enabled:f&&!!I,staleTime:3e4}),w=je({queryKey:["crossd-bridge-adapter",e,"token-info"],queryFn:({signal:s})=>Ee(`${r.walletApi}/v1/public/token/info`,s),enabled:f,staleTime:3e4}),P=je({queryKey:["crossd-bridge-adapter",e,"token-stats"],queryFn:({signal:s})=>Ee(`${r.walletApi}/v1/public/token/stats`,s),enabled:f,staleTime:3e4}),v=ln({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 Ee(`${r.walletApi}/v1/public/token/balance?${d}`,a)},enabled:f&&!!t,staleTime:0,refetchInterval:f&&t?5e3:!1}))}),x=ln({queries:[r.chainIds.cross,r.chainIds.bsc].map(s=>({queryKey:["crossd-bridge-adapter",e,"gas-suggestion",s],queryFn:async({signal:a})=>{try{let y=await xn(o,{chainId:s})?.estimateFeesPerGas?.();if(y?.maxFeePerGas||y?.gasPrice)return{fast:{maxFee:y.maxFeePerGas?.toString()||y.gasPrice?.toString(),maxPriorityFee:y.maxPriorityFeePerGas?.toString()||"0"}}}catch{}let d=new URLSearchParams({chain_id:String(s),without_gas_limit:"false"});return Ee(`${r.walletApi}/v1/public/transaction/gas-suggestion/dynamic?${d}`,a)},enabled:f,staleTime:1e4,retry:1}))}),N=je({queryKey:["crossd-bridge-adapter",e,"hidden-pairs"],queryFn:async({signal:s})=>Jo(await Ee(Yo[e],s),e),enabled:f,staleTime:5*6e4,retry:1}),U=Te(()=>N.data??[],[N.data]),B=Te(()=>Tr({envConfig:r,bridgePairList:C.data,swapPools:T.data,tokenInfo:w.data,tokenStats:P.data}),[C.data,r,T.data,w.data,P.data]),V=Te(()=>Sr({envConfig:r,bridgePairList:C.data,swapPools:T.data,enrichedTokens:B}),[C.data,B,r,T.data]),j=Te(()=>Wr(v.map(s=>s.data).filter(s=>Array.isArray(s))),[v]),M=Te(()=>{let s=new Map;return Object.values(B).forEach(a=>{let d=kn(a,j);s.set(a.key,d)}),s},[j,B]),F=Te(()=>{let s=new Map,a=M.get(oe(r.chainIds.cross,r.contracts.NATIVE_CROSS));a&&s.set(r.chainIds.cross,{symbol:a.symbol,iconUrl:a.iconUrl});let d=w.data?.find(m=>Number(m.chainId??m.chain_id)===r.chainIds.bsc&&(m.symbol??"").toUpperCase()==="BNB");return d&&s.set(r.chainIds.bsc,{symbol:d.symbol??"BNB",iconUrl:d.image??d.icon_url}),s},[r,M,w.data]),G=je({queryKey:["crossd-bridge-adapter",e,"history",t],queryFn:({signal:s})=>gn(`${r.bridgeApi}/history`,{owner:t,page:1,size:20,sort:"desc",status:"all"},s),enabled:f&&!!t,staleTime:0,refetchInterval:f&&t?5e3:!1}),ve=Te(()=>(G.data?.histories||[]).map(s=>Fr({envConfig:r,item:s,tokenByBridgeKey:M})).filter(s=>!!s),[G.data?.histories,r,M]),O=Te(()=>Mr(g.data),[g.data]),E=x[0]?.data,W=x[1]?.data,he=Te(()=>{let s=new Map;return E&&s.set(r.chainIds.cross,E),W&&s.set(r.chainIds.bsc,W),s},[W,E,r.chainIds.bsc,r.chainIds.cross]),Ye=te((s,a,d)=>{let m=he.get(s.from.chainId)?.fast,y=a?d?.gasLimit??It(s.type):0n,A=d?.gasPrice&&d.gasPrice>0n?d.gasPrice:0n,R=d?.maxFeePerGas&&d.maxFeePerGas>0n?d.maxFeePerGas:0n,S=d?.maxPriorityFeePerGas&&d.maxPriorityFeePerGas>0n?d.maxPriorityFeePerGas:0n,_=Qe(m?.maxFee??m?.max_fee),u=Qe(m?.maxPriorityFee??m?.max_priority_fee),l=R>0n?R:_>0n?_:A,k=S>0n?S:u>0n?u:l,h=A>0n?A:l,L=Sn.has(s.from.chainId)&&h>0n,J=y*(L?h:l),re=M.get(oe(s.from.chainId,r.contracts.NATIVE_CROSS)),H=s.type!=="swap-bridge",K=F.get(s.from.chainId);return{estTxFee:a?st(J):"0",priorityFeePerGas:a&&!L?Wt(k):"0",maxFeePerGas:a&&!L?Wt(l):"0",gasLimit:a?y.toString():"0",gasPrice:a&&L?Wt(h):void 0,isDelegateFee:s.type==="swap-bridge"?!1:br(r,s.from.address,s.to.address),tokenIconUrl:H?re?.iconUrl:void 0,tokenSymbol:H?re?.symbol:void 0,gasCurrencyIconUrl:K?.iconUrl,gasCurrencySymbol:K?.symbol}},[r,he,F,M]),X=te(async s=>{let a=yr(s);if(!a)return null;let d=`${e}:${a.from}:${a.to}:${a.token.toLowerCase()}`,m=c.current.get(d);if(m)return m;let y=(async()=>{let A=new URLSearchParams({from:String(a.from),to:String(a.to),token:a.token});try{return(await Ee(`${r.bridgeApi}/token-config?${A}`)).config??null}catch{return null}})();return c.current.set(d,y),y},[e,r.bridgeApi]),ie=Te(()=>{let s=Object.values(B).map(d=>kn(d,j)),a=oe(r.chainIds.cross,r.contracts.CROSSD);return s.sort((d,m)=>{let y=ue(d).toLowerCase()===a.toLowerCase(),A=ue(m).toLowerCase()===a.toLowerCase();return y!==A?y?-1:1:ue(d).localeCompare(ue(m))})},[j,B,r]),we=te(s=>{let a=ue(s),d=a.toLowerCase(),m=[];Object.keys(B).forEach(R=>{let S=R.toLowerCase();if(d===S||U.some(l=>l.fromKey===d&&l.toKey===S))return;let _=V(a,R);if(!_)return;let u=M.get(R);u&&m.push({token:u,path:_})});let y=oe(r.chainIds.cross,r.contracts.CROSSD),A=oe(r.chainIds.cross,r.contracts.NATIVE_CROSS);return m.sort((R,S)=>{if(d===y.toLowerCase()){let h=ue(R.token).toLowerCase()===A.toLowerCase(),L=ue(S.token).toLowerCase()===A.toLowerCase();if(h!==L)return h?-1:1}let _=_e(R.path.type),u=_e(S.path.type);if(_!==u)return _?-1:1;let l=R.token.chainId===s.chainId,k=S.token.chainId===s.chainId;return l!==k?l?-1:1:ue(R.token).localeCompare(ue(S.token))}),m.map(R=>R.token)},[B,r,V,U,M]),Ne=te(async s=>await Se(o,{address:r.contracts.SWAP_BRIDGE_ROUTER,abi:rt,functionName:"quoter",chainId:s}),[r.contracts.SWAP_BRIDGE_ROUTER,o]),Ce=te(async s=>{Nt(o)!==s&&await un(o,{chainId:s})},[o]),Ue=te(s=>kt({getChainId:()=>Nt(o),switchChain:a=>un(o,{chainId:a})},s,i),[i,o]),fe=te(async s=>await Se(o,{address:r.contracts.SWAP_BRIDGE_ROUTER,abi:rt,functionName:"swapRouter",chainId:s}),[r.contracts.SWAP_BRIDGE_ROUTER,o]),xe=te(async({path:s,step:a,amount:d,source:m})=>{let y=await Ne(a.chain),A=a.poolAddress?Se(o,{address:a.poolAddress,abi:ar,functionName:"slot0",chainId:a.chain}).then(_=>_?.[0]).catch(()=>{}):Promise.resolve(void 0);if(m==="from"){let _=await Se(o,{address:y,abi:fn,functionName:"quoteExactInputSingle",args:[{tokenIn:ne(r,a.fromToken),tokenOut:ne(r,a.toToken),amountIn:bt(d),fee:a.fee??Ie,sqrtPriceLimitX96:0n}],chainId:a.chain}),u=yn(await A,_[1]);return{amount:st(_[0]),path:s,priceImpact:u}}let R=await Se(o,{address:y,abi:fn,functionName:"quoteExactOutputSingle",args:[{tokenIn:ne(r,a.fromToken),tokenOut:ne(r,a.toToken),amount:bt(d),fee:a.fee??Ie,sqrtPriceLimitX96:0n}],chainId:a.chain}),S=yn(await A,R[1]);return{amount:st(R[0]),path:s,priceImpact:S}},[r,Ne,o]),ae=te(async(s,a)=>{if(!t)throw new Error("Wallet is not connected.");let d=It(a.type);if(_e(a.type)){let l=Me(a,"first");if(!l)throw new Error("Swap route is not available.");let k=pe(s.fromAmount),h=pe(s.toAmount);if(k<=0n)throw new Error("Bridge amount is empty.");if(h<=0n)throw new Error("Bridge quote is not ready.");let L=await fe(l.chain),Y=Tt(h,s.slippage),J=a.type==="swap-withdraw"?Ge:t,re={tokenIn:ne(r,l.fromToken),tokenOut:ne(r,l.toToken),fee:l.fee??Ie,recipient:J,deadline:gt(),amountIn:k,amountOutMinimum:Y,sqrtPriceLimitX96:0n};if(a.type==="swap-withdraw"){let H=ft({abi:De,functionName:"exactInputSingle",args:[re]}),K=ft({abi:De,functionName:"unwrapWETH9",args:[Y,t]});return{address:L,abi:De,functionName:"multicall",args:[[H,K]],chainId:l.chain,fallbackGasLimit:d}}if(a.type==="deposit-swap"){let H=ft({abi:De,functionName:"exactInputSingle",args:[re]}),K=ft({abi:De,functionName:"refundETH",args:[]});return{address:L,abi:De,functionName:"multicall",args:[[H,K]],value:k,chainId:l.chain,fallbackGasLimit:d}}return{address:L,abi:De,functionName:"exactInputSingle",args:[re],chainId:l.chain,fallbackGasLimit:d}}if(a.type==="swap-bridge"){let l=Me(a,"first");if(!l)throw new Error("Swap bridge route is not available.");let k=pe(s.fromAmount),h=pe(s.toAmount);if(k<=0n)throw new Error("Bridge amount is empty.");if(h<=0n)throw new Error("Bridge quote is not ready.");let L=r.contracts.SWAP_BRIDGE_ROUTER,Y=gt(),J={toChainID:BigInt(a.to.chainId),recipient:t,extraData:"0x"},re={tokenIn:ne(r,a.from.address),tokenOut:ne(r,l.toToken),fee:l.fee??Ie,sqrtPriceLimitX96:0n,bridgeParams:J};if(s.lastChangedBy==="to"){let K={...re,amountOut:h,amountInMaximum:dn(k,s.slippage)};return{address:L,abi:rt,functionName:"swapBridgeExactOutputSingle",args:[K,Y],value:a.from.isNativeToken?K.amountInMaximum:void 0,chainId:a.from.chainId,fallbackGasLimit:d}}let H={...re,amountIn:k,amountOutMinimum:Tt(h,s.slippage)};return{address:L,abi:rt,functionName:"swapBridgeExactInputSingle",args:[H,Y],value:a.from.isNativeToken?k:void 0,chainId:a.from.chainId,fallbackGasLimit:d}}let m=a.steps.find(l=>l.type==="bridge");if(!m?.bridgeAddress)throw new Error("Bridge route is not available.");let y=pe(s.fromAmount);if(y<=0n)throw new Error("Bridge amount is empty.");let A=await X(a),R=Qe(A?.gasFee??A?.gas_fee),S=Cn(y,A?.exFeeRate??A?.ex_fee_rate),_="0x";if(a.type==="bridge-swap"){let l=Me(a,"last");if(!l)throw new Error("Bridge swap route is not available.");let k=pe(s.toAmount);if(k<=0n)throw new Error("Bridge quote is not ready.");let h=await fe(a.to.chainId),L=Tt(k,s.slippage),Y=ft({abi:De,functionName:"exactInputSingle",args:[{tokenIn:ne(r,l.fromToken),tokenOut:ne(r,l.toToken),fee:l.fee??Ie,recipient:t,deadline:gt(),amountIn:y,amountOutMinimum:L,sqrtPriceLimitX96:0n}]});_=`${h}${Y.slice(2)}`}let u=[BigInt(a.to.chainId),a.from.address,t,y,R,S,_];return{address:m.bridgeAddress,abi:cr,functionName:"bridgeToken",args:u,value:a.from.isNativeToken?y+S+R:void 0,chainId:a.from.chainId,fallbackGasLimit:d}},[r,X,fe,t]),Ze=te(async(s,a)=>{if(a.type==="bridge"||a.type==="bridge-swap")return ae(s,a);if(!t)throw new Error("Wallet is not connected.");let d=pe(s.fromAmount);if(d<=0n)throw new Error("Bridge amount is empty.");if(a.type==="swap-bridge"){let R=Me(a,"first");if(!R)throw new Error("Swap bridge route is not available.");let S=r.contracts.SWAP_BRIDGE_ROUTER,_={tokenIn:ne(r,a.from.address),tokenOut:ne(r,R.toToken),fee:R.fee??Ie,sqrtPriceLimitX96:0n,bridgeParams:{toChainID:BigInt(a.to.chainId),recipient:t,extraData:"0x"},amountIn:d,amountOutMinimum:0n};return{address:S,abi:rt,functionName:"swapBridgeExactInputSingle",args:[_,gt()],value:a.from.isNativeToken?d:void 0,chainId:a.from.chainId,fallbackGasLimit:It(a.type)}}let m=Me(a,"first");if(!m)throw new Error("Swap route is not available.");let y=await fe(m.chain),A={tokenIn:ne(r,m.fromToken),tokenOut:ne(r,m.toToken),fee:m.fee??Ie,recipient:t,deadline:gt(),amountIn:d,amountOutMinimum:0n,sqrtPriceLimitX96:0n};return{address:y,abi:De,functionName:"exactInputSingle",args:[A],value:a.from.isNativeToken?d:void 0,chainId:m.chain,fallbackGasLimit:It(a.type)}},[ae,r,fe,t]),Je=te(async(s,a)=>{if(!t)return null;try{let d=await Ze(s,a),m=_e(a.type)||a.type==="swap-bridge",y=await hn(o,d.chainId,d.fallbackGasLimit,m,{account:t,address:d.address,abi:d.abi,functionName:d.functionName,args:d.args,value:d.value},!0);return{gasLimit:y.gas,gasPrice:y.gasPrice,maxFeePerGas:y.maxFeePerGas,maxPriorityFeePerGas:y.maxPriorityFeePerGas}}catch{return null}},[Ze,o,t]),Ke=te(async s=>{let a=ue(s.fromToken),d=ue(s.toToken),m=V(a,d);if(!m)return{error:"Route is not available."};let y=s.lastChangedBy==="to"?s.toAmount:s.fromAmount,A=!!y&&Number(y)>0,R=Dr(m,r)?O:void 0,S=async(Y,J,re)=>{let H=A?await Je(Y,m):null,K=Ye(m,A,H);return Ur({input:Y,path:m,gasInfo:K,amountData:J,liquidity:R,enrichedTokens:B,priceImpact:re})};if(!y||Number(y)<=0)return{fromAmount:s.fromAmount,toAmount:s.toAmount,summary:await S(s)};let _=await X(m),u=Qe(_?.gasFee??_?.gas_fee),l=m.type==="bridge"||m.type==="bridge-swap"?{networkFee:u}:void 0,k=m.type==="bridge"?s.lastChangedBy==="to"?{...s,fromAmount:s.toAmount}:{...s,toAmount:s.fromAmount}:s,h=hr({input:k,path:m,config:_});if(h)return{fromAmount:k.fromAmount,toAmount:k.toAmount,summary:await S(k,l),error:h};let L=wr({input:k,path:m,config:_});if(L)return{fromAmount:k.fromAmount,toAmount:k.toAmount,summary:await S(k,l),error:L};if(m.type==="bridge")return{fromAmount:k.fromAmount,toAmount:k.toAmount,summary:await S(k,l)};try{if(m.type==="swap-bridge"){let H=Me(m,"first"),K=r.contracts.SWAP_BRIDGE_ROUTER;if(!H)return{error:"Swap bridge route is not ready."};let at=Re=>xe({path:m,step:H,amount:Re,source:"from"}).then(Fe=>Fe.priceImpact).catch(()=>{});if(s.lastChangedBy==="from"){let Re=await Se(o,{address:K,abi:rt,functionName:"getAmountSwapBridgeOut",args:[BigInt(m.to.chainId),ne(r,m.from.address),ne(r,H.toToken),H.fee??Ie,bt(s.fromAmount)],chainId:m.from.chainId}),Fe=st(Re[1]),Pt={...s,toAmount:Fe};return{toAmount:Fe,summary:await S(Pt,{networkFee:Re[3],exFee:Re[4]},await at(s.fromAmount))}}let Ae=await Se(o,{address:K,abi:rt,functionName:"getAmountSwapBridgeIn",args:[BigInt(m.to.chainId),ne(r,m.from.address),ne(r,H.toToken),H.fee??Ie,bt(s.toAmount)],chainId:m.from.chainId}),qe=st(Ae[1]),tt={...s,fromAmount:qe};return{fromAmount:qe,summary:await S(tt,{networkFee:Ae[3],exFee:Ae[4]},await at(qe))}}let Y=m.type==="bridge-swap"?Me(m,"last"):Me(m,"first");if(!Y)return{error:"Swap route is not available."};let J=await xe({path:m,step:Y,amount:y,source:s.lastChangedBy});if(s.lastChangedBy==="from"){let H={...s,toAmount:J.amount};return{toAmount:J.amount,summary:await S(H,l,J.priceImpact)}}let re={...s,fromAmount:J.amount};return{fromAmount:J.amount,summary:await S(re,l,J.priceImpact)}}catch(Y){return{fromAmount:s.fromAmount,toAmount:s.toAmount,summary:await S(s,l),error:ur(Y)}}},[O,Ye,B,r,Je,V,X,xe,o]),$e=te(async s=>{if(s.from.isNativeToken)return null;if(s.type==="swap"||s.type==="deposit-swap"||s.type==="swap-withdraw")return fe(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,fe]),ce=te(async s=>{if(!t)throw new Error("Wallet is not connected.");let a=ue(s.fromToken),d=ue(s.toToken),m=V(a,d);if(!m)throw new Error("Route is not available.");if(!_e(m.type)&&m.type!=="swap-bridge"||m.from.isNativeToken)return null;let y=pe(s.fromAmount);if(y<=0n)return null;let A=await $e(m);return!A||await Se(o,{address:m.from.address,abi:Ft,functionName:"allowance",args:[t,A],chainId:m.from.chainId})>=y?null:{token:s.fromToken,tokenAddress:m.from.address,spenderAddress:A,amount:s.fromAmount}},[V,$e,o,t]),Pe=te(async(s,a)=>{let d=pe(a.amount||s.fromAmount);if(d<=0n)throw new Error("Approval amount is empty.");await Ce(a.token.chainId);let m=await mn(o,{address:a.tokenAddress,abi:Ft,functionName:"approve",args:[a.spenderAddress,d],chainId:a.token.chainId});await qo(o,{hash:m,chainId:a.token.chainId})},[Ce,o]),q=te(async(s,a)=>{let d=await ae(s,a);await Ce(d.chainId);let m=await hn(o,d.chainId,d.fallbackGasLimit,Vo(a.type),{account:t,address:d.address,abi:d.abi,functionName:d.functionName,args:d.args,value:d.value});return{txHash:await mn(o,{address:d.address,abi:d.abi,functionName:d.functionName,args:d.args,value:d.value,chainId:d.chainId,...m}),fromToken:s.fromToken,toToken:s.toToken,fromAmount:s.fromAmount,toAmount:s.toAmount}},[ae,Ce,o,t]),ge=te(async(s,a)=>{let d=t;if(!d)throw new Error("Wallet is not connected.");let m=a.steps.find(Fe=>Fe.type==="bridge");if(!m?.bridgeAddress)throw new Error("Bridge route is not available.");let y=a.from.address,A=a.from.chainId,R=pe(s.fromAmount);if(R<=0n)throw new Error("Bridge amount is empty.");let S=await X(a),_=Qe(S?.gasFee??S?.gas_fee),u=Cn(R,S?.exFeeRate??S?.ex_fee_rate),l=R+u+_,[k,h]=await Promise.all([Se(o,{address:y,abi:pn,functionName:"name",chainId:A}),Se(o,{address:y,abi:pn,functionName:"nonces",args:[d],chainId:A})]),L=BigInt(Math.floor(Date.now()/1e3)+300),Y=await $o(o,{domain:{name:k,version:"1",chainId:A,verifyingContract:y},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:m.bridgeAddress,value:l,nonce:h,deadline:L}}),{r:J,s:re,v:H,yParity:K}=Uo(Y),at=H!==void 0?Number(H):K+27,Ae={exFee:u.toString(),from:A,fromToken:y,nonce:Number(h),gasFee:_.toString(),permitArgs:{account:d,deadline:L.toString(),r:J,s:re,token:y,v:at,value:l.toString()},to:d,toChainID:String(a.to.chainId),value:l.toString()},qe=await gn(`${r.bridgeApi}/permit`,Ae),tt=qe?.requestId??qe?.request_id;if(!tt)throw new Error("Bridge permit request failed.");let Re=await lr(r.bridgeApi,tt);if(!Dt(Re))throw new Error("Bridge submitted, but confirmation timed out. Check History shortly.");return{txHash:Re,fromToken:s.fromToken,toToken:s.toToken,fromAmount:s.fromAmount,toAmount:s.toAmount}},[r,X,o,t]),et=te(async s=>{let a=Nt(o),d=ue(s.fromToken),m=ue(s.toToken),y=V(d,m);if(!y)throw new Error("Route is not available.");if(!(_e(y.type)||y.type==="swap-bridge"||y.type==="bridge-swap"||y.type==="bridge"))throw new Error("This bridge route is not supported yet.");let S=y.type==="bridge"&&y.from.chainId===r.chainIds.bsc&&y.from.address.toLowerCase()===r.contracts.BSC_CROSS.toLowerCase()?await ge(s,y):await q(s,y);return await Ue(a),{...S,pathType:y.type,routeTokens:Gr(y,B)}},[B,r,V,Ue,ge,q,o]);return{bridgeTokens:ie,bridgeHistory:ve,getBridgeApproval:ce,approveBridge:Pe,getBridgeQuote:Ke,getBridgeToTokens:we,submitBridge:et,isLoading:C.isLoading||T.isLoading||w.isLoading||P.isLoading||v.some(s=>s.isLoading)}}import{useEffect as En,useRef as Kr,useState as _n}from"react";import{useAccount as $r}from"wagmi";function Gt(e){let{address:t,connector:n}=$r(),{currentWallet:i}=We(),o=e?.walletId!==void 0?e.walletId:i,c=e?.connector!==void 0?e.connector:n,p=e?.address!==void 0?e.address:t,[b,f]=_n({loginType:null,accountName:null,accounts:[],isResolved:!1}),r=Kr(new Map),[C,T]=_n(0);return En(()=>{let I=!1;if(o!=="cross_embedded")return f({loginType:null,accountName:null,accounts:[],isResolved:!0}),()=>{I=!0};if(!c)return f({loginType:null,accountName:null,accounts:[],isResolved:!1}),()=>{I=!0};f(v=>({...v,isResolved:!1}));let g=20,w=300,P=async()=>{if(typeof c.getProvider!="function")return"retry";let v;try{v=await c.getProvider()}catch{return"retry"}let x=v?.sdk;if(!x)return"giveup";try{let W=x.getRNBridgeActiveWallet?.(),he=W?.walletName?.trim();W&&he&&r.current.set(W.address.toLowerCase(),he)}catch{}let[N,U]=await Promise.all([x.getUserInfo?.().catch(()=>null)??null,x.getAddresses?.().catch(()=>null)??null]);if(I)return"done";let B=N?.loginType,V=B==="google"||B==="apple"?B:null;if(!V)return"retry";let j=p?.toLowerCase(),M=j&&Array.isArray(U)?U.find(W=>W.address.toLowerCase()===j):null,F=Array.isArray(U)?U.filter(W=>/^0x[a-fA-F0-9]{40}$/.test(W.address)).map(W=>({address:W.address.toLowerCase(),...Number.isFinite(W.index)?{index:W.index}:{},...W.name?.trim()?{name:W.name.trim()}:{}})):[],G=j?r.current.get(j)?.trim():void 0,ve=!M&&j&&/^0x[a-fA-F0-9]{40}$/.test(j)?[...F,{address:j,index:F.length,...G?{name:G}:{}}]:F,E=G||M?.name?.trim()||(typeof M?.index=="number"?`Account ${M.index+1}`:p?`${p.slice(0,6)}\u2026${p.slice(-4)}`:null);return f({loginType:V,accountName:E,accounts:ve,isResolved:!0}),"done"};return(async()=>{for(let v=0;v<g;v++){if(I)return;let x=await P();if(x==="done")return;if(x==="giveup"){I||f({loginType:null,accountName:null,accounts:[],isResolved:!0});return}await new Promise(N=>setTimeout(N,w))}I||f({loginType:null,accountName:null,accounts:[],isResolved:!0})})(),()=>{I=!0}},[o,c,p,C]),En(()=>{if(o!=="cross_embedded"||!c||typeof c.getProvider!="function")return;let I=!1,g;return(async()=>{let w;try{w=await c.getProvider()}catch{return}if(I)return;let P=w?.sdk;P?.on&&(g=P.on("addressChanged",({address:v,walletName:x})=>{let N=x?.trim();N&&(r.current.set(v.toLowerCase(),N),T(U=>U+1))}))})(),()=>{I=!0,g?.()}},[o,c]),b}import{Fragment as Fn,jsx as me,jsxs as it}from"react/jsx-runtime";var ts=[{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"}]}],ns=[{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"}]}],os={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"}},$t=10n**18n,rs={google:{name:"Google",iconUrl:Ln,connectorId:Xe.CROSSx},apple:{name:"Apple",iconUrl:Vt,connectorId:Xe.CROSSx},cross:{name:"CROSSx",iconUrl:Ht,connectorId:Xe.CROSSx},metamask:{name:"MetaMask",iconUrl:Dn,connectorId:Xe.MetaMask},binance:{name:"Binance Wallet",iconUrl:Wn,connectorId:Xe.Binance}};function ss(e){switch(e){case"cross_embedded":return Xe.CROSSx;case"metamask":return Xe.MetaMask;case"binance":return Xe.Binance;default:return}}function is(e,t){switch(e){case"cross_embedded":return t==="google"?{name:"Google",iconUrl:Ln}:t==="apple"?{name:"Apple",iconUrl:Vt}:{name:"CROSSx",iconUrl:Ht};case"cross_wallet":return{name:"CROSSx Wallet",iconUrl:Ht};case"cross_extension":return{name:"CROSSx Extension",iconUrl:es};case"metamask":return{name:"MetaMask",iconUrl:Dn};case"binance":return{name:"Binance Wallet",iconUrl:Wn};default:return null}}var as="Bridge is available only with the CROSSx 2.0 wallet.",cs="Send is available only with the CROSSx 2.0 wallet.";function ds({label:e="Connect Wallet",className:t,style:n,walletInfoStyle:i,user:o,enablePortfolio:c,portfolio:p,theme:b,accountName:f,connectorId:r,showPortfolio:C,sendAccounts:T,getTransactionReceipt:I,sendTransaction:g,estimateGas:w,onDisconnect:P,onSelectWallet:v,onBuy:x,onRampRedirectUrl:N,bridgeTokens:U,bridgeHistory:B,getBridgeQuote:V,getBridgeToTokens:j,getBridgeApproval:M,approveBridge:F,submitBridge:G,showBalance:ve=!0,env:O,...E}){let{address:W,isConnected:he,connector:Ye,chain:X}=Vr(),ie=Qr(),we=jr(),{switchChainAsync:Ne}=Xr(),{sendTransactionAsync:Ce}=zr(),{connectWallet:Ue,disconnect:fe,selectWallet:xe,currentWallet:ae,isConnecting:Ze,kitConfig:Je}=We(),Ke=Je?.restoreChainAfterSwitch!==!1,$e=pt(),ce=b??$e?.mode??"dark",Pe=yt(()=>Yr(O),[O]),q=o?.address??W,ge=o?rs[o.provider]:null,{loginType:et,accountName:s,accounts:a}=Gt({walletId:ae,connector:Ye,address:q}),d=yt(()=>ge?{name:ge.name,iconUrl:ge.iconUrl}:is(ae,et),[ge,ae,et]),m=f??o?.name??s??void 0,y=ge?ge.connectorId:ss(ae),A=r??y,R=p??C??!!c,S=Mt({env:Pe,walletAddress:q,enabled:he&&!!q&&ve,restoreChainAfterSwitch:Ke}),_=U??S.bridgeTokens,u=B??S.bridgeHistory,l=V??S.getBridgeQuote,k=j??S.getBridgeToTokens,h=M??S.getBridgeApproval,L=F??S.approveBridge,Y=G??S.submitBridge,J=ze(()=>{Ue().catch(D=>{console.error("[crossx-kit] connectWallet error:",D)})},[Ue]),re=ze(()=>{fe()},[fe]),H=P??re,K=Zr(),{eligibility:at}=Jr({network:X?String(X.id):void 0}),Ae=at?.allowed===!0,qe=yt(()=>{if(x)return x;if(!(!K||!X||!Ae))return()=>K.open({crypto:X.nativeCurrency?.symbol??"USDT",network:String(X.id),...N?{redirectUrl:N}:{}}).then(()=>{}).catch(D=>{throw console.warn("[crossx-kit] onramp open failed:",D),D})},[x,K,X,Ae,N]),tt=Hr();qr(()=>{if(K?.onStatus)return K.onStatus(()=>{tt.invalidateQueries()})},[K,tt]);let Re=yt(()=>{if(!x&&!(!K||!X)&&!Ae)return"On-ramp is not available in your region."},[x,K,X,Ae]),Fe=yt(()=>o?o.provider==="google"||o.provider==="apple":ae==="cross_embedded",[o,ae]),Pt=E.onBridgeDisabledMessage??(Fe?void 0:as),$n=E.onSendDisabledMessage??(Fe?void 0:cs),qn=o?o.provider==="google"||o.provider==="apple":ae==="cross_embedded",Hn=ze(()=>{xe().catch(D=>{console.error("[crossx-kit] selectWallet error:",D)})},[xe]),jt=v??(qn?Hn:void 0),Vn=ze(async({hash:D,chainId:Z})=>{let ee=Ut(ie,Z?{chainId:Z}:void 0);if(!ee)return null;try{return await ee.getTransactionReceipt({hash:D})}catch{return null}},[ie]),jn=ze(async D=>{let Z=we,ee=!1;D.chainId!==void 0&&D.chainId!==we&&(await Ne({chainId:D.chainId}),ee=!0);let de=D.chainId===56||D.chainId===97?{...D,type:"legacy"}:D,Q=await(g??Ce)(de);return await kt({getChainId:()=>ee?D.chainId:Z,switchChain:ye=>Ne({chainId:ye})},Z,Ke),Q},[g,Ce,we,Ne,Ke]),Qn=R||g?jn:void 0,zn=ze(async D=>{let Z=D.chainId??we,ee=Ut(ie,Z?{chainId:Z}:void 0);if(!ee)throw new Error(`publicClient for chainId ${Z??"unknown"} is not available \u2014 register the chain in createCrossxConfig({ networks }).`);let be=Z===56||Z===97,[de,ke]=await Promise.all([ee.estimateGas({account:D.from,to:D.to,value:D.value,data:D.data}),(async()=>{if(be)return{maxFeePerGas:void 0,maxPriorityFeePerGas:void 0,gasPrice:await ee.getGasPrice()};try{let Q=await ee.estimateFeesPerGas();return{maxFeePerGas:Q.maxFeePerGas,maxPriorityFeePerGas:Q.maxPriorityFeePerGas,gasPrice:void 0}}catch{return{maxFeePerGas:void 0,maxPriorityFeePerGas:void 0,gasPrice:await ee.getGasPrice()}}})()]);return{gasLimit:de,maxFeePerGas:ke.maxFeePerGas,maxPriorityFeePerGas:ke.maxPriorityFeePerGas,gasPrice:ke.gasPrice}},[ie,we]),Xn=w??zn,Yn=ze(async D=>{let Z={};if(!W||D.length===0)return Z;let ee=D.flatMap(de=>{let Q={address:de,abi:ts,chainId:we};return[{...Q,functionName:"balanceOf",args:[W]},{...Q,functionName:"totalSupply"},{...Q,functionName:"decimals"}]}),be;try{be=await On(ie,{contracts:ee,allowFailure:!0})}catch{return Z}return D.forEach((de,ke)=>{let Q=ke*3,ye=be[Q],ht=be[Q+1],ct=be[Q+2];!ye||ye.status!=="success"||(Z[de.toLowerCase()]={balance:ye.result,totalSupply:ht&&ht.status==="success"?ht.result:void 0,decimals:ct&&ct.status==="success"?Number(ct.result):void 0})}),Z},[ie,W,we]),Zn=ze(async D=>{let Z={earnedWei:0n,stakedWei:0n};if(!D)return Z;let ee=os[Pe],be={address:ee.poolAddress,abi:ns,chainId:ee.crossChainId},de;try{de=await On(ie,{allowFailure:!0,contracts:[{...be,functionName:"earned",args:[D]},{...be,functionName:"balanceOf",args:[D]},{...be,functionName:"posaActive"},{...be,functionName:"lastRewardBlock"},{...be,functionName:"totalStaked"}]})}catch{return Z}let ke=nt=>de[nt]&&de[nt].status==="success"?de[nt].result:0n,Q=ke(0),ye=ke(1);if(de[2]&&de[2].status==="success"?de[2].result:!1)return{earnedWei:Q,stakedWei:ye};let ct=ke(3),Xt=ke(4);if(Xt===0n)return{earnedWei:Q,stakedWei:ye};let At=0n;try{At=await Ut(ie,{chainId:ee.crossChainId})?.getBlockNumber?.()??0n}catch{return{earnedWei:Q,stakedWei:ye}}if(At<=ct)return{earnedWei:Q,stakedWei:ye};let Rt=0n;try{let nt=await fetch(ee.networkStatsUrl).then(Bt=>Bt.json()),Yt=nt?.data?.block_reward??nt?.block_reward;if(Yt){let[Bt,no=""]=String(Yt).split("."),oo=(no+"0".repeat(18)).slice(0,18);Rt=BigInt(Bt||"0")*$t+BigInt(oo||"0")}}catch{}if(Rt===0n)return{earnedWei:Q,stakedWei:ye};let eo=(At-ct)*Rt*$t/Xt,to=ye*eo/$t;return{earnedWei:Q+to,stakedWei:ye}},[ie,Pe]),Qt=!jt,zt=t?`cb-button ${t}`:"cb-button",Jn=t?`cb-pill ${t}`:"cb-pill";return Ze&&!he?it(Fn,{children:[me("style",{children:qt}),it("button",{type:"button",disabled:!0,className:zt,style:n,"aria-busy":"true",children:[me("span",{className:"cb-spinner","aria-hidden":"true"}),me("span",{className:"cb-button-label",children:"Connecting..."})]})]}):he&&q?it("span",{"data-crossx-wallet-info":Qt?"external":"embedded",children:[me("style",{children:qt}),Qt&&me("style",{children:us}),it(Kt,{...E,env:Pe,theme:ce,showBalance:ve,walletAddress:q,accountName:m,sendAccounts:T??a,connectorId:A,showPortfolio:R,onDisconnect:H,onSelectWallet:jt,onBuy:qe,onBuyDisabledMessage:Re,onBridgeDisabledMessage:Pt,onSendDisabledMessage:$n,sendTransaction:Qn,getTransactionReceipt:I??Vn,estimateGas:Xn,lpBalanceReader:Yn,stakingRewardsReader:Zn,bridgeTokens:_,bridgeHistory:u,getBridgeQuote:l,getBridgeToTokens:k,getBridgeApproval:h,approveBridge:L,submitBridge:Y,style:i,children:[me(Kt.Trigger,{asChild:!0,children:it("button",{type:"button",className:Jn,style:n,"aria-label":`Connected with ${d?.name??"wallet"}: ${Nn(q)}`,children:[d?.iconUrl?me("img",{src:d.iconUrl,alt:"",width:20,height:20,className:"cb-pill-icon","data-provider":d.iconUrl===Vt?"apple":void 0}):me("span",{className:"cb-pill-icon-placeholder","aria-hidden":"true"}),me("span",{className:"cb-pill-address",children:Nn(q)})]})}),me(Kt.Content,{align:"end",sideOffset:8})]})]}):it(Fn,{children:[me("style",{children:qt}),it("button",{type:"button",onClick:J,className:zt,style:n,"aria-label":typeof e=="string"?e:"Connect Wallet",children:[me(ls,{}),me("span",{className:"cb-button-label",children:e})]})]})}function ls(){return me("svg",{className:"cb-button-icon",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:me("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 us=`
3
+ [data-crossx-wallet-info="external"] .wi-select-wallet-btn {
4
+ display: none !important;
5
+ }
6
+ `;function Nn(e){return`${e.slice(0,6)}...${e.slice(-4)}`}var qt=`
7
+ .cb-button {
8
+ -webkit-font-smoothing: antialiased;
9
+ --cb-bg: var(--ds-accent-primary-default, #00D5AA);
10
+ --cb-bg-hover: var(--ds-accent-primary-high, #00a0a2);
11
+ --cb-color: var(--ds-accent-primary-on, #000);
12
+ --cb-border: none;
13
+ --cb-radius: 8px;
14
+ --cb-height: 36px;
15
+ --cb-padding: 0 16px;
16
+ --cb-font-family: Inter, system-ui, -apple-system, sans-serif;
17
+ --cb-font-size: 14px;
18
+ --cb-font-weight: 500;
19
+ --cb-gap: 8px;
20
+ --cb-transition: background-color 0.15s ease, transform 0.1s ease;
21
+ --cb-loading-opacity: 0.7;
22
+ --cb-press-scale: 0.95;
23
+ --cb-spinner-size: 14px;
24
+ --cb-spinner-thumb: currentColor;
25
+ --cb-spinner-track: color-mix(in srgb, currentColor 20%, transparent);
26
+ --cb-icon-size: 18px;
27
+
28
+ display: inline-flex;
29
+ align-items: center;
30
+ justify-content: center;
31
+ box-sizing: border-box;
32
+ height: var(--cb-height);
33
+ gap: var(--cb-gap);
34
+ padding: var(--cb-padding);
35
+ border-radius: var(--cb-radius);
36
+ border: var(--cb-border);
37
+ background: var(--cb-bg);
38
+ color: var(--cb-color);
39
+ font-family: var(--cb-font-family);
40
+ font-size: var(--cb-font-size);
41
+ font-weight: var(--cb-font-weight);
42
+ cursor: pointer;
43
+ transition: var(--cb-transition);
44
+ }
45
+ .cb-button:hover:not(:disabled) { background: var(--cb-bg-hover); }
46
+ .cb-button:active:not(:disabled) { transform: scale(var(--cb-press-scale)); }
47
+ .cb-button:disabled, .cb-button[aria-busy="true"] {
48
+ cursor: default;
49
+ opacity: var(--cb-loading-opacity);
50
+ }
51
+ .cb-spinner {
52
+ display: inline-block;
53
+ width: var(--cb-spinner-size);
54
+ height: var(--cb-spinner-size);
55
+ border: 2px solid var(--cb-spinner-track);
56
+ border-top-color: var(--cb-spinner-thumb);
57
+ border-radius: 50%;
58
+ animation: cck-cb-spin 0.6s linear infinite;
59
+ flex-shrink: 0;
60
+ }
61
+ .cb-button-icon {
62
+ width: var(--cb-icon-size);
63
+ height: var(--cb-icon-size);
64
+ flex-shrink: 0;
65
+ }
66
+ .cb-button-label { white-space: nowrap; }
67
+ .cb-pill {
68
+ --cb-pill-bg: var(--ds-surface-default, #1e232e);
69
+ --cb-pill-bg-hover: var(--ds-surface-medium, #252b39);
70
+ --cb-pill-color: var(--ds-content-high, #ffffffd9);
71
+ --cb-pill-border: 1px solid var(--ds-border-default, #ffffff12);
72
+ --cb-pill-border-hover: 1px solid var(--ds-border-medium, #ffffff2e);
73
+ --cb-pill-radius: 8px;
74
+ --cb-pill-height: 36px;
75
+ --cb-pill-padding: 0 12px;
76
+ --cb-pill-press-scale: 0.95;
77
+ --cb-pill-font-family: Inter, system-ui, -apple-system, sans-serif;
78
+ --cb-pill-font-size: 14px;
79
+ --cb-pill-font-weight: 500;
80
+ --cb-pill-gap: 8px;
81
+ --cb-pill-icon-size: 20px;
82
+ --cb-pill-icon-placeholder-bg: var(--ds-surface-high, #2a2d3a);
83
+ --cb-pill-address-font: Inter, system-ui, -apple-system, sans-serif;
84
+ --cb-pill-address-font-size: 14px;
85
+ --cb-pill-address-letter-spacing: -0.01em;
86
+
87
+ display: inline-flex;
88
+ align-items: center;
89
+ box-sizing: border-box;
90
+ height: var(--cb-pill-height);
91
+ gap: var(--cb-pill-gap);
92
+ padding: var(--cb-pill-padding);
93
+ border-radius: var(--cb-pill-radius);
94
+ border: var(--cb-pill-border);
95
+ background: var(--cb-pill-bg);
96
+ color: var(--cb-pill-color);
97
+ font-family: var(--cb-pill-font-family);
98
+ font-size: var(--cb-pill-font-size);
99
+ font-weight: var(--cb-pill-font-weight);
100
+ cursor: pointer;
101
+ }
102
+ .cb-pill:hover,
103
+ .cb-pill[data-state="open"] { background: var(--cb-pill-bg-hover); border: var(--cb-pill-border-hover, 1px solid var(--ds-border-medium, #ffffff2e)); }
104
+ .cb-pill:active:not(:disabled) { transform: scale(var(--cb-pill-press-scale)); }
105
+ .cb-pill-icon {
106
+ width: var(--cb-pill-icon-size);
107
+ height: var(--cb-pill-icon-size);
108
+ border-radius: 50%;
109
+ object-fit: contain;
110
+ flex-shrink: 0;
111
+ background: transparent;
112
+ }
113
+ /* Apple is a monochrome black logomark in an <img> data URI (can't follow
114
+ theme via currentColor). Flip it to white in dark mode so it stays
115
+ visible on the dark pill; multicolor marks (Google/MetaMask/Binance/
116
+ CROSSx) are untouched. */
117
+ [data-theme="dark"] .cb-pill-icon[data-provider="apple"] {
118
+ filter: invert(1);
119
+ }
120
+ .cb-pill-icon-placeholder {
121
+ display: inline-block;
122
+ width: var(--cb-pill-icon-size);
123
+ height: var(--cb-pill-icon-size);
124
+ border-radius: 50%;
125
+ background: var(--cb-pill-icon-placeholder-bg);
126
+ flex-shrink: 0;
127
+ }
128
+ .cb-pill-address {
129
+ font-family: var(--cb-pill-address-font);
130
+ font-size: var(--cb-pill-address-font-size);
131
+ letter-spacing: var(--cb-pill-address-letter-spacing);
132
+ }
133
+ @media (max-width: 767.98px) {
134
+ .cb-button, .cb-pill {
135
+ width: 36px;
136
+ min-width: 36px;
137
+ padding: 0;
138
+ }
139
+ .cb-button-label, .cb-pill-address { display: none; }
140
+ }
141
+ @keyframes cck-cb-spin {
142
+ to { transform: rotate(360deg); }
143
+ }
144
+ `;import{useCallback as Mn,useEffect as ms,useMemo as Gn,useState as ps}from"react";import{detectWallets as Un,DEFAULT_WALLET_REGISTRY as Kn}from"@nexus-cross/connect-kit-wagmi";import{jsx as se,jsxs as Oe}from"react/jsx-runtime";var fs=["Ensure your wallet extension is installed and unlocked","Try refreshing the page","Some wallets may require you to first open the extension","You can try clicking the wallet anyway"],gs="Connect with one of our available wallet providers to continue.";function bs({open:e,onClose:t,onSelect:n,title:i="Connect Wallet",description:o=gs,troubleshootingTips:c=fs}){let{availableWallets:p}=We(),[b,f]=ps({});ms(()=>{if(!e)return;let g=Un(Kn),w={};for(let v of g)v.installed!==void 0&&(w[v.id]=v.installed);f(w);let P=setTimeout(()=>{let v=Un(Kn),x={};for(let N of v)N.installed!==void 0&&(x[N.id]=N.installed);f(x)},1e3);return()=>clearTimeout(P)},[e]);let r=Gn(()=>typeof navigator>"u"?!1:/Mobi|Android/i.test(navigator.userAgent),[]),C=Gn(()=>r?p.filter(g=>g.type!=="extension"):p,[p,r]),T=Mn(g=>{if(!b[g.walletId]&&g.installUrl&&g.type==="extension"){window.open(g.installUrl,"_blank");return}t(),n(g.walletId)},[t,n,b]),I=Mn((g,w)=>{g.stopPropagation(),t(),window.open(w,"_blank")},[t]);return e?se("div",{style:$.overlay,onClick:t,children:Oe("div",{style:$.modal,onClick:g=>g.stopPropagation(),children:[Oe("div",{style:$.header,children:[se("h2",{style:$.title,children:i}),se("button",{type:"button",onClick:t,style:$.closeBtn,"aria-label":"Close",children:Oe("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[se("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),se("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),se("p",{style:$.desc,children:o}),se("div",{style:$.walletList,children:C.map(g=>{let w=b[g.walletId],P=w===!1&&g.type==="extension"&&!!g.installUrl;return Oe("div",{style:$.walletGroup,children:[Oe("button",{type:"button",onClick:()=>T(g),style:{...$.walletItem,...g.walletId==="cross_wallet"?$.walletItemAccent:{}},"aria-label":`Connect with ${g.name}`,children:[g.iconUrl?se("img",{src:g.iconUrl,alt:"",style:$.walletIcon}):se("div",{style:$.walletIconPlaceholder}),Oe("div",{style:$.walletInfo,children:[Oe("div",{style:$.walletNameRow,children:[se("span",{style:$.walletName,children:g.name}),w!==void 0&&se("span",{style:{...$.badge,...w?$.badgeInstalled:$.badgeNotInstalled},children:w?"Installed":"Not Installed"})]}),se("span",{style:$.walletDesc,children:P?"Extension not detected \u2014 click to install":g.type==="extension"?"Browser extension approval is required":g.walletId==="cross_wallet"?"App approval is required":g.walletId==="binance"?"Mobile app only \u2014 Add CROSS network first":w?"Connect with browser extension":"Scan QR code with app"})]})]}),g.guideUrl&&Oe("button",{type:"button",onClick:v=>I(v,g.guideUrl),style:$.guideBtn,children:[se("span",{"aria-hidden":"true",children:"\u26A0\uFE0F"}),g.guideLabel??"Required Settings"]})]},g.walletId)})}),Oe("div",{style:$.troubleshoot,children:[se("h3",{style:$.troubleshootTitle,children:"Wallet not detected?"}),se("ul",{style:$.troubleshootList,children:c.map(g=>Oe("li",{style:$.troubleshootItem,children:[se("span",{style:$.troubleshootDot,"aria-hidden":"true"}),se("span",{children:g})]},g))})]})]})}):null}var z={surfaceBg:"var(--wi-surface-bg, #121212)",surfaceDefault:"var(--wi-surface-default, rgba(255,255,255,0.05))",surfaceSubtle:"var(--wi-surface-subtle, rgba(255,255,255,0.1))",borderDefault:"var(--wi-border-default, rgba(255,255,255,0.05))",textPrimary:"var(--wi-texticon-primary, #ffffff)",textSecondary:"var(--wi-texticon-secondary, rgba(255,255,255,0.7))",textTertiary:"var(--wi-texticon-tertiary, rgba(255,255,255,0.5))",primary:"var(--wi-primary, #019d92)",primarySoft:"var(--crossx-kit-primary-soft, rgba(1,157,146,0.15))",accentGradient:"var(--crossx-kit-accent-gradient, linear-gradient(113deg, rgba(255,255,255,0.05) 0%, rgba(1,157,146,0.12) 70%, rgba(255,255,255,0.05) 70%, rgba(1,157,146,0.12) 80%, rgba(255,255,255,0.05) 80%))",warningBg:"var(--crossx-kit-warning-bg, rgba(245,158,11,0.1))",warningBorder:"var(--crossx-kit-warning-border, rgba(245,158,11,0.25))",warningText:"var(--crossx-kit-warning-text, #fbbf24)"},$={overlay:{position:"fixed",inset:0,zIndex:1e4,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",backdropFilter:"blur(4px)"},modal:{width:"100%",maxWidth:"420px",margin:"16px",background:z.surfaceBg,border:`1px solid ${z.borderDefault}`,borderRadius:"20px",overflow:"hidden"},header:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"20px 24px 0"},title:{fontSize:"18px",fontWeight:700,color:z.textPrimary,margin:0},closeBtn:{background:"none",border:"none",color:z.textTertiary,cursor:"pointer",padding:"4px",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"center"},desc:{padding:"8px 24px 16px",fontSize:"13px",color:z.textTertiary,margin:0,lineHeight:1.5},walletList:{display:"flex",flexDirection:"column",gap:"6px",padding:"0 12px 12px"},walletGroup:{display:"flex",flexDirection:"column",borderRadius:"12px",overflow:"hidden",background:z.surfaceDefault},walletItem:{display:"flex",alignItems:"center",gap:"14px",width:"100%",padding:"14px",background:"transparent",border:"none",color:z.textPrimary,cursor:"pointer",textAlign:"left"},walletItemAccent:{background:z.accentGradient},walletIcon:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0},walletIconPlaceholder:{width:"40px",height:"40px",borderRadius:"10px",background:z.surfaceSubtle,flexShrink:0},walletInfo:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:"3px"},walletNameRow:{display:"flex",alignItems:"center",gap:"8px"},walletName:{fontSize:"15px",fontWeight:700,lineHeight:1.3,color:z.textPrimary},badge:{fontSize:"10px",fontWeight:600,padding:"2px 7px",borderRadius:"99px",lineHeight:1},badgeInstalled:{background:z.primarySoft,color:z.primary},badgeNotInstalled:{background:"rgba(255,255,255,0.05)",color:z.textTertiary},walletDesc:{fontSize:"11px",color:z.textSecondary,lineHeight:1.3},guideBtn:{display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",margin:"0 14px 14px",padding:"10px 12px",borderRadius:"10px",border:`1px solid ${z.warningBorder}`,background:z.warningBg,color:z.warningText,fontWeight:600,fontSize:"13px",cursor:"pointer"},troubleshoot:{margin:"0 12px 16px",background:z.surfaceDefault,borderRadius:"12px",padding:"14px 16px"},troubleshootTitle:{fontSize:"12px",fontWeight:700,color:z.textPrimary,margin:"0 0 8px"},troubleshootList:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:"8px"},troubleshootItem:{display:"flex",alignItems:"flex-start",gap:"8px",fontSize:"11px",color:z.textSecondary,lineHeight:1.5},troubleshootDot:{flexShrink:0,width:"4px",height:"4px",marginTop:"6px",borderRadius:"50%",background:z.textSecondary}};import{useOnRamp as Ni,useOnRampEligibility as Fi,OnRampProvider as Wi}from"@nexus-cross/onramp/react";import{useKyc as Di,useOptionalKyc as Mi,KycProvider as Gi,KycError as Ui,launchKycVerification as Ki}from"@nexus-cross/kyc/react";import{WalletInfo as qi,ConnectorId as Hi}from"@nexus-cross/dapp-ui";import{AppLauncher as ji,AppLauncherTrigger as Qi,AppLauncherContent as zi,useGlobalMenu as Xi}from"@nexus-cross/dapp-ui";import{SkillsButton as Zi}from"@nexus-cross/dapp-ui";import{OnRampError as ea}from"@nexus-cross/connect-kit-core";import{ConnectionStatus as na,formatBalance as oa,formatWei as ra}from"@nexus-cross/connect-kit-core";Zt();export{We as a,lo as b,pt as c,_t as d,Mo as e,Mt as f,Gt as g,ds as h,bs as i,Ni as j,Fi as k,Wi as l,Di as m,Mi as n,Gi as o,Ui as p,Ki as q,qi as r,Hi as s,ji as t,Qi as u,zi as v,Xi as w,Zi as x,ea as y,na as z,oa as A,ra as B};
package/dist/client.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { ConnectButton, ConnectButtonProps, CrossConnectKitContextValue, CrossConnectKitProvider, CrossConnectKitProviderProps, CrossConnectKitThemeContextValue, CrossConnectModal, CrossConnectModalProps, CrossxEmbeddedInfo, OtherWalletsModal, OtherWalletsModalProps, WalletProvider, WalletUser, useCrossConnectKit, useCrossConnectKitTheme, useCrossdBridgeAdapter, useCrossxEmbeddedInfo, useOptionalCrossConnectKitTheme } from './index.js';
2
2
  export { OnRampProvider, OnRampProviderProps, UseOnRampEligibilityOptions, UseOnRampEligibilityResult, UseOnRampOptions, UseOnRampResult, useOnRamp, useOnRampEligibility } from '@nexus-cross/onramp/react';
3
+ export { KycError, KycErrorCode, KycIdentity, KycLaunchTarget, KycLoginType, KycProvider, KycProviderProps, KycRejectType, KycStatus, KycVerificationHandle, KycVerificationMode, LaunchKycVerificationOptions, UseKycOptions, UseKycResult, launchKycVerification, useKyc, useOptionalKyc } from '@nexus-cross/kyc/react';
3
4
  export { AppLauncher, AppLauncherContent, AppLauncherContentProps, AppLauncherProps, AppLauncherTrigger, AppLauncherTriggerProps, AppLauncherTriggerStyle, ConnectButtonStyle, ConnectorId, GlobalMenu, GlobalMenuItem, GlobalMenuItemUrl, SendTransactionArgs, SendTransactionFn, SkillsButton, SkillsButtonProps, SkillsButtonStyle, WalletInfo, WalletInfoContentProps, WalletInfoProps, WalletInfoStyle, WalletInfoTriggerProps, useGlobalMenu } from '@nexus-cross/dapp-ui';
4
5
  import { AppMetadata, NetworkConfig, WalletId } from '@nexus-cross/connect-kit-core';
5
6
  export { Account, ChainBalance, ColorOverrides, ConnectionStatus, ConnectorType, CrossConnectKitConfig, ModalView, OnRampDisallowReason, OnRampEligibility, OnRampError, OnRampErrorCode, OnRampOpenParams, OnRampProviderId, OnRampSession, OnRampStatus, OnRampStatusEvent, Theme, ThemeMode, ThemeTokens, WalletDescriptor, WalletId, WalletState, formatBalance, formatWei } from '@nexus-cross/connect-kit-core';
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import{a as S,b as _,c as V,d as X,e as W,f as h,g as j,h as F,i as L,j as B,k as U,l as q,m as z,n as D,o as G,p as H,q as J,r as Q,s as Y,t as Z,u as $,v as ee,w as ne}from"./chunk-AGBUWVJ2.js";import{bscMainnetNetwork as v,bscTestnetNetwork as x,createCrossxConfig as E,crossMainnetNetwork as O,crossTestnetNetwork as k}from"@nexus-cross/connect-kit-wagmi";import{toNexusAdapter as M}from"@nexus-cross/connect-kit-wagmi/to-nexus";import{reownAdapter as P}from"@nexus-cross/connect-kit-wagmi/reown";import{embeddedConnectorFactory as A}from"@nexus-cross/connect-kit-wagmi/embedded";function d(e){try{return import.meta.env?.[e]}catch{return}}function p(e){if(!(typeof process>"u"))return process.env?.[e]}function I(){return d("VITE_CROSSX_ENVIRONMENT")??d("NEXT_PUBLIC_CROSSX_ENVIRONMENT")??p("NEXT_PUBLIC_CROSSX_ENVIRONMENT")??p("CROSSX_ENVIRONMENT")}function K(e){switch(e?.toLowerCase()){case"dev":case"development":return"development";case"stage":case"staging":case"stg":return"staging";default:return"production"}}function R(e){return e==="production"?[O,v]:[k,x]}function T(){return{name:"CROSSx DApp",url:typeof window<"u"&&window.location?.origin?window.location.origin:"https://example.com"}}function b(e){let{app:c,appMetadata:l,networks:u,defaultNetwork:f,wallets:n,embedded:C=!0,environment:w,toNexus:t,reown:o,...r}=e,g=K(w??I()),i=u??R(g),a=Array.isArray(n)?null:n??"all",s=a!=="external-only"&&t!==!1,m=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??T(),networks:i,defaultNetwork:f??i[0],...Array.isArray(n)?{wallets:n}:{},...s?{crossProvider:M(y)}:{},...m?{reownProvider:P(N)}:{},...s&&C?{embeddedConnectorFactory:A}:{}})}export{G as AppLauncher,J as AppLauncherContent,H as AppLauncherTrigger,F as ConnectButton,$ as ConnectionStatus,D as ConnectorId,W as CrossConnectKitProvider,X as CrossConnectModal,Z as OnRampError,q as OnRampProvider,L as OtherWalletsModal,Y as SkillsButton,z as WalletInfo,b as createConnectKitConfig,ee as formatBalance,ne as formatWei,S as useCrossConnectKit,_ as useCrossConnectKitTheme,h as useCrossdBridgeAdapter,j as useCrossxEmbeddedInfo,Q as useGlobalMenu,B as useOnRamp,U as useOnRampEligibility,V as useOptionalCrossConnectKitTheme};
1
+ import{A as ae,B as ie,a as S,b as _,c as V,d as X,e as W,f as h,g as j,h as F,i as L,j as B,k as U,l as q,m as z,n as D,o as G,p as H,q as J,r as Q,s as Y,t as Z,u as $,v as ee,w as ne,x as te,y as oe,z as re}from"./chunk-4TWKECXR.js";import{bscMainnetNetwork as v,bscTestnetNetwork as x,createCrossxConfig as E,crossMainnetNetwork as O,crossTestnetNetwork as k}from"@nexus-cross/connect-kit-wagmi";import{toNexusAdapter as M}from"@nexus-cross/connect-kit-wagmi/to-nexus";import{reownAdapter as P}from"@nexus-cross/connect-kit-wagmi/reown";import{embeddedConnectorFactory as A}from"@nexus-cross/connect-kit-wagmi/embedded";function d(e){try{return import.meta.env?.[e]}catch{return}}function p(e){if(!(typeof process>"u"))return process.env?.[e]}function I(){return d("VITE_CROSSX_ENVIRONMENT")??d("NEXT_PUBLIC_CROSSX_ENVIRONMENT")??p("NEXT_PUBLIC_CROSSX_ENVIRONMENT")??p("CROSSX_ENVIRONMENT")}function K(e){switch(e?.toLowerCase()){case"dev":case"development":return"development";case"stage":case"staging":case"stg":return"staging";default:return"production"}}function R(e){return e==="production"?[O,v]:[k,x]}function T(){return{name:"CROSSx DApp",url:typeof window<"u"&&window.location?.origin?window.location.origin:"https://example.com"}}function b(e){let{app:c,appMetadata:l,networks:u,defaultNetwork:f,wallets:n,embedded:C=!0,environment:w,toNexus:t,reown:o,...r}=e,g=K(w??I()),i=u??R(g),a=Array.isArray(n)?null:n??"all",s=a!=="external-only"&&t!==!1,m=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??T(),networks:i,defaultNetwork:f??i[0],...Array.isArray(n)?{wallets:n}:{},...s?{crossProvider:M(y)}:{},...m?{reownProvider:P(N)}:{},...s&&C?{embeddedConnectorFactory:A}:{}})}export{Z as AppLauncher,ee as AppLauncherContent,$ as AppLauncherTrigger,F as ConnectButton,re as ConnectionStatus,Y as ConnectorId,W as CrossConnectKitProvider,X as CrossConnectModal,H as KycError,G as KycProvider,oe as OnRampError,q as OnRampProvider,L as OtherWalletsModal,te as SkillsButton,Q as WalletInfo,b as createConnectKitConfig,ae as formatBalance,ie as formatWei,J as launchKycVerification,S as useCrossConnectKit,_ as useCrossConnectKitTheme,h as useCrossdBridgeAdapter,j as useCrossxEmbeddedInfo,ne as useGlobalMenu,z as useKyc,B as useOnRamp,U as useOnRampEligibility,V as useOptionalCrossConnectKitTheme,D as useOptionalKyc};
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ import { WalletInfoProps, ConnectButtonStyle, WalletInfoStyle, Environment, Brid
8
8
  export { AppLauncher, AppLauncherContent, AppLauncherContentProps, AppLauncherProps, AppLauncherTrigger, AppLauncherTriggerProps, AppLauncherTriggerStyle, ConnectButtonStyle, ConnectorId, GlobalMenu, GlobalMenuItem, GlobalMenuItemUrl, SendTransactionArgs, SendTransactionFn, SkillsButton, SkillsButtonProps, SkillsButtonStyle, WalletInfo, WalletInfoContentProps, WalletInfoProps, WalletInfoStyle, WalletInfoTriggerProps, useGlobalMenu } from '@nexus-cross/dapp-ui';
9
9
  import { Connector } from 'wagmi';
10
10
  export { OnRampProvider, OnRampProviderProps, UseOnRampEligibilityOptions, UseOnRampEligibilityResult, UseOnRampOptions, UseOnRampResult, useOnRamp, useOnRampEligibility } from '@nexus-cross/onramp/react';
11
+ export { KycError, KycErrorCode, KycIdentity, KycLaunchTarget, KycLoginType, KycProvider, KycProviderProps, KycRejectType, KycStatus, KycVerificationHandle, KycVerificationMode, LaunchKycVerificationOptions, UseKycOptions, UseKycResult, launchKycVerification, useKyc, useOptionalKyc } from '@nexus-cross/kyc/react';
11
12
 
12
13
  interface CrossConnectKitProviderProps {
13
14
  children: ReactNode;
@@ -348,6 +349,7 @@ type CrossdBridgeAdapterOptions = {
348
349
  env: Environment;
349
350
  walletAddress?: string;
350
351
  enabled?: boolean;
352
+ restoreChainAfterSwitch?: boolean;
351
353
  };
352
354
  type CrossdBridgeAdapter = {
353
355
  bridgeTokens: BridgeToken[];
@@ -359,6 +361,6 @@ type CrossdBridgeAdapter = {
359
361
  submitBridge: BridgeSubmitFn;
360
362
  isLoading: boolean;
361
363
  };
362
- declare function useCrossdBridgeAdapter({ env, walletAddress, enabled, }: CrossdBridgeAdapterOptions): CrossdBridgeAdapter;
364
+ declare function useCrossdBridgeAdapter({ env, walletAddress, enabled, restoreChainAfterSwitch, }: CrossdBridgeAdapterOptions): CrossdBridgeAdapter;
363
365
 
364
366
  export { ConnectButton, type ConnectButtonProps, type CrossConnectKitContextValue, CrossConnectKitProvider, type CrossConnectKitProviderProps, type CrossConnectKitThemeContextValue, CrossConnectModal, type CrossConnectModalProps, type CrossxEmbeddedInfo, OtherWalletsModal, type OtherWalletsModalProps, type WalletProvider, type WalletUser, useCrossConnectKit, useCrossConnectKitTheme, useCrossdBridgeAdapter, useCrossxEmbeddedInfo, useOptionalCrossConnectKitTheme };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w}from"./chunk-AGBUWVJ2.js";export{o as AppLauncher,q as AppLauncherContent,p as AppLauncherTrigger,h as ConnectButton,u as ConnectionStatus,n as ConnectorId,e as CrossConnectKitProvider,d as CrossConnectModal,t as OnRampError,l as OnRampProvider,i as OtherWalletsModal,s as SkillsButton,m as WalletInfo,v as formatBalance,w as formatWei,a as useCrossConnectKit,b as useCrossConnectKitTheme,f as useCrossdBridgeAdapter,g as useCrossxEmbeddedInfo,r as useGlobalMenu,j as useOnRamp,k as useOnRampEligibility,c as useOptionalCrossConnectKitTheme};
1
+ import{A,B,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-4TWKECXR.js";export{t as AppLauncher,v as AppLauncherContent,u as AppLauncherTrigger,h as ConnectButton,z as ConnectionStatus,s as ConnectorId,e as CrossConnectKitProvider,d as CrossConnectModal,p as KycError,o as KycProvider,y as OnRampError,l as OnRampProvider,i as OtherWalletsModal,x as SkillsButton,r as WalletInfo,A as formatBalance,B as formatWei,q as launchKycVerification,a as useCrossConnectKit,b as useCrossConnectKitTheme,f as useCrossdBridgeAdapter,g as useCrossxEmbeddedInfo,w as useGlobalMenu,m as useKyc,j as useOnRamp,k as useOnRampEligibility,c as useOptionalCrossConnectKitTheme,n as useOptionalKyc};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexus-cross/connect-kit-react",
3
- "version": "1.3.3",
3
+ "version": "1.3.4-beta.10",
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,11 +24,12 @@
24
24
  "access": "public"
25
25
  },
26
26
  "dependencies": {
27
- "@nexus-cross/connect-kit-core": "1.3.3",
28
- "@nexus-cross/connect-kit-wagmi": "1.3.3",
29
- "@nexus-cross/dapp-ui": "1.3.3",
30
- "@nexus-cross/crossx-design-system": "1.3.3",
31
- "@nexus-cross/onramp": "1.3.3"
27
+ "@nexus-cross/connect-kit-core": "1.3.4-beta.10",
28
+ "@nexus-cross/connect-kit-wagmi": "1.3.4-beta.10",
29
+ "@nexus-cross/crossx-design-system": "1.3.4-beta.10",
30
+ "@nexus-cross/dapp-ui": "1.3.4-beta.10",
31
+ "@nexus-cross/kyc": "1.3.4-beta.10",
32
+ "@nexus-cross/onramp": "1.3.4-beta.10"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@tanstack/react-query": "^5.60.0",
@@ -51,7 +52,8 @@
51
52
  "scripts": {
52
53
  "build": "tsup",
53
54
  "dev": "tsup --watch",
54
- "test": "echo 'no tests yet'",
55
+ "test": "vitest run",
56
+ "test:watch": "vitest",
55
57
  "typecheck": "tsc --noEmit"
56
58
  }
57
59
  }
@@ -1,144 +0,0 @@
1
- var st="1.3.3";var pt="__nexusCrossAppLauncherRuntime";function Xn(){if(typeof window>"u")return null;let e=window;return e[pt]??(e[pt]={mode:"dapp-ui"}),e[pt]}function Yn(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 o=e.connectKitVersion??st;console.info(`[CROSSx App Launcher] connect-kit-react v${o} \uCD08\uAE30\uD654 \uC644\uB8CC (dapp-ui v${st}, \uC0AC\uC6A9 \uBAA8\uB4DC: connect-kit)`)}else console.info(`[CROSSx App Launcher] dapp-ui v${st} \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 qt(){let e=Xn();e&&(e.mode="connect-kit-react",e.connectKitVersion=st,Yn(e))}import{useCallback as ve,useEffect as de,useMemo as Le,useRef as Qe,useState as Me}from"react";import{WagmiProvider as ro,useAccount as so,useChainId as io,useConnect as ao,useDisconnect as co,useSwitchChain as lo}from"wagmi";import{QueryClient as uo,QueryClientProvider as mo}from"@tanstack/react-query";import{clearWalletSessionStorage as jt,onOpenOtherWallets as po,pickInitialState as fo,resolveCurrentWallet as go}from"@nexus-cross/connect-kit-wagmi";import{resolveThemeMode as bo}from"@nexus-cross/connect-kit-core";import{buildDesignSystemCss as yo}from"@nexus-cross/crossx-design-system";import{OnRampProvider as wo}from"@nexus-cross/onramp/react";import{createContext as Zn,useContext as Jn}from"react";var xt=Zn(null);function Be(){let e=Jn(xt);if(!e)throw new Error("useCrossConnectKit must be used within <CrossConnectKitProvider>");return e}import{createContext as eo,useContext as Ht}from"react";var ft=eo(null);function to(){let e=Ht(ft);if(!e)throw new Error("useCrossConnectKitTheme must be used within <CrossConnectKitProvider>");return e}function it(){return Ht(ft)}import{useCallback as no,useMemo as Vt}from"react";import{WalletConnectModal as zt}from"@nexus-cross/dapp-ui";import{jsx as Qt}from"react/jsx-runtime";var oo=new Set(["cross_wallet","cross_extension","metamask","binance"]);function Tt({open:e,onOpenChange:t}){let{connect:o,availableWallets:s,oauth:n,extraWallets:a,walletAllowlist:g,kitConfig:f}=Be(),p=it()?.mode??"dark",h=Vt(()=>{let m=g?new Set(g):null,T={};for(let P of s){if(!oo.has(P.walletId)||m&&!m.has(P.walletId))continue;let C=P.walletId;T[C]=()=>{o(P.walletId)}}for(let[P,C]of Object.entries(a))C&&(m&&!m.has(P)||(T[P]=C));return T},[s,o,a,g]),I=Vt(()=>{if(n)return{apple:()=>{n.signIn("apple")},google:()=>{n.signIn("google")}}},[n]),S=no(m=>t(m),[t]);return Qt(zt,{wallets:h,socialProviders:I,termsUrl:f.legal?.termsUrl,privacyUrl:f.legal?.privacyUrl,theme:p,open:e,onOpenChange:S,children:Qt(zt.Content,{})})}import{jsx as tt,jsxs as Zt}from"react/jsx-runtime";var ho=new uo,It="crossx-kit:last-wallet-intent",Co=15e3;function Xt(e,t){return Promise.race([e.then(()=>{},()=>{}),new Promise(o=>setTimeout(o,t))])}function ko(e){let t=[],o=e,s=0;for(;o&&s<5;){let n=o;typeof n.message=="string"&&t.push(n.message),o=n.cause,s+=1}return t.some(n=>/external wallet connection/i.test(n))}function xo(){if(typeof window>"u")return null;try{return window.localStorage.getItem(It)??null}catch{return null}}function Yt(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(It,e):window.localStorage.removeItem(It)}catch{}}function To(e,t){if(typeof window>"u")return t;try{let o=window.localStorage.getItem(e);return o==="cross"||o==="reown"?o:t}catch{return t}}function Io(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}function So({children:e,config:t,activeProvider:o,onRequestProviderSwap:s,pendingConnectWalletId:n,clearPending:a,themeMode:g,themeTokens:f,extraWallets:b,walletAllowlist:p}){let[h,I]=Me(!1),[S,m]=Me(()=>xo()),[T,P]=Me(null),{address:C,isConnected:k,isConnecting:_,isReconnecting:O,connector:U}=so(),{connectors:te,connectAsync:z}=ao(),{disconnectAsync:K}=co(),{kitConfig:D,connectorRegistry:M,crossProvider:Ce,reownProvider:E}=t,A=o==="cross"?Ce:E,W=Le(()=>!k||!U?null:go(M,U.id,S),[k,U,M,S]),ke=Le(()=>M.entries.filter(u=>u.type!=="embedded"),[M]),qe=Qe(C);qe.current=C;let j=D.embeddedProjectId?.trim()||D.crossProjectId?.trim(),q=!!D.onRampEnabled&&!!j,pe=Le(()=>!q||!j?null:{projectId:j,walletState:{getAddress:()=>qe.current}},[q,j]);de(()=>po(()=>I(!0)),[]),de(()=>{if(!h||typeof document>"u")return;let u=setTimeout(()=>{document.querySelectorAll("#__crossx-confirm-overlay").forEach(d=>d.remove())},50);return()=>clearTimeout(u)},[h]);let we=Qe(k),Oe=Qe(k);we.current=k;let Ne=Qe(!1);de(()=>{console.debug("[crossx-kit] state",{activeProvider:o,isConnected:k,isConnecting:_,isReconnecting:O,activeConnectorId:U?.id,currentWallet:W,lastIntent:S})},[o,k,_,O,U?.id,W,S]),de(()=>{k&&!Oe.current&&A?.closeModal?.({kitConfig:D}),Oe.current=k},[k,A,D]),de(()=>{k&&P(null)},[k]);let He=io(),{switchChainAsync:Fe}=lo(),fe=Qe(null);de(()=>{if(!D.enforceDefaultNetworkOnConnect)return;let u=D.defaultNetwork?.id;if(!u)return;if(!k||!C||!U){fe.current=null;return}let d=`${U.id}:${C}`;fe.current!==d&&(fe.current=d,He!==u&&Fe({chainId:u}).catch(()=>{}))},[D.enforceDefaultNetworkOnConnect,D.defaultNetwork,k,C,U,He,Fe]);let ae=ve(u=>te.find(d=>d.id===u),[te]);de(()=>{let u=M.getEntry("cross_embedded");if(!u)return;let d=ae(u.connectorId);if(!d)return;let w=!1;return(async()=>{try{let y=await d.getProvider();if(w)return;y?.sdk?.applyTheme?.(g,f??void 0)}catch(y){console.debug("[crossx-kit] applyTheme skipped:",y)}})(),()=>{w=!0}},[M,ae,g,f]);let De=ve(u=>{m(u),Yt(u)},[]),X=ve(()=>{m(null),Yt(null),P(null)},[]);de(()=>{if(!A?.subscribeModalState)return;let u=!1;return A.subscribeModalState({kitConfig:D},d=>{if(Ne.current=d,d){u=!0;return}u&&(u=!1,setTimeout(()=>{we.current||(async()=>{try{await K()}catch{}X()})()},250))})},[A,D,K,X]),de(()=>{if(!T||k||typeof window>"u"||T==="cross_embedded")return;let u=typeof document<"u"&&!document.hasFocus(),d=null,w=()=>{u=!0},y=()=>{u&&(d&&clearTimeout(d),d=setTimeout(()=>{we.current||Ne.current||(async()=>{try{await K()}catch{}X()})()},1e3))};return window.addEventListener("blur",w),window.addEventListener("focus",y),()=>{window.removeEventListener("blur",w),window.removeEventListener("focus",y),d&&clearTimeout(d)}},[T,k,K,X]);let Se=ve(async u=>{console.debug("[crossx-kit] runConnect enter",{walletId:u,activeProvider:o,isConnected:k,activeConnectorId:U?.id});let d=M.getEntry(u);if(!d){if((u==="metamask"||u==="binance")&&!E){console.error(`[crossx-kit] "${u}" 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: "${u}"`);return}if(P(u),d.providerKind!==o){console.debug("[crossx-kit] provider swap needed",{from:o,to:d.providerKind,walletId:u}),De(u);try{await K()}catch{}await new Promise(y=>setTimeout(y,0)),s(d.providerKind,u);return}if(De(u),A?.beforeConnect)try{let y=await A.beforeConnect({kitConfig:D,themeMode:g},u);if(console.debug("[crossx-kit] beforeConnect result",{walletId:u,result:y}),y==="handled")return}catch(y){console.warn('[crossx-kit] adapter.beforeConnect threw for "%s":',u,y)}let w=ae(d.connectorId);if(console.debug("[crossx-kit] findConnector",{lookupId:d.connectorId,found:w?.id,availableIds:te.map(y=>y.id)}),!w){console.error(`[crossx-kit] Connector "${d.connectorId}" not found on provider "${d.providerKind}". Available: ${te.map(y=>y.id).join(", ")}`),X();return}try{console.debug("[crossx-kit] connectAsync start",{connectorId:w.id});let y=await z({connector:w});console.debug("[crossx-kit] connectAsync resolved",{accountsLen:y.accounts.length,chainId:y.chainId});return}catch(y){if(!ko(y)){console.error('[crossx-kit] connectAsync error for "%s":',u,y);try{await K()}catch{}}if(!d.fallbackConnectorId){X();return}}if(d.fallbackConnectorId){let y=ae(d.fallbackConnectorId);if(y)try{await z({connector:y})}catch(N){console.error('[crossx-kit] Fallback connect failed for "%s":',u,N);try{await K()}catch{}X()}else X()}},[M,te,ae,z,K,De,X,A,o,D,s,g]);de(()=>{if(!n)return;let u=n;a(),Se(u)},[n,o]);let r=ve(async()=>{I(!0)},[]),i=ve(async()=>{try{await K()}catch(u){console.error("[crossx-kit] wagmi disconnect error:",u)}if(A?.teardown)try{await A.teardown({kitConfig:D})}catch(u){console.error("[crossx-kit] adapter teardown error:",u)}jt(),X()},[K,A,D,X]),c=ve(async()=>{await Xt(K(),3e3);try{let u=M.getEntry("cross_embedded"),d=u&&ae(u.connectorId);if(d?.getProvider){let w=await Promise.race([d.getProvider(),new Promise(N=>setTimeout(N,3e3))]),y=w?.sdk?.signOut;typeof y=="function"&&await Xt(y.call(w.sdk),3e3)}}catch{}jt()},[M,ae,K]),l=ve(async()=>{let u=M.getEntry("cross_embedded");if(!u)return null;let d=ae(u.connectorId);if(!d)return null;try{let w=await d.getProvider(),y=w?.sdk;if(!y?.selectWallet)return null;let N=await y.selectWallet(y.currentAddress??void 0);return N?.address&&w.notifyAccountsChanged&&w.notifyAccountsChanged([N.address]),N}catch{return null}},[M,ae]),x=Le(()=>{let u=t.oauth;return u?{signIn:async d=>{P("cross_embedded");try{await u.signIn(d)}catch(w){throw P(null),w}}}:null},[t.oauth]),v=Qe(!1);de(()=>{if(o!=="cross"||k||_||O||T!=null||v.current)return;let u=M.getEntry("cross_embedded");if(!u)return;let d=ae(u.connectorId);if(!d)return;v.current=!0;let w=!1;return(async()=>{try{let y=await d.isAuthorized?.();if(w||!y)return;await z({connector:d})}catch{}})(),()=>{w=!0}},[o,k,_,O,T,M,ae,z]),de(()=>{if(T!=="cross_embedded"||k||typeof window>"u")return;let u=!document.hasFocus(),d=()=>{u=!0};window.addEventListener("blur",d);let w=setTimeout(()=>{we.current||u||(console.warn("[crossx-kit] embedded sign-in stalled before the OAuth popup opened \u2014 clearing the stale session so a retry starts clean"),X(),c())},Co);return()=>{window.removeEventListener("blur",d),clearTimeout(w)}},[T,k,X,c]);let R=T!=null&&!k,B=Le(()=>({kitConfig:D,connectorRegistry:M,availableWallets:ke,connect:Se,connectWallet:r,disconnect:i,selectWallet:l,currentWallet:W,lastIntent:S,isConnecting:R,connectingWalletId:T,openOtherWallets:()=>I(!0),closeOtherWallets:()=>I(!1),otherWalletsOpen:h,oauth:x,extraWallets:b,walletAllowlist:p,onRampEnabled:q}),[D,M,ke,Se,r,i,l,W,S,R,T,h,x,b,p,q]),F=Zt(xt.Provider,{value:B,children:[e,tt(Tt,{open:h,onOpenChange:I})]});return pe?tt(wo,{config:pe,children:F}):F}var vo=[/Connection interrupted while trying to subscribe/i,/No matching key\. subscription:/i,/Proposal expired/i];function Po(e){let t=e?.message;return typeof t!="string"?!1:vo.some(o=>o.test(t))}var Ao={};function Ro(e){return e&&{...e,connections:new Map,current:null}}function Bo({children:e,config:t,initialState:o,extraWallets:s=Ao,walletAllowlist:n}){let[a,g]=Me(()=>To(t.activeProviderStorageKey,t.defaultProvider)),[f,b]=Me(null),p=Qe(!1),{kitConfig:h}=t,[I,S]=Me(null),[m,T]=Me(null),[P,C]=Me(0),k=Le(()=>bo(h.theme,h.autoDetectTheme),[h.theme,h.autoDetectTheme,P]),_=I??k,O=m??h.themeTokens;de(()=>{if(!h.autoDetectTheme||I||typeof window>"u"||!window.matchMedia)return;let E=window.matchMedia("(prefers-color-scheme: dark)"),A=()=>C(W=>W+1);try{return E.addEventListener("change",A),()=>E.removeEventListener("change",A)}catch{return E.addListener(A),()=>E.removeListener(A)}},[h.autoDetectTheme,I]),de(()=>{if(typeof document>"u")return;let E=document.documentElement,A=E.getAttribute("data-ds-theme"),W=E.getAttribute("data-theme");return E.setAttribute("data-ds-theme",_),W||E.setAttribute("data-theme",_),()=>{A==null?E.removeAttribute("data-ds-theme"):E.setAttribute("data-ds-theme",A),W==null&&E.removeAttribute("data-theme")}},[_]);let U=Le(()=>yo(t.designSystem),[t.designSystem]),te=Le(()=>({mode:_,tokens:O,setThemeMode:E=>S(E),setThemeTokens:E=>T(E)}),[_,O]);de(()=>{if(typeof window>"u")return;let E=A=>{Po(A.reason)&&A.preventDefault()};return window.addEventListener("unhandledrejection",E),()=>window.removeEventListener("unhandledrejection",E)},[]);let z=ve((E,A)=>{p.current||(p.current=!0,b(A),g(E),Io(t.activeProviderStorageKey,E),queueMicrotask(()=>{p.current=!1}))},[t.activeProviderStorageKey]),K=ve(()=>b(null),[]),D=a==="cross"?t.crossWagmiConfig:t.reownWagmiConfig,M=Ro(fo(o,a));if(!D){if(!(a==="cross"?t.reownWagmiConfig:t.crossWagmiConfig))throw new Error("[crossx-kit] createCrossxConfig returned no wagmi Config for either side");let A=a==="cross"?"reown":"cross";queueMicrotask(()=>g(A))}let Ce=D??(a==="cross"?t.reownWagmiConfig:t.crossWagmiConfig);return Zt(ft.Provider,{value:te,children:[tt("style",{"data-crossx-design-system":"",children:U}),tt(ro,{config:Ce,initialState:M,children:tt(mo,{client:ho,children:tt(So,{config:t,activeProvider:a,onRequestProviderSwap:z,pendingConnectWalletId:f,clearPending:K,themeMode:_,themeTokens:O,extraWallets:s,walletAllowlist:n??t.kitConfig.wallets??null,children:e})})},a)]})}import{useCallback as Ke,useEffect as Rr,useMemo as lt}from"react";import{useQueryClient as Br}from"@tanstack/react-query";import{useAccount as _r,useChainId as Er,useConfig as Or,useSendTransaction as Nr,useSwitchChain as Fr}from"wagmi";import{getPublicClient as Et,readContracts as Tn}from"wagmi/actions";import{WalletInfo as Ot,ConnectorId as $e,resolveEnvironment as Dr}from"@nexus-cross/dapp-ui";import{useOptionalOnRamp as Wr,useOptionalOnRampEligibility as Lr}from"@nexus-cross/onramp/react";import{APPLE_ICON as Wt,BINANCE_ICON as vn,CROSSX_ICON as Dt,EXTENSION_ICON as Mr,GOOGLE_ICON as Pn,METAMASK_ICON as An}from"@nexus-cross/connect-kit-wagmi";import{useCallback as se,useMemo as Pe,useRef as _o}from"react";import{useQueries as Jt,useQuery as nt}from"@tanstack/react-query";import{encodeFunctionData as at,formatUnits as wt,parseSignature as Eo,parseUnits as Oo}from"viem";import{getChainId as No,getPublicClient as pn,readContract as Ie,signTypedData as Fo,switchChain as Do,waitForTransactionReceipt as Wo,writeContract as en}from"wagmi/actions";import{useConfig as Lo}from"wagmi";function Mo(e){return e!=="bridge"}var fn="0x0000000000000000000000000000000000000000",he=100,rt=18,Go=180000n,Uo=250000n,gn=new Set([56,97]),Ko=130n,$o=100n,qo={dev:{bridgeApi:"https://stg-bridge-api.crosstoken.io/bridge",walletApi:"https://stg-wallet-server.crosstoken.io/api",chainIds:{cross:612044,bsc:97},contracts:{BSC_CROSS:"0x26ca2a92ea9659e073621bb85b9117dc5944cff1",W_CROSS:"0xda37a3B60E6b97E8CB44b460130d40331efc566b",NATIVE_CROSS:"0x0000000000000000000000000000000000000001",USDTX:"0x9f85c7b5d7637e18f946cc8af9c131318c6833d9",CROSSD:"0x9364ea6790f6e0ecfaa5164085f2a7de34ec55fb",USDTB:"0xbb188503c32fa7f61e019c3b3ae61ae6b0b3b492",SWAP_BRIDGE_ROUTER:"0x337071C06416f13b568eE644c1D714edd65509eB"},hiddenPairs:[{fromKey:"97-0xbb188503c32fa7f61e019c3b3ae61ae6b0b3b492",toKey:"612044-0x9f85c7b5d7637e18f946cc8af9c131318c6833d9"},{fromKey:"612044-0x9364ea6790f6e0ecfaa5164085f2a7de34ec55fb",toKey:"612044-0x9f85c7b5d7637e18f946cc8af9c131318c6833d9"},{fromKey:"97-0x26ca2a92ea9659e073621bb85b9117dc5944cff1",toKey:"612044-0x9364ea6790f6e0ecfaa5164085f2a7de34ec55fb"}]},stage:{bridgeApi:"https://stg-bridge-api.crosstoken.io/bridge",walletApi:"https://stg-wallet-server.crosstoken.io/api",chainIds:{cross:612044,bsc:97},contracts:{BSC_CROSS:"0x26ca2a92ea9659e073621bb85b9117dc5944cff1",W_CROSS:"0xda37a3B60E6b97E8CB44b460130d40331efc566b",NATIVE_CROSS:"0x0000000000000000000000000000000000000001",USDTX:"0x9f85c7b5d7637e18f946cc8af9c131318c6833d9",CROSSD:"0x9364ea6790f6e0ecfaa5164085f2a7de34ec55fb",USDTB:"0xbb188503c32fa7f61e019c3b3ae61ae6b0b3b492",SWAP_BRIDGE_ROUTER:"0x337071C06416f13b568eE644c1D714edd65509eB"},hiddenPairs:[{fromKey:"97-0xbb188503c32fa7f61e019c3b3ae61ae6b0b3b492",toKey:"612044-0x9f85c7b5d7637e18f946cc8af9c131318c6833d9"},{fromKey:"612044-0x9364ea6790f6e0ecfaa5164085f2a7de34ec55fb",toKey:"612044-0x9f85c7b5d7637e18f946cc8af9c131318c6833d9"},{fromKey:"97-0x26ca2a92ea9659e073621bb85b9117dc5944cff1",toKey:"612044-0x9364ea6790f6e0ecfaa5164085f2a7de34ec55fb"}]},production:{bridgeApi:"https://bridge-api.crosstoken.io/bridge",walletApi:"https://wallet-server.crosstoken.io/api",chainIds:{cross:612055,bsc:56},contracts:{BSC_CROSS:"0x6bf62ca91e397b5a7d1d6bce97d9092065d7a510",W_CROSS:"0x731a104a4461ae45bfef520468b43c262d35e682",NATIVE_CROSS:"0x0000000000000000000000000000000000000001",USDTX:"0x1c37d4f44ed3ec86d96868001cfa89e97112a85c",CROSSD:"0xff42c13d927a6b9265236619161accb227b6d452",USDTB:"0x55d398326f99059ff775485246999027b3197955",SWAP_BRIDGE_ROUTER:"0xB298C340816fee45cfB39B1e6EE4DB4D5739e357"},hiddenPairs:[{fromKey:"56-0x55d398326f99059ff775485246999027b3197955",toKey:"612055-0x1c37d4f44ed3ec86d96868001cfa89e97112a85c"},{fromKey:"612055-0xff42c13d927a6b9265236619161accb227b6d452",toKey:"612055-0x1c37d4f44ed3ec86d96868001cfa89e97112a85c"},{fromKey:"56-0x6bf62ca91e397b5a7d1d6bce97d9092065d7a510",toKey:"612055-0xff42c13d927a6b9265236619161accb227b6d452"}]}},je=[{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"}]}],St=[{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"}]}],nn=[{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"}]}],Ho=[{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"}]}],_e=[{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:[]}],Vo=[{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 bn(e){let t="";try{t=await e.text()}catch{}if(t){try{let o=JSON.parse(t),s=typeof o.data=="string"&&o.data||typeof o.message=="string"&&o.message||"";if(s)return`${s} (status ${e.status})`}catch{}return`${t.slice(0,300)} (status ${e.status})`}return`status ${e.status}`}async function Ge(e,t){let o=await fetch(e,{cache:"no-store",signal:t});if(!o.ok)throw new Error(`CrossD bridge adapter request failed: ${await bn(o)}`);let s=await o.json();if(s&&typeof s=="object"&&"code"in s&&typeof s.code=="number"&&s.code!==200)throw new Error(s.message||`CrossD bridge adapter API error: ${s.code}`);return s&&typeof s=="object"&&"data"in s?s.data:s}async function on(e,t,o){let s=await fetch(e,{method:"POST",cache:"no-store",signal:o,headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!s.ok)throw new Error(`CrossD bridge adapter request failed: ${await bn(s)}`);let n=await s.json();if(n&&typeof n=="object"&&"code"in n&&typeof n.code=="number"&&n.code!==200)throw new Error(n.message||`CrossD bridge adapter API error: ${n.code}`);return n&&typeof n=="object"&&"data"in n?n.data:n}function zo(e){return new Promise(t=>setTimeout(t,e))}async function Qo(e,t,{attempts:o=60,intervalMs:s=2e3}={}){for(let n=0;n<o;n+=1){try{let a=await Ge(`${e}/permit-hash/${t}`);if(Rt(a))return a}catch{}await zo(s)}return null}function ee(e,t){return`${e}-${t.toLowerCase()}`}function le(e){return ee(e.chainId,e.address)}function Ae(e){return e==="swap"||e==="deposit-swap"||e==="swap-withdraw"}function jo(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"",o=t.toLowerCase();return o.includes("quoteexactinputsingle")||o.includes("quoteexactoutputsingle")||o.includes("getamountswapbridgeout")||o.includes("getamountswapbridgein")||o.includes("execution reverted")?"Amount is too large for this route.":t.split(`
2
- `)[0]?.trim()||"Failed to quote bridge."}function rn(e){return e===56||e===97?"BSC":e===612044||e===612055?"CROSS":`Chain ${e}`}function J(e,t){return t?t.toLowerCase()===e.contracts.NATIVE_CROSS.toLowerCase()?e.contracts.W_CROSS:t:fn}function Xe(e){let t=wt(e,rt);return t.includes(".")?t.replace(/\.?0+$/,""):t}function dt(e){return Oo(e||"0",rt)}function me(e){try{return dt(e||"0")}catch{return 0n}}function Ue(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 vt(e){let t=wt(e,9);return(t.includes(".")?t.replace(/\.?0+$/,""):t)||"0"}function gt(e){return e==="bridge"?Go:Uo}function sn(e,t){if(!e||!t)return"0";let o=e*e;if(o===0n)return"0";let s=t*t,n=s>o?s-o:o-s;if(n===0n)return"0";let a=(n*100000000n+o/2n)/o;if(a>=100000000n)return"100";let g=a/1000000n,f=(a%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return f?`${g}.${f}`:`${g}`}function Xo(e){if(!e||Number(e)===0)return"0%";let[t,o=""]=e.split("."),s=o.length>4?o.slice(0,4):o;return s?`${t}.${s}%`:`${t}%`}async function an(e,t,o,s,n,a=!1){let g=pn(e,{chainId:t}),f=o;try{let p=await g?.estimateContractGas?.({account:n.account,address:n.address,abi:n.abi,functionName:n.functionName,args:n.args,value:n.value});typeof p=="bigint"&&p>0n&&(f=s?p*Ko/$o:p)}catch{}let b={gas:f};if(gn.has(t))try{let p=await g?.getGasPrice?.();typeof p=="bigint"&&p>0n&&(b.gasPrice=p)}catch{}else if(a)try{let p=await g?.estimateFeesPerGas?.();typeof p?.maxFeePerGas=="bigint"&&(b.maxFeePerGas=p.maxFeePerGas),typeof p?.maxPriorityFeePerGas=="bigint"&&(b.maxPriorityFeePerGas=p.maxPriorityFeePerGas)}catch{}return b}function yn(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 Pt(e,t){let o=yn(t);return o>=10000n?0n:e*(10000n-o)/10000n}function Yo(e,t){let o=yn(t);return(e*(10000n+o)+9999n)/10000n}function ct(){return BigInt(Math.floor(Date.now()/1e3)+1800)}var Zo={100:"0.01%",500:"0.05%",3e3:"0.3%",1e4:"1%"};function Jo(e){return Zo[e]??`${e/1e4}%`}function er(e,t){let o=Number(e||"0");return!Number.isFinite(o)||o<=0?"0":(o*t/1e6).toFixed(8).replace(/\.?0+$/,"")}function cn(e){return Xe(e)}function dn(e,t){let o=Number(t??"0");return!Number.isFinite(o)||o<=0?0n:e*BigInt(Math.floor(o))/1000n}function bt(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(s=>s.toLowerCase()===o)}function tr(e,t,o){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(n=>bt(t,n.from)&&bt(o,n.to)||bt(t,n.to)&&bt(o,n.from))}function nr(e){if(Ae(e.type))return null;if(e.type==="swap-bridge"){let t=e.steps.find(o=>o.type==="bridge");return t?{from:t.fromChain,to:t.toChain,token:t.fromToken}:null}if(e.type==="bridge-swap"){let t=e.steps.find(o=>o.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 or({input:e,path:t,config:o}){if(!o||Ae(t.type))return"";let s=Ue(o.minimumValue),n=Ue(o.gasFee??o.gas_fee),a=t.type==="swap-bridge"?s+n*12n/10n:s;return a<=0n?"":e.fromAmount&&me(e.fromAmount)<a&&t.type!=="swap"?`Minimum ${cn(a)}`:t.type==="swap-bridge"&&e.toAmount&&me(e.toAmount)<a?`Available ${cn(a)} or more.`:""}function rr({input:e,path:t,config:o}){if(!o||t.type!=="bridge"&&t.type!=="bridge-swap")return"";let s=Ue(o.gasFee??o.gas_fee);if(s<=0n||!e.fromAmount)return"";let n=me(e.fromToken.balance||"0"),a=me(e.fromAmount);return n-s<a?`Insufficient network fee(${e.fromToken.symbol})`:""}function sr(e,t){let o=new Set;return e?.list?.forEach(s=>{let n=s.localChain??s.local_chain;n&&Object.entries(s.pairs||{}).forEach(([a,g])=>{g.forEach(f=>{f.localToken&&o.add(ee(n,f.localToken)),f.remoteToken&&o.add(ee(Number(a),f.remoteToken))})})}),Object.entries(t?.swapPools||t?.swap_pools||{}).forEach(([s,n])=>{n.forEach(a=>{a.token0&&o.add(ee(Number(s),a.token0)),a.token1&&o.add(ee(Number(s),a.token1))})}),o}function ir(e,t){return!e||!t?null:ee(e,t)}function ar({envConfig:e,bridgePairList:t,swapPools:o,tokenInfo:s,tokenStats:n}){let a=sr(t,o),g=new Map;n?.forEach(b=>{let p=ir(Number(b.chainId??b.chain_id),b.address);p&&g.set(p,b)});let f={};return a.forEach(b=>{let[p,h]=b.split("-"),I=Number(p),S=s?.find(T=>Number(T.chainId??T.chain_id)===I&&T.address?.toLowerCase()===h);if(!S?.symbol||!S.name)return;let m=g.get(b);f[b]={key:b,chainId:I,address:h,symbol:S.symbol,name:S.name,decimals:S.decimals||rt,image:S.image||S.icon_url,price:m?.price?Number(m.price):void 0,isNativeToken:h.toLowerCase()===e.contracts.NATIVE_CROSS.toLowerCase()}}),f}function wn(e,t){return t?.list?.find(o=>(o.localChain??o.local_chain)===e)?.bridge||""}function hn(e,t,o){let[s,n]=e.split("-"),[a,g]=t.split("-"),f=Number(s),b=Number(a);for(let p of o?.list||[]){if((p.localChain??p.local_chain)!==f)continue;let h=p.pairs?.[a];if(h){for(let I of h)if(I.localToken?.toLowerCase()===n&&I.remoteToken?.toLowerCase()===g)return{type:"bridge",fromChain:f,fromToken:n,toChain:b,toToken:g,bridgeAddress:wn(f,o)}}}return null}function Cn(e,t,o,s){let[n,a]=e.split("-"),[g,f]=t.split("-");if(n!==g)return null;let b=Number(n),p=(o?.swapPools||o?.swap_pools)?.[n];if(!p)return null;let h=s.contracts.W_CROSS.toLowerCase(),I=s.contracts.NATIVE_CROSS.toLowerCase(),S=m=>m?.toLowerCase()===h?I:m?.toLowerCase();for(let m of p){let T=S(m.token0),P=S(m.token1);if(T===a&&P===f||P===a&&T===f){let C="swap";return b===s.chainIds.cross&&(a===I&&(C="deposit-swap"),f===I&&(C="swap-withdraw")),{pathType:C,step:{type:"swap",chain:b,fromToken:a,toToken:f,fee:m.fee||he,poolAddress:m.poolAddress||m.pool_address||""}}}}return null}function cr(e,t,o,s){let[n,a]=e.split("-"),[g]=t.split("-");if(n===g)return null;for(let f of(o?.swapPools||o?.swap_pools)?.[n]||[]){let b=f.token0?.toLowerCase(),p=f.token1?.toLowerCase(),h=b===a?p:p===a?b:null;if(!h)continue;let I=hn(ee(Number(n),h),t,s);if(I)return[{type:"swap",chain:Number(n),fromToken:a,toToken:h,fee:f.fee||he,poolAddress:f.poolAddress||f.pool_address||""},I]}return null}function dr(e,t,o,s,n){let[a,g]=e.split("-"),[f]=t.split("-");if(a===f)return null;for(let b of o?.list||[])if((b.localChain??b.local_chain)===Number(a))for(let p of b.pairs?.[f]||[]){if(p.localToken?.toLowerCase()!==g)continue;let h=p.remoteToken?.toLowerCase();if(!h)continue;let I=Cn(ee(Number(f),h),t,s,n);if(I)return[{type:"bridge",fromChain:Number(a),fromToken:g,toChain:Number(f),toToken:h,bridgeAddress:wn(Number(a),o)},I.step]}return null}function lr({envConfig:e,bridgePairList:t,swapPools:o,enrichedTokens:s}){return(n,a)=>{let g=s[n],f=s[a];if(!g||!f||n===a)return null;let b=hn(n,a,t);if(b)return{type:"bridge",steps:[b],from:g,to:f};let p=Cn(n,a,o,e);if(p)return{type:p.pathType,steps:[p.step],from:g,to:f};let h=cr(n,a,o,t);if(h)return{type:"swap-bridge",steps:h,from:g,to:f};let I=dr(n,a,t,o,e);return I?{type:"bridge-swap",steps:I,from:g,to:f}:null}}function ln(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 ur(e){return e.length<=10?e:`${e.slice(0,6)}...${e.slice(-4)}`}function mr(e){return e.includes(".")?e.replace(/\.?0+$/,"")||"0":e}function pr(e,t){let o=e.startsWith("-"),s=o?e.slice(1):e,[n,a=""]=s.split("."),g=a.slice(0,t).replace(/0+$/,""),f=g?`${n}.${g}`:n;return o?`-${f}`:f}function fr(e){let t=e.startsWith("-"),o=t?e.slice(1):e,[s,n]=o.split("."),a=s.replace(/\B(?=(\d{3})+(?!\d))/g,","),g=n?`${a}.${n}`:a;return t?`-${g}`:g}function At(e){if(e==null||e==="")return"0";let t=String(e),o=Number(t);return!Number.isFinite(o)||o===0?"0":fr(pr(t,4))}function un(e,t){if(e==null||e==="")return"0";try{return mr(wt(BigInt(String(e)),t.decimals))}catch{return"0"}}function Rt(e){return!!(e&&/^0x[0-9a-fA-F]+$/.test(e))}function gr(e){return e?new Date(e*1e3).toISOString():new Date().toISOString()}function br(e,t){return t.toLowerCase()===e.contracts.W_CROSS.toLowerCase()?e.contracts.NATIVE_CROSS:t}function yr(e,t){let o=ur(t);return{name:o,symbol:o,chainId:e,address:t,decimals:rt,balance:"0"}}function mn({envConfig:e,tokenByBridgeKey:t,chainId:o,address:s}){if(!s)return null;let n=br(e,s);return t.get(ee(o,n))||t.get(ee(o,s))||yr(o,n)}function yt(e){return e?.toLowerCase()||""}function wr(e){if(e.source==="swap")return"swap";let t=yt(e.fromToken??e.from_token),o=yt(e.toToken??e.to_token),s=yt(e.swapTokenIn??e.swap_token_in),n=yt(e.swapTokenOut??e.swap_token_out);return o&&s&&o===s?"bridge-swap":t&&n&&t===n?"swap-bridge":"bridge"}function hr(e,t){let o=e.status??0,s=e.extracallSuccess??e.extracall_success??!1;return t==="bridge-swap"&&o===1&&!s?"failed":o===1?"success":"pending"}function Cr({envConfig:e,item:t,tokenByBridgeKey:o}){let s=Number(t.fromChainID??t.from_chain_id??0),n=Number(t.toChainID??t.to_chain_id??0);if(!s||!n)return null;let a=wr(t),g=t.swapTokenIn??t.swap_token_in,f=t.swapTokenOut??t.swap_token_out,b=t.swapAmountIn??t.swap_amount_in,p=t.swapAmountOut??t.swap_amount_out,h=t.fromToken??t.from_token,I=t.toToken??t.to_token,S=t.value,m=t.value;a==="swap"?(h=g,I=f,S=b,m=p):a==="swap-bridge"?(h=g,S=b,m=t.value):a==="bridge-swap"&&(I=f,S=b,m=p);let T=mn({envConfig:e,tokenByBridgeKey:o,chainId:s,address:h}),P=mn({envConfig:e,tokenByBridgeKey:o,chainId:n,address:I}),C=t.initiatedTxHash??t.initiated_tx_hash;return!T||!P||!Rt(C)?null:{id:`${C}-${t.index??""}`,timestamp:gr(t.initiatedTime??t.initiated_time),txHash:C,fromToken:T,toToken:P,fromAmount:un(S,T),toAmount:un(m,P),summary:{pathType:a},status:hr(t,a)}}function kr(e){let t=new Map;return e.flat().forEach(o=>{let s=Number(o.chainId??o.chain_id),n=o.address?.toLowerCase();if(!s||!n)return;let a=o.quantity?.numeric??o.balance??"0",g=o.quantity?.decimals??o.decimals??rt;try{t.set(ee(s,n),wt(BigInt(a||"0"),g))}catch{t.set(ee(s,n),"0")}}),t}function Ee(e,t="first"){let o=e.steps.filter(s=>s.type==="swap");return t==="last"?o[o.length-1]:o[0]}function xr(e,t){let o=(e?.swapPools||e?.swap_pools)?.[String(t.chainIds.cross)];if(!o?.length)return"";let s=t.contracts.CROSSD.toLowerCase(),n=t.contracts.USDTX.toLowerCase(),a=o.find(g=>{let f=g.token0?.toLowerCase(),b=g.token1?.toLowerCase();return f===s&&b===n||f===n&&b===s});return a?.poolAddress||a?.pool_address||""}function Tr(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 Ir(e){if(e===void 0)return;let t=10n**BigInt(rt),o=e>=50000n*t?"normal":e>10000n*t?"low":"rebalancing",s=Number(e>0n?e*100n/(100000n*t):0n);return{label:"Available Liquidity",status:o,percentage:Math.min(s,100)}}function ot(e,t,o,s){let n=[e.from,e.to].find(a=>a.chainId===t&&a.address.toLowerCase()===o.toLowerCase())??s?.[ee(t,o)];return{symbol:n?.symbol||o.slice(0,6),iconUrl:n?.image}}function Sr(e,t){let o=[];for(let n of e.steps)n.type==="swap"?(o.push({chain:n.chain,address:n.fromToken}),o.push({chain:n.chain,address:n.toToken})):(o.push({chain:n.fromChain,address:n.fromToken}),o.push({chain:n.toChain,address:n.toToken}));let s=o.filter((n,a)=>a===0||!(n.chain===o[a-1].chain&&n.address.toLowerCase()===o[a-1].address.toLowerCase()));return s.length===0?[{symbol:e.from.symbol,iconUrl:e.from.image},{symbol:e.to.symbol,iconUrl:e.to.image}]:s.map(n=>ot(e,n.chain,n.address,t))}function vr({input:e,path:t,amountData:o,gasInfo:s,liquidity:n,enrichedTokens:a,priceImpact:g}){let f=e.fromAmount||"0",b=e.toAmount||"0",p=Ee(t),h=t.steps.find(O=>O.type==="bridge"),I=t.type!=="bridge",S=!Ae(t.type),m=p?er(f,p.fee):"0",T=Number(f)>0||Number(b)>0,P=p?ot(t,p.chain,p.fromToken,a):{symbol:e.fromToken.symbol,iconUrl:e.fromToken.iconUrl},C=p?ot(t,p.chain,p.toToken,a):{symbol:e.toToken.symbol,iconUrl:e.toToken.iconUrl},k=h?ot(t,h.fromChain,h.fromToken,a):void 0,_=(O,U,te)=>T?U&&U>0n?{label:O,value:Xe(U),tone:"default",valueToken:te}:{label:O,value:"Free",tone:"accent"}:{label:O,value:"0"};return{pathType:t.type,priceImpact:g,liquidity:n,bridgeInfo:S&&h?[{label:"Route",value:`${rn(h.fromChain)} \u2192 ${rn(h.toChain)}`},_("Validator Fee",o?.exFee,k),_("Network Fee",o?.networkFee,k)]:void 0,swapInfo:I&&p?[{label:"Route",value:"",routeTokens:[ot(t,p.chain,p.fromToken,a),ot(t,p.chain,p.toToken,a)]},{label:"Price Impact",value:Xo(g)},{label:"In Amount",value:At(f),valueToken:P},{label:p&&Ae(t.type)?`Swap Fee (${Jo(p.fee||he)})`:"Swap Fee",value:At(m),valueToken:P},{label:"Out Amount",value:At(b),valueToken:C}]:void 0,txFee:[...s?.gasPrice?[{label:"Gas Price",value:`${s.gasPrice} Gwei`}]:[{label:"Priority Fee Per Gas",value:`${s?.priorityFeePerGas||"0"} Gwei`},{label:"Max Fee Per Gas",value:`${s?.maxFeePerGas||"0"} Gwei`}],{label:"Gas Limit",value:s?.gasLimit||"0"}],txFeeInfo:s?{estTxFee:s.estTxFee,isDelegateFee:s.isDelegateFee,tokenIconUrl:s.gasCurrencyIconUrl,tokenSymbol:s.gasCurrencySymbol}:{estTxFee:"0",isDelegateFee:!1}}}function Bt({env:e,walletAddress:t,enabled:o=!0}){let s=Lo(),n=qo[e],a=o,g=_o(new Map),f=nt({queryKey:["crossd-bridge-adapter",e,"pairs"],queryFn:({signal:r})=>Ge(`${n.bridgeApi}/pairs`,r),enabled:a,staleTime:3e4}),b=nt({queryKey:["crossd-bridge-adapter",e,"swap-pools"],queryFn:({signal:r})=>Ge(`${n.bridgeApi}/swap-pools`,r),enabled:a,staleTime:3e4}),p=Pe(()=>xr(b.data,n),[n,b.data]),h=nt({queryKey:["crossd-bridge-adapter",e,"available-liquidity",p],queryFn:async()=>await Ie(s,{address:n.contracts.USDTX,abi:St,functionName:"balanceOf",args:[p],chainId:n.chainIds.cross}),enabled:a&&!!p,staleTime:3e4}),I=nt({queryKey:["crossd-bridge-adapter",e,"token-info"],queryFn:({signal:r})=>Ge(`${n.walletApi}/v1/public/token/info`,r),enabled:a,staleTime:3e4}),S=nt({queryKey:["crossd-bridge-adapter",e,"token-stats"],queryFn:({signal:r})=>Ge(`${n.walletApi}/v1/public/token/stats`,r),enabled:a,staleTime:3e4}),m=Jt({queries:[n.chainIds.cross,n.chainIds.bsc].map(r=>({queryKey:["crossd-bridge-adapter",e,"balance",t,r],queryFn:({signal:i})=>{let c=new URLSearchParams({networkId:`eip155:${r}`,account:t||""});return Ge(`${n.walletApi}/v1/public/token/balance?${c}`,i)},enabled:a&&!!t,staleTime:0,refetchInterval:a&&t?5e3:!1}))}),T=Jt({queries:[n.chainIds.cross,n.chainIds.bsc].map(r=>({queryKey:["crossd-bridge-adapter",e,"gas-suggestion",r],queryFn:async({signal:i})=>{try{let x=await pn(s,{chainId:r})?.estimateFeesPerGas?.();if(x?.maxFeePerGas||x?.gasPrice)return{fast:{maxFee:x.maxFeePerGas?.toString()||x.gasPrice?.toString(),maxPriorityFee:x.maxPriorityFeePerGas?.toString()||"0"}}}catch{}let c=new URLSearchParams({chain_id:String(r),without_gas_limit:"false"});return Ge(`${n.walletApi}/v1/public/transaction/gas-suggestion/dynamic?${c}`,i)},enabled:a,staleTime:1e4,retry:1}))}),P=n.hiddenPairs,C=Pe(()=>ar({envConfig:n,bridgePairList:f.data,swapPools:b.data,tokenInfo:I.data,tokenStats:S.data}),[f.data,n,b.data,I.data,S.data]),k=Pe(()=>lr({envConfig:n,bridgePairList:f.data,swapPools:b.data,enrichedTokens:C}),[f.data,C,n,b.data]),_=Pe(()=>kr(m.map(r=>r.data).filter(r=>Array.isArray(r))),[m]),O=Pe(()=>{let r=new Map;return Object.values(C).forEach(i=>{let c=ln(i,_);r.set(i.key,c)}),r},[_,C]),U=Pe(()=>{let r=new Map,i=O.get(ee(n.chainIds.cross,n.contracts.NATIVE_CROSS));i&&r.set(n.chainIds.cross,{symbol:i.symbol,iconUrl:i.iconUrl});let c=I.data?.find(l=>Number(l.chainId??l.chain_id)===n.chainIds.bsc&&(l.symbol??"").toUpperCase()==="BNB");return c&&r.set(n.chainIds.bsc,{symbol:c.symbol??"BNB",iconUrl:c.image??c.icon_url}),r},[n,O,I.data]),te=nt({queryKey:["crossd-bridge-adapter",e,"history",t],queryFn:({signal:r})=>on(`${n.bridgeApi}/history`,{owner:t,page:1,size:20,sort:"desc",status:"all"},r),enabled:a&&!!t,staleTime:0,refetchInterval:a&&t?5e3:!1}),z=Pe(()=>(te.data?.histories||[]).map(r=>Cr({envConfig:n,item:r,tokenByBridgeKey:O})).filter(r=>!!r),[te.data?.histories,n,O]),K=Pe(()=>Ir(h.data),[h.data]),D=T[0]?.data,M=T[1]?.data,Ce=Pe(()=>{let r=new Map;return D&&r.set(n.chainIds.cross,D),M&&r.set(n.chainIds.bsc,M),r},[M,D,n.chainIds.bsc,n.chainIds.cross]),E=se((r,i,c)=>{let l=Ce.get(r.from.chainId)?.fast,x=i?c?.gasLimit??gt(r.type):0n,v=c?.gasPrice&&c.gasPrice>0n?c.gasPrice:0n,R=c?.maxFeePerGas&&c.maxFeePerGas>0n?c.maxFeePerGas:0n,B=c?.maxPriorityFeePerGas&&c.maxPriorityFeePerGas>0n?c.maxPriorityFeePerGas:0n,F=Ue(l?.maxFee??l?.max_fee),u=Ue(l?.maxPriorityFee??l?.max_priority_fee),d=R>0n?R:F>0n?F:v,w=B>0n?B:u>0n?u:d,y=v>0n?v:d,N=gn.has(r.from.chainId)&&y>0n,Y=x*(N?y:d),ne=O.get(ee(r.from.chainId,n.contracts.NATIVE_CROSS)),$=r.type!=="swap-bridge",Z=U.get(r.from.chainId);return{estTxFee:i?Xe(Y):"0",priorityFeePerGas:i&&!N?vt(w):"0",maxFeePerGas:i&&!N?vt(d):"0",gasLimit:i?x.toString():"0",gasPrice:i&&N?vt(y):void 0,isDelegateFee:r.type==="swap-bridge"?!1:tr(n,r.from.address,r.to.address),tokenIconUrl:$?ne?.iconUrl:void 0,tokenSymbol:$?ne?.symbol:void 0,gasCurrencyIconUrl:Z?.iconUrl,gasCurrencySymbol:Z?.symbol}},[n,Ce,U,O]),A=se(async r=>{let i=nr(r);if(!i)return null;let c=`${e}:${i.from}:${i.to}:${i.token.toLowerCase()}`,l=g.current.get(c);if(l)return l;let x=(async()=>{let v=new URLSearchParams({from:String(i.from),to:String(i.to),token:i.token});try{return(await Ge(`${n.bridgeApi}/token-config?${v}`)).config??null}catch{return null}})();return g.current.set(c,x),x},[e,n.bridgeApi]),W=Pe(()=>{let r=Object.values(C).map(c=>ln(c,_)),i=ee(n.chainIds.cross,n.contracts.CROSSD);return r.sort((c,l)=>{let x=le(c).toLowerCase()===i.toLowerCase(),v=le(l).toLowerCase()===i.toLowerCase();return x!==v?x?-1:1:le(c).localeCompare(le(l))})},[_,C,n]),ke=se(r=>{let i=le(r),c=i.toLowerCase(),l=[];Object.keys(C).forEach(R=>{let B=R.toLowerCase();if(c===B||P.some(d=>d.fromKey===c&&d.toKey===B))return;let F=k(i,R);if(!F)return;let u=O.get(R);u&&l.push({token:u,path:F})});let x=ee(n.chainIds.cross,n.contracts.CROSSD),v=ee(n.chainIds.cross,n.contracts.NATIVE_CROSS);return l.sort((R,B)=>{if(c===x.toLowerCase()){let y=le(R.token).toLowerCase()===v.toLowerCase(),N=le(B.token).toLowerCase()===v.toLowerCase();if(y!==N)return y?-1:1}let F=Ae(R.path.type),u=Ae(B.path.type);if(F!==u)return F?-1:1;let d=R.token.chainId===r.chainId,w=B.token.chainId===r.chainId;return d!==w?d?-1:1:le(R.token).localeCompare(le(B.token))}),l.map(R=>R.token)},[C,n,k,P,O]),qe=se(async r=>await Ie(s,{address:n.contracts.SWAP_BRIDGE_ROUTER,abi:je,functionName:"quoter",chainId:r}),[n.contracts.SWAP_BRIDGE_ROUTER,s]),j=se(async r=>{No(s)!==r&&await Do(s,{chainId:r})},[s]),q=se(async r=>await Ie(s,{address:n.contracts.SWAP_BRIDGE_ROUTER,abi:je,functionName:"swapRouter",chainId:r}),[n.contracts.SWAP_BRIDGE_ROUTER,s]),pe=se(async({path:r,step:i,amount:c,source:l})=>{let x=await qe(i.chain),v=i.poolAddress?Ie(s,{address:i.poolAddress,abi:Ho,functionName:"slot0",chainId:i.chain}).then(F=>F?.[0]).catch(()=>{}):Promise.resolve(void 0);if(l==="from"){let F=await Ie(s,{address:x,abi:nn,functionName:"quoteExactInputSingle",args:[{tokenIn:J(n,i.fromToken),tokenOut:J(n,i.toToken),amountIn:dt(c),fee:i.fee||he,sqrtPriceLimitX96:0n}],chainId:i.chain}),u=sn(await v,F[1]);return{amount:Xe(F[0]),path:r,priceImpact:u}}let R=await Ie(s,{address:x,abi:nn,functionName:"quoteExactOutputSingle",args:[{tokenIn:J(n,i.fromToken),tokenOut:J(n,i.toToken),amount:dt(c),fee:i.fee||he,sqrtPriceLimitX96:0n}],chainId:i.chain}),B=sn(await v,R[1]);return{amount:Xe(R[0]),path:r,priceImpact:B}},[n,qe,s]),we=se(async(r,i)=>{if(!t)throw new Error("Wallet is not connected.");let c=gt(i.type);if(Ae(i.type)){let d=Ee(i,"first");if(!d)throw new Error("Swap route is not available.");let w=me(r.fromAmount),y=me(r.toAmount);if(w<=0n)throw new Error("Bridge amount is empty.");if(y<=0n)throw new Error("Bridge quote is not ready.");let N=await q(d.chain),V=Pt(y,r.slippage),Y=i.type==="swap-withdraw"?fn:t,ne={tokenIn:J(n,d.fromToken),tokenOut:J(n,d.toToken),fee:d.fee||he,recipient:Y,deadline:ct(),amountIn:w,amountOutMinimum:V,sqrtPriceLimitX96:0n};if(i.type==="swap-withdraw"){let $=at({abi:_e,functionName:"exactInputSingle",args:[ne]}),Z=at({abi:_e,functionName:"unwrapWETH9",args:[V,t]});return{address:N,abi:_e,functionName:"multicall",args:[[$,Z]],chainId:d.chain,fallbackGasLimit:c}}if(i.type==="deposit-swap"){let $=at({abi:_e,functionName:"exactInputSingle",args:[ne]}),Z=at({abi:_e,functionName:"refundETH",args:[]});return{address:N,abi:_e,functionName:"multicall",args:[[$,Z]],value:w,chainId:d.chain,fallbackGasLimit:c}}return{address:N,abi:_e,functionName:"exactInputSingle",args:[ne],chainId:d.chain,fallbackGasLimit:c}}if(i.type==="swap-bridge"){let d=Ee(i,"first");if(!d)throw new Error("Swap bridge route is not available.");let w=me(r.fromAmount),y=me(r.toAmount);if(w<=0n)throw new Error("Bridge amount is empty.");if(y<=0n)throw new Error("Bridge quote is not ready.");let N=n.contracts.SWAP_BRIDGE_ROUTER,V=ct(),Y={toChainID:BigInt(i.to.chainId),recipient:t,extraData:"0x"},ne={tokenIn:J(n,i.from.address),tokenOut:J(n,d.toToken),fee:d.fee||he,sqrtPriceLimitX96:0n,bridgeParams:Y};if(r.lastChangedBy==="to"){let Z={...ne,amountOut:y,amountInMaximum:Yo(w,r.slippage)};return{address:N,abi:je,functionName:"swapBridgeExactOutputSingle",args:[Z,V],value:i.from.isNativeToken?Z.amountInMaximum:void 0,chainId:i.from.chainId,fallbackGasLimit:c}}let $={...ne,amountIn:w,amountOutMinimum:Pt(w,r.slippage)};return{address:N,abi:je,functionName:"swapBridgeExactInputSingle",args:[$,V],value:i.from.isNativeToken?w:void 0,chainId:i.from.chainId,fallbackGasLimit:c}}let l=i.steps.find(d=>d.type==="bridge");if(!l?.bridgeAddress)throw new Error("Bridge route is not available.");let x=me(r.fromAmount);if(x<=0n)throw new Error("Bridge amount is empty.");let v=await A(i),R=Ue(v?.gasFee??v?.gas_fee),B=dn(x,v?.exFeeRate??v?.ex_fee_rate),F="0x";if(i.type==="bridge-swap"){let d=Ee(i,"last");if(!d)throw new Error("Bridge swap route is not available.");let w=me(r.toAmount);if(w<=0n)throw new Error("Bridge quote is not ready.");let y=await q(i.to.chainId),N=Pt(w,r.slippage),V=at({abi:_e,functionName:"exactInputSingle",args:[{tokenIn:J(n,d.fromToken),tokenOut:J(n,d.toToken),fee:d.fee||he,recipient:t,deadline:ct(),amountIn:x,amountOutMinimum:N,sqrtPriceLimitX96:0n}]});F=`${y}${V.slice(2)}`}let u=[BigInt(i.to.chainId),i.from.address,t,x,R,B,F];return{address:l.bridgeAddress,abi:Vo,functionName:"bridgeToken",args:u,value:i.from.isNativeToken?x+B+R:void 0,chainId:i.from.chainId,fallbackGasLimit:c}},[n,A,q,t]),Oe=se(async(r,i)=>{if(i.type==="bridge"||i.type==="bridge-swap")return we(r,i);if(!t)throw new Error("Wallet is not connected.");let c=me(r.fromAmount);if(c<=0n)throw new Error("Bridge amount is empty.");if(i.type==="swap-bridge"){let R=Ee(i,"first");if(!R)throw new Error("Swap bridge route is not available.");let B=n.contracts.SWAP_BRIDGE_ROUTER,F={tokenIn:J(n,i.from.address),tokenOut:J(n,R.toToken),fee:R.fee||he,sqrtPriceLimitX96:0n,bridgeParams:{toChainID:BigInt(i.to.chainId),recipient:t,extraData:"0x"},amountIn:c,amountOutMinimum:0n};return{address:B,abi:je,functionName:"swapBridgeExactInputSingle",args:[F,ct()],value:i.from.isNativeToken?c:void 0,chainId:i.from.chainId,fallbackGasLimit:gt(i.type)}}let l=Ee(i,"first");if(!l)throw new Error("Swap route is not available.");let x=await q(l.chain),v={tokenIn:J(n,l.fromToken),tokenOut:J(n,l.toToken),fee:l.fee||he,recipient:t,deadline:ct(),amountIn:c,amountOutMinimum:0n,sqrtPriceLimitX96:0n};return{address:x,abi:_e,functionName:"exactInputSingle",args:[v],value:i.from.isNativeToken?c:void 0,chainId:l.chain,fallbackGasLimit:gt(i.type)}},[we,n,q,t]),Ne=se(async(r,i)=>{if(!t)return null;try{let c=await Oe(r,i),l=Ae(i.type)||i.type==="swap-bridge",x=await an(s,c.chainId,c.fallbackGasLimit,l,{account:t,address:c.address,abi:c.abi,functionName:c.functionName,args:c.args,value:c.value},!0);return{gasLimit:x.gas,gasPrice:x.gasPrice,maxFeePerGas:x.maxFeePerGas,maxPriorityFeePerGas:x.maxPriorityFeePerGas}}catch{return null}},[Oe,s,t]),He=se(async r=>{let i=le(r.fromToken),c=le(r.toToken),l=k(i,c);if(!l)return{error:"Route is not available."};let x=r.lastChangedBy==="to"?r.toAmount:r.fromAmount,v=!!x&&Number(x)>0,R=Tr(l,n)?K:void 0,B=async(V,Y,ne)=>{let $=v?await Ne(V,l):null,Z=E(l,v,$);return vr({input:V,path:l,gasInfo:Z,amountData:Y,liquidity:R,enrichedTokens:C,priceImpact:ne})};if(!x||Number(x)<=0)return{fromAmount:r.fromAmount,toAmount:r.toAmount,summary:await B(r)};let F=await A(l),u=Ue(F?.gasFee??F?.gas_fee),d=l.type==="bridge"||l.type==="bridge-swap"?{networkFee:u}:void 0,w=l.type==="bridge"?r.lastChangedBy==="to"?{...r,fromAmount:r.toAmount}:{...r,toAmount:r.fromAmount}:r,y=or({input:w,path:l,config:F});if(y)return{fromAmount:w.fromAmount,toAmount:w.toAmount,summary:await B(w,d),error:y};let N=rr({input:w,path:l,config:F});if(N)return{fromAmount:w.fromAmount,toAmount:w.toAmount,summary:await B(w,d),error:N};if(l.type==="bridge")return{fromAmount:w.fromAmount,toAmount:w.toAmount,summary:await B(w,d)};try{if(l.type==="swap-bridge"){let $=Ee(l,"first"),Z=n.contracts.SWAP_BRIDGE_ROUTER;if(!$)return{error:"Swap bridge route is not ready."};let Ze=ge=>pe({path:l,step:$,amount:ge,source:"from"}).then(We=>We.priceImpact).catch(()=>{});if(r.lastChangedBy==="from"){let ge=await Ie(s,{address:Z,abi:je,functionName:"getAmountSwapBridgeOut",args:[BigInt(l.to.chainId),J(n,l.from.address),J(n,$.toToken),$.fee||he,dt(r.fromAmount)],chainId:l.from.chainId}),We=Xe(ge[1]),ut={...r,toAmount:We};return{toAmount:We,summary:await B(ut,{networkFee:ge[3],exFee:ge[4]},await Ze(r.fromAmount))}}let Ve=await Ie(s,{address:Z,abi:je,functionName:"getAmountSwapBridgeIn",args:[BigInt(l.to.chainId),J(n,l.from.address),J(n,$.toToken),$.fee||he,dt(r.toAmount)],chainId:l.from.chainId}),ce=Xe(Ve[1]),Je={...r,fromAmount:ce};return{fromAmount:ce,summary:await B(Je,{networkFee:Ve[3],exFee:Ve[4]},await Ze(ce))}}let V=l.type==="bridge-swap"?Ee(l,"last"):Ee(l,"first");if(!V)return{error:"Swap route is not available."};let Y=await pe({path:l,step:V,amount:x,source:r.lastChangedBy});if(r.lastChangedBy==="from"){let $={...r,toAmount:Y.amount};return{toAmount:Y.amount,summary:await B($,d,Y.priceImpact)}}let ne={...r,fromAmount:Y.amount};return{fromAmount:Y.amount,summary:await B(ne,d,Y.priceImpact)}}catch(V){return{fromAmount:r.fromAmount,toAmount:r.toAmount,summary:await B(r,d),error:jo(V)}}},[K,E,C,n,Ne,k,A,pe,s]),Fe=se(async r=>{if(r.from.isNativeToken)return null;if(r.type==="swap"||r.type==="deposit-swap"||r.type==="swap-withdraw")return q(r.from.chainId);if(r.type==="swap-bridge")return n.contracts.SWAP_BRIDGE_ROUTER;let i=r.steps.find(c=>c.type==="bridge");return i?.bridgeAddress?i.bridgeAddress:null},[n.contracts.SWAP_BRIDGE_ROUTER,q]),fe=se(async r=>{if(!t)throw new Error("Wallet is not connected.");let i=le(r.fromToken),c=le(r.toToken),l=k(i,c);if(!l)throw new Error("Route is not available.");if(!Ae(l.type)&&l.type!=="swap-bridge"||l.from.isNativeToken)return null;let x=me(r.fromAmount);if(x<=0n)return null;let v=await Fe(l);return!v||await Ie(s,{address:l.from.address,abi:St,functionName:"allowance",args:[t,v],chainId:l.from.chainId})>=x?null:{token:r.fromToken,tokenAddress:l.from.address,spenderAddress:v,amount:r.fromAmount}},[k,Fe,s,t]),ae=se(async(r,i)=>{let c=me(i.amount||r.fromAmount);if(c<=0n)throw new Error("Approval amount is empty.");await j(i.token.chainId);let l=await en(s,{address:i.tokenAddress,abi:St,functionName:"approve",args:[i.spenderAddress,c],chainId:i.token.chainId});await Wo(s,{hash:l,chainId:i.token.chainId})},[j,s]),De=se(async(r,i)=>{let c=await we(r,i);await j(c.chainId);let l=await an(s,c.chainId,c.fallbackGasLimit,Mo(i.type),{account:t,address:c.address,abi:c.abi,functionName:c.functionName,args:c.args,value:c.value});return{txHash:await en(s,{address:c.address,abi:c.abi,functionName:c.functionName,args:c.args,value:c.value,chainId:c.chainId,...l}),fromToken:r.fromToken,toToken:r.toToken,fromAmount:r.fromAmount,toAmount:r.toAmount}},[we,j,s,t]),X=se(async(r,i)=>{let c=t;if(!c)throw new Error("Wallet is not connected.");let l=i.steps.find(We=>We.type==="bridge");if(!l?.bridgeAddress)throw new Error("Bridge route is not available.");let x=i.from.address,v=i.from.chainId,R=me(r.fromAmount);if(R<=0n)throw new Error("Bridge amount is empty.");let B=await A(i),F=Ue(B?.gasFee??B?.gas_fee),u=dn(R,B?.exFeeRate??B?.ex_fee_rate),d=R+u+F,[w,y]=await Promise.all([Ie(s,{address:x,abi:tn,functionName:"name",chainId:v}),Ie(s,{address:x,abi:tn,functionName:"nonces",args:[c],chainId:v})]),N=BigInt(Math.floor(Date.now()/1e3)+300),V=await Fo(s,{domain:{name:w,version:"1",chainId:v,verifyingContract:x},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:c,spender:l.bridgeAddress,value:d,nonce:y,deadline:N}}),{r:Y,s:ne,v:$,yParity:Z}=Eo(V),Ze=$!==void 0?Number($):Z+27,Ve={exFee:u.toString(),from:v,fromToken:x,nonce:Number(y),gasFee:F.toString(),permitArgs:{account:c,deadline:N.toString(),r:Y,s:ne,token:x,v:Ze,value:d.toString()},to:c,toChainID:String(i.to.chainId),value:d.toString()},ce=await on(`${n.bridgeApi}/permit`,Ve),Je=ce?.requestId??ce?.request_id;if(!Je)throw new Error("Bridge permit request failed.");let ge=await Qo(n.bridgeApi,Je);if(!Rt(ge))throw new Error("Bridge submitted, but confirmation timed out. Check History shortly.");return{txHash:ge,fromToken:r.fromToken,toToken:r.toToken,fromAmount:r.fromAmount,toAmount:r.toAmount}},[n,A,s,t]),Se=se(async r=>{let i=le(r.fromToken),c=le(r.toToken),l=k(i,c);if(!l)throw new Error("Route is not available.");if(!(Ae(l.type)||l.type==="swap-bridge"||l.type==="bridge-swap"||l.type==="bridge"))throw new Error("This bridge route is not supported yet.");return{...l.type==="bridge"&&l.from.chainId===n.chainIds.bsc&&l.from.address.toLowerCase()===n.contracts.BSC_CROSS.toLowerCase()?await X(r,l):await De(r,l),pathType:l.type,routeTokens:Sr(l,C)}},[C,n,k,X,De]);return{bridgeTokens:W,bridgeHistory:z,getBridgeApproval:fe,approveBridge:ae,getBridgeQuote:He,getBridgeToTokens:ke,submitBridge:Se,isLoading:f.isLoading||b.isLoading||I.isLoading||S.isLoading||m.some(r=>r.isLoading)}}import{useEffect as kn,useRef as Pr,useState as xn}from"react";import{useAccount as Ar}from"wagmi";function _t(e){let{address:t,connector:o}=Ar(),{currentWallet:s}=Be(),n=e?.walletId!==void 0?e.walletId:s,a=e?.connector!==void 0?e.connector:o,g=e?.address!==void 0?e.address:t,[f,b]=xn({loginType:null,accountName:null,accounts:[],isResolved:!1}),p=Pr(new Map),[h,I]=xn(0);return kn(()=>{let S=!1;if(n!=="cross_embedded")return b({loginType:null,accountName:null,accounts:[],isResolved:!0}),()=>{S=!0};if(!a)return b({loginType:null,accountName:null,accounts:[],isResolved:!1}),()=>{S=!0};b(C=>({...C,isResolved:!1}));let m=20,T=300,P=async()=>{if(typeof a.getProvider!="function")return"retry";let C;try{C=await a.getProvider()}catch{return"retry"}let k=C?.sdk;if(!k)return"giveup";try{let W=k.getRNBridgeActiveWallet?.(),ke=W?.walletName?.trim();W&&ke&&p.current.set(W.address.toLowerCase(),ke)}catch{}let[_,O]=await Promise.all([k.getUserInfo?.().catch(()=>null)??null,k.getAddresses?.().catch(()=>null)??null]);if(S)return"done";let U=_?.loginType,te=U==="google"||U==="apple"?U:null;if(!te)return"retry";let z=g?.toLowerCase(),K=z&&Array.isArray(O)?O.find(W=>W.address.toLowerCase()===z):null,D=Array.isArray(O)?O.filter(W=>/^0x[a-fA-F0-9]{40}$/.test(W.address)).map(W=>({address:W.address.toLowerCase(),...Number.isFinite(W.index)?{index:W.index}:{},...W.name?.trim()?{name:W.name.trim()}:{}})):[],M=z?p.current.get(z)?.trim():void 0,Ce=!K&&z&&/^0x[a-fA-F0-9]{40}$/.test(z)?[...D,{address:z,index:D.length,...M?{name:M}:{}}]:D,A=M||K?.name?.trim()||(typeof K?.index=="number"?`Account ${K.index+1}`:g?`${g.slice(0,6)}\u2026${g.slice(-4)}`:null);return b({loginType:te,accountName:A,accounts:Ce,isResolved:!0}),"done"};return(async()=>{for(let C=0;C<m;C++){if(S)return;let k=await P();if(k==="done")return;if(k==="giveup"){S||b({loginType:null,accountName:null,accounts:[],isResolved:!0});return}await new Promise(_=>setTimeout(_,T))}S||b({loginType:null,accountName:null,accounts:[],isResolved:!0})})(),()=>{S=!0}},[n,a,g,h]),kn(()=>{if(n!=="cross_embedded"||!a||typeof a.getProvider!="function")return;let S=!1,m;return(async()=>{let T;try{T=await a.getProvider()}catch{return}if(S)return;let P=T?.sdk;P?.on&&(m=P.on("addressChanged",({address:C,walletName:k})=>{let _=k?.trim();_&&(p.current.set(C.toLowerCase(),_),I(O=>O+1))}))})(),()=>{S=!0,m?.()}},[n,a]),f}import{Fragment as Sn,jsx as ue,jsxs as Ye}from"react/jsx-runtime";var Gr=[{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"}]}],Ur=[{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"}]}],Kr={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"}},Nt=10n**18n,$r={google:{name:"Google",iconUrl:Pn,connectorId:$e.CROSSx},apple:{name:"Apple",iconUrl:Wt,connectorId:$e.CROSSx},cross:{name:"CROSSx",iconUrl:Dt,connectorId:$e.CROSSx},metamask:{name:"MetaMask",iconUrl:An,connectorId:$e.MetaMask},binance:{name:"Binance Wallet",iconUrl:vn,connectorId:$e.Binance}};function qr(e){switch(e){case"cross_embedded":return $e.CROSSx;case"metamask":return $e.MetaMask;case"binance":return $e.Binance;default:return}}function Hr(e,t){switch(e){case"cross_embedded":return t==="google"?{name:"Google",iconUrl:Pn}:t==="apple"?{name:"Apple",iconUrl:Wt}:{name:"CROSSx",iconUrl:Dt};case"cross_wallet":return{name:"CROSSx Wallet",iconUrl:Dt};case"cross_extension":return{name:"CROSSx Extension",iconUrl:Mr};case"metamask":return{name:"MetaMask",iconUrl:An};case"binance":return{name:"Binance Wallet",iconUrl:vn};default:return null}}var Vr="Bridge is available only with the CROSSx 2.0 wallet.",zr="Send is available only with the CROSSx 2.0 wallet.";function Qr({label:e="Connect Wallet",className:t,style:o,walletInfoStyle:s,user:n,enablePortfolio:a,portfolio:g,theme:f,accountName:b,connectorId:p,showPortfolio:h,sendAccounts:I,getTransactionReceipt:S,sendTransaction:m,estimateGas:T,onDisconnect:P,onSelectWallet:C,onBuy:k,onRampRedirectUrl:_,bridgeTokens:O,bridgeHistory:U,getBridgeQuote:te,getBridgeToTokens:z,getBridgeApproval:K,approveBridge:D,submitBridge:M,showBalance:Ce=!0,env:E,...A}){let{address:W,isConnected:ke,connector:qe,chain:j}=_r(),q=Or(),pe=Er(),{switchChainAsync:we}=Fr(),{sendTransactionAsync:Oe}=Nr(),{connectWallet:Ne,disconnect:He,selectWallet:Fe,currentWallet:fe,isConnecting:ae}=Be(),De=it(),X=f??De?.mode??"dark",Se=lt(()=>Dr(E),[E]),r=n?.address??W,i=n?$r[n.provider]:null,{loginType:c,accountName:l,accounts:x}=_t({walletId:fe,connector:qe,address:r}),v=lt(()=>i?{name:i.name,iconUrl:i.iconUrl}:Hr(fe,c),[i,fe,c]),R=b??n?.name??l??void 0,B=i?i.connectorId:qr(fe),F=p??B,u=g??h??!!a,d=Bt({env:Se,walletAddress:r,enabled:ke&&!!r&&Ce}),w=O??d.bridgeTokens,y=U??d.bridgeHistory,N=te??d.getBridgeQuote,V=z??d.getBridgeToTokens,Y=K??d.getBridgeApproval,ne=D??d.approveBridge,$=M??d.submitBridge,Z=Ke(()=>{Ne().catch(L=>{console.error("[crossx-kit] connectWallet error:",L)})},[Ne]),Ze=Ke(()=>{He()},[He]),Ve=P??Ze,ce=Wr(),{eligibility:Je}=Lr({network:j?String(j.id):void 0}),ge=Je?.allowed===!0,We=lt(()=>{if(k)return k;if(!(!ce||!j||!ge))return()=>ce.open({crypto:j.nativeCurrency?.symbol??"USDT",network:String(j.id),..._?{redirectUrl:_}:{}}).then(()=>{}).catch(L=>{throw console.warn("[crossx-kit] onramp open failed:",L),L})},[k,ce,j,ge,_]),ut=Br();Rr(()=>{if(ce?.onStatus)return ce.onStatus(()=>{ut.invalidateQueries()})},[ce,ut]);let On=lt(()=>{if(!k&&!(!ce||!j)&&!ge)return"On-ramp is not available in your region."},[k,ce,j,ge]),Lt=lt(()=>n?n.provider==="google"||n.provider==="apple":fe==="cross_embedded",[n,fe]),Nn=A.onBridgeDisabledMessage??(Lt?void 0:Vr),Fn=A.onSendDisabledMessage??(Lt?void 0:zr),Dn=n?n.provider==="google"||n.provider==="apple":fe==="cross_embedded",Wn=Ke(()=>{Fe().catch(L=>{console.error("[crossx-kit] selectWallet error:",L)})},[Fe]),Mt=C??(Dn?Wn:void 0),Ln=Ke(async({hash:L,chainId:oe})=>{let re=Et(q,oe?{chainId:oe}:void 0);if(!re)return null;try{return await re.getTransactionReceipt({hash:L})}catch{return null}},[q]),Mn=Ke(async L=>{L.chainId!==void 0&&L.chainId!==pe&&await we({chainId:L.chainId});let re=L.chainId===56||L.chainId===97?{...L,type:"legacy"}:L;return(m??Oe)(re)},[m,Oe,pe,we]),Gn=u?Mn:m,Un=Ke(async L=>{let oe=L.chainId??pe,re=Et(q,oe?{chainId:oe}:void 0);if(!re)throw new Error(`publicClient for chainId ${oe??"unknown"} is not available \u2014 register the chain in createCrossxConfig({ networks }).`);let be=oe===56||oe===97,[ye,xe]=await Promise.all([re.estimateGas({account:L.from,to:L.to,value:L.value,data:L.data}),(async()=>{if(be)return{maxFeePerGas:void 0,maxPriorityFeePerGas:void 0,gasPrice:await re.getGasPrice()};try{let Q=await re.estimateFeesPerGas();return{maxFeePerGas:Q.maxFeePerGas,maxPriorityFeePerGas:Q.maxPriorityFeePerGas,gasPrice:void 0}}catch{return{maxFeePerGas:void 0,maxPriorityFeePerGas:void 0,gasPrice:await re.getGasPrice()}}})()]);return{gasLimit:ye,maxFeePerGas:xe.maxFeePerGas,maxPriorityFeePerGas:xe.maxPriorityFeePerGas,gasPrice:xe.gasPrice}},[q,pe]),Kn=T??Un,$n=Ke(async L=>{let oe={};if(!W||L.length===0)return oe;let re=L.flatMap(ye=>{let Q={address:ye,abi:Gr,chainId:pe};return[{...Q,functionName:"balanceOf",args:[W]},{...Q,functionName:"totalSupply"},{...Q,functionName:"decimals"}]}),be;try{be=await Tn(q,{contracts:re,allowFailure:!0})}catch{return oe}return L.forEach((ye,xe)=>{let Q=xe*3,Te=be[Q],mt=be[Q+1],et=be[Q+2];!Te||Te.status!=="success"||(oe[ye.toLowerCase()]={balance:Te.result,totalSupply:mt&&mt.status==="success"?mt.result:void 0,decimals:et&&et.status==="success"?Number(et.result):void 0})}),oe},[q,W,pe]),qn=Ke(async L=>{let oe={earnedWei:0n,stakedWei:0n};if(!L)return oe;let re=Kr[Se],be={address:re.poolAddress,abi:Ur,chainId:re.crossChainId},ye;try{ye=await Tn(q,{allowFailure:!0,contracts:[{...be,functionName:"earned",args:[L]},{...be,functionName:"balanceOf",args:[L]},{...be,functionName:"posaActive"},{...be,functionName:"lastRewardBlock"},{...be,functionName:"totalStaked"}]})}catch{return oe}let xe=ze=>ye[ze]&&ye[ze].status==="success"?ye[ze].result:0n,Q=xe(0),Te=xe(1);if(ye[2]&&ye[2].status==="success"?ye[2].result:!1)return{earnedWei:Q,stakedWei:Te};let et=xe(3),Kt=xe(4);if(Kt===0n)return{earnedWei:Q,stakedWei:Te};let ht=0n;try{ht=await Et(q,{chainId:re.crossChainId})?.getBlockNumber?.()??0n}catch{return{earnedWei:Q,stakedWei:Te}}if(ht<=et)return{earnedWei:Q,stakedWei:Te};let Ct=0n;try{let ze=await fetch(re.networkStatsUrl).then(kt=>kt.json()),$t=ze?.data?.block_reward??ze?.block_reward;if($t){let[kt,Qn=""]=String($t).split("."),jn=(Qn+"0".repeat(18)).slice(0,18);Ct=BigInt(kt||"0")*Nt+BigInt(jn||"0")}}catch{}if(Ct===0n)return{earnedWei:Q,stakedWei:Te};let Vn=(ht-et)*Ct*Nt/Kt,zn=Te*Vn/Nt;return{earnedWei:Q+zn,stakedWei:Te}},[q,Se]),Gt=!Mt,Ut=t?`cb-button ${t}`:"cb-button",Hn=t?`cb-pill ${t}`:"cb-pill";return ae&&!ke?Ye(Sn,{children:[ue("style",{children:Ft}),Ye("button",{type:"button",disabled:!0,className:Ut,style:o,"aria-busy":"true",children:[ue("span",{className:"cb-spinner","aria-hidden":"true"}),ue("span",{className:"cb-button-label",children:"Connecting..."})]})]}):ke&&r?Ye("span",{"data-crossx-wallet-info":Gt?"external":"embedded",children:[ue("style",{children:Ft}),Gt&&ue("style",{children:Xr}),Ye(Ot,{...A,env:Se,theme:X,showBalance:Ce,walletAddress:r,accountName:R,sendAccounts:I??x,connectorId:F,showPortfolio:u,onDisconnect:Ve,onSelectWallet:Mt,onBuy:We,onBuyDisabledMessage:On,onBridgeDisabledMessage:Nn,onSendDisabledMessage:Fn,sendTransaction:Gn,getTransactionReceipt:S??Ln,estimateGas:Kn,lpBalanceReader:$n,stakingRewardsReader:qn,bridgeTokens:w,bridgeHistory:y,getBridgeQuote:N,getBridgeToTokens:V,getBridgeApproval:Y,approveBridge:ne,submitBridge:$,style:s,children:[ue(Ot.Trigger,{asChild:!0,children:Ye("button",{type:"button",className:Hn,style:o,"aria-label":`Connected with ${v?.name??"wallet"}: ${In(r)}`,children:[v?.iconUrl?ue("img",{src:v.iconUrl,alt:"",width:20,height:20,className:"cb-pill-icon","data-provider":v.iconUrl===Wt?"apple":void 0}):ue("span",{className:"cb-pill-icon-placeholder","aria-hidden":"true"}),ue("span",{className:"cb-pill-address",children:In(r)})]})}),ue(Ot.Content,{align:"end",sideOffset:8})]})]}):Ye(Sn,{children:[ue("style",{children:Ft}),Ye("button",{type:"button",onClick:Z,className:Ut,style:o,"aria-label":typeof e=="string"?e:"Connect Wallet",children:[ue(jr,{}),ue("span",{className:"cb-button-label",children:e})]})]})}function jr(){return ue("svg",{className:"cb-button-icon",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:ue("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 Xr=`
3
- [data-crossx-wallet-info="external"] .wi-select-wallet-btn {
4
- display: none !important;
5
- }
6
- `;function In(e){return`${e.slice(0,6)}...${e.slice(-4)}`}var Ft=`
7
- .cb-button {
8
- -webkit-font-smoothing: antialiased;
9
- --cb-bg: var(--ds-accent-primary-default, #00D5AA);
10
- --cb-bg-hover: var(--ds-accent-primary-high, #00a0a2);
11
- --cb-color: var(--ds-accent-primary-on, #000);
12
- --cb-border: none;
13
- --cb-radius: 8px;
14
- --cb-height: 36px;
15
- --cb-padding: 0 16px;
16
- --cb-font-family: Inter, system-ui, -apple-system, sans-serif;
17
- --cb-font-size: 14px;
18
- --cb-font-weight: 500;
19
- --cb-gap: 8px;
20
- --cb-transition: background-color 0.15s ease, transform 0.1s ease;
21
- --cb-loading-opacity: 0.7;
22
- --cb-press-scale: 0.95;
23
- --cb-spinner-size: 14px;
24
- --cb-spinner-thumb: currentColor;
25
- --cb-spinner-track: color-mix(in srgb, currentColor 20%, transparent);
26
- --cb-icon-size: 18px;
27
-
28
- display: inline-flex;
29
- align-items: center;
30
- justify-content: center;
31
- box-sizing: border-box;
32
- height: var(--cb-height);
33
- gap: var(--cb-gap);
34
- padding: var(--cb-padding);
35
- border-radius: var(--cb-radius);
36
- border: var(--cb-border);
37
- background: var(--cb-bg);
38
- color: var(--cb-color);
39
- font-family: var(--cb-font-family);
40
- font-size: var(--cb-font-size);
41
- font-weight: var(--cb-font-weight);
42
- cursor: pointer;
43
- transition: var(--cb-transition);
44
- }
45
- .cb-button:hover:not(:disabled) { background: var(--cb-bg-hover); }
46
- .cb-button:active:not(:disabled) { transform: scale(var(--cb-press-scale)); }
47
- .cb-button:disabled, .cb-button[aria-busy="true"] {
48
- cursor: default;
49
- opacity: var(--cb-loading-opacity);
50
- }
51
- .cb-spinner {
52
- display: inline-block;
53
- width: var(--cb-spinner-size);
54
- height: var(--cb-spinner-size);
55
- border: 2px solid var(--cb-spinner-track);
56
- border-top-color: var(--cb-spinner-thumb);
57
- border-radius: 50%;
58
- animation: cck-cb-spin 0.6s linear infinite;
59
- flex-shrink: 0;
60
- }
61
- .cb-button-icon {
62
- width: var(--cb-icon-size);
63
- height: var(--cb-icon-size);
64
- flex-shrink: 0;
65
- }
66
- .cb-button-label { white-space: nowrap; }
67
- .cb-pill {
68
- --cb-pill-bg: var(--ds-surface-default, #1e232e);
69
- --cb-pill-bg-hover: var(--ds-surface-medium, #252b39);
70
- --cb-pill-color: var(--ds-content-high, #ffffffd9);
71
- --cb-pill-border: 1px solid var(--ds-border-default, #ffffff12);
72
- --cb-pill-border-hover: 1px solid var(--ds-border-medium, #ffffff2e);
73
- --cb-pill-radius: 8px;
74
- --cb-pill-height: 36px;
75
- --cb-pill-padding: 0 12px;
76
- --cb-pill-press-scale: 0.95;
77
- --cb-pill-font-family: Inter, system-ui, -apple-system, sans-serif;
78
- --cb-pill-font-size: 14px;
79
- --cb-pill-font-weight: 500;
80
- --cb-pill-gap: 8px;
81
- --cb-pill-icon-size: 20px;
82
- --cb-pill-icon-placeholder-bg: var(--ds-surface-high, #2a2d3a);
83
- --cb-pill-address-font: Inter, system-ui, -apple-system, sans-serif;
84
- --cb-pill-address-font-size: 14px;
85
- --cb-pill-address-letter-spacing: -0.01em;
86
-
87
- display: inline-flex;
88
- align-items: center;
89
- box-sizing: border-box;
90
- height: var(--cb-pill-height);
91
- gap: var(--cb-pill-gap);
92
- padding: var(--cb-pill-padding);
93
- border-radius: var(--cb-pill-radius);
94
- border: var(--cb-pill-border);
95
- background: var(--cb-pill-bg);
96
- color: var(--cb-pill-color);
97
- font-family: var(--cb-pill-font-family);
98
- font-size: var(--cb-pill-font-size);
99
- font-weight: var(--cb-pill-font-weight);
100
- cursor: pointer;
101
- }
102
- .cb-pill:hover,
103
- .cb-pill[data-state="open"] { background: var(--cb-pill-bg-hover); border: var(--cb-pill-border-hover, 1px solid var(--ds-border-medium, #ffffff2e)); }
104
- .cb-pill:active:not(:disabled) { transform: scale(var(--cb-pill-press-scale)); }
105
- .cb-pill-icon {
106
- width: var(--cb-pill-icon-size);
107
- height: var(--cb-pill-icon-size);
108
- border-radius: 50%;
109
- object-fit: contain;
110
- flex-shrink: 0;
111
- background: transparent;
112
- }
113
- /* Apple is a monochrome black logomark in an <img> data URI (can't follow
114
- theme via currentColor). Flip it to white in dark mode so it stays
115
- visible on the dark pill; multicolor marks (Google/MetaMask/Binance/
116
- CROSSx) are untouched. */
117
- [data-theme="dark"] .cb-pill-icon[data-provider="apple"] {
118
- filter: invert(1);
119
- }
120
- .cb-pill-icon-placeholder {
121
- display: inline-block;
122
- width: var(--cb-pill-icon-size);
123
- height: var(--cb-pill-icon-size);
124
- border-radius: 50%;
125
- background: var(--cb-pill-icon-placeholder-bg);
126
- flex-shrink: 0;
127
- }
128
- .cb-pill-address {
129
- font-family: var(--cb-pill-address-font);
130
- font-size: var(--cb-pill-address-font-size);
131
- letter-spacing: var(--cb-pill-address-letter-spacing);
132
- }
133
- @media (max-width: 767.98px) {
134
- .cb-button, .cb-pill {
135
- width: 36px;
136
- min-width: 36px;
137
- padding: 0;
138
- }
139
- .cb-button-label, .cb-pill-address { display: none; }
140
- }
141
- @keyframes cck-cb-spin {
142
- to { transform: rotate(360deg); }
143
- }
144
- `;import{useCallback as Rn,useEffect as Yr,useMemo as Bn,useState as Zr}from"react";import{detectWallets as _n,DEFAULT_WALLET_REGISTRY as En}from"@nexus-cross/connect-kit-wagmi";import{jsx as ie,jsxs as Re}from"react/jsx-runtime";var Jr=["Ensure your wallet extension is installed and unlocked","Try refreshing the page","Some wallets may require you to first open the extension","You can try clicking the wallet anyway"],es="Connect with one of our available wallet providers to continue.";function ts({open:e,onClose:t,onSelect:o,title:s="Connect Wallet",description:n=es,troubleshootingTips:a=Jr}){let{availableWallets:g}=Be(),[f,b]=Zr({});Yr(()=>{if(!e)return;let m=_n(En),T={};for(let C of m)C.installed!==void 0&&(T[C.id]=C.installed);b(T);let P=setTimeout(()=>{let C=_n(En),k={};for(let _ of C)_.installed!==void 0&&(k[_.id]=_.installed);b(k)},1e3);return()=>clearTimeout(P)},[e]);let p=Bn(()=>typeof navigator>"u"?!1:/Mobi|Android/i.test(navigator.userAgent),[]),h=Bn(()=>p?g.filter(m=>m.type!=="extension"):g,[g,p]),I=Rn(m=>{if(!f[m.walletId]&&m.installUrl&&m.type==="extension"){window.open(m.installUrl,"_blank");return}t(),o(m.walletId)},[t,o,f]),S=Rn((m,T)=>{m.stopPropagation(),t(),window.open(T,"_blank")},[t]);return e?ie("div",{style:G.overlay,onClick:t,children:Re("div",{style:G.modal,onClick:m=>m.stopPropagation(),children:[Re("div",{style:G.header,children:[ie("h2",{style:G.title,children:s}),ie("button",{type:"button",onClick:t,style:G.closeBtn,"aria-label":"Close",children:Re("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[ie("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ie("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),ie("p",{style:G.desc,children:n}),ie("div",{style:G.walletList,children:h.map(m=>{let T=f[m.walletId],P=T===!1&&m.type==="extension"&&!!m.installUrl;return Re("div",{style:G.walletGroup,children:[Re("button",{type:"button",onClick:()=>I(m),style:{...G.walletItem,...m.walletId==="cross_wallet"?G.walletItemAccent:{}},"aria-label":`Connect with ${m.name}`,children:[m.iconUrl?ie("img",{src:m.iconUrl,alt:"",style:G.walletIcon}):ie("div",{style:G.walletIconPlaceholder}),Re("div",{style:G.walletInfo,children:[Re("div",{style:G.walletNameRow,children:[ie("span",{style:G.walletName,children:m.name}),T!==void 0&&ie("span",{style:{...G.badge,...T?G.badgeInstalled:G.badgeNotInstalled},children:T?"Installed":"Not Installed"})]}),ie("span",{style:G.walletDesc,children:P?"Extension not detected \u2014 click to install":m.type==="extension"?"Browser extension approval is required":m.walletId==="cross_wallet"?"App approval is required":m.walletId==="binance"?"Mobile app only \u2014 Add CROSS network first":T?"Connect with browser extension":"Scan QR code with app"})]})]}),m.guideUrl&&Re("button",{type:"button",onClick:C=>S(C,m.guideUrl),style:G.guideBtn,children:[ie("span",{"aria-hidden":"true",children:"\u26A0\uFE0F"}),m.guideLabel??"Required Settings"]})]},m.walletId)})}),Re("div",{style:G.troubleshoot,children:[ie("h3",{style:G.troubleshootTitle,children:"Wallet not detected?"}),ie("ul",{style:G.troubleshootList,children:a.map(m=>Re("li",{style:G.troubleshootItem,children:[ie("span",{style:G.troubleshootDot,"aria-hidden":"true"}),ie("span",{children:m})]},m))})]})]})}):null}var H={surfaceBg:"var(--wi-surface-bg, #121212)",surfaceDefault:"var(--wi-surface-default, rgba(255,255,255,0.05))",surfaceSubtle:"var(--wi-surface-subtle, rgba(255,255,255,0.1))",borderDefault:"var(--wi-border-default, rgba(255,255,255,0.05))",textPrimary:"var(--wi-texticon-primary, #ffffff)",textSecondary:"var(--wi-texticon-secondary, rgba(255,255,255,0.7))",textTertiary:"var(--wi-texticon-tertiary, rgba(255,255,255,0.5))",primary:"var(--wi-primary, #019d92)",primarySoft:"var(--crossx-kit-primary-soft, rgba(1,157,146,0.15))",accentGradient:"var(--crossx-kit-accent-gradient, linear-gradient(113deg, rgba(255,255,255,0.05) 0%, rgba(1,157,146,0.12) 70%, rgba(255,255,255,0.05) 70%, rgba(1,157,146,0.12) 80%, rgba(255,255,255,0.05) 80%))",warningBg:"var(--crossx-kit-warning-bg, rgba(245,158,11,0.1))",warningBorder:"var(--crossx-kit-warning-border, rgba(245,158,11,0.25))",warningText:"var(--crossx-kit-warning-text, #fbbf24)"},G={overlay:{position:"fixed",inset:0,zIndex:1e4,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",backdropFilter:"blur(4px)"},modal:{width:"100%",maxWidth:"420px",margin:"16px",background:H.surfaceBg,border:`1px solid ${H.borderDefault}`,borderRadius:"20px",overflow:"hidden"},header:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"20px 24px 0"},title:{fontSize:"18px",fontWeight:700,color:H.textPrimary,margin:0},closeBtn:{background:"none",border:"none",color:H.textTertiary,cursor:"pointer",padding:"4px",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"center"},desc:{padding:"8px 24px 16px",fontSize:"13px",color:H.textTertiary,margin:0,lineHeight:1.5},walletList:{display:"flex",flexDirection:"column",gap:"6px",padding:"0 12px 12px"},walletGroup:{display:"flex",flexDirection:"column",borderRadius:"12px",overflow:"hidden",background:H.surfaceDefault},walletItem:{display:"flex",alignItems:"center",gap:"14px",width:"100%",padding:"14px",background:"transparent",border:"none",color:H.textPrimary,cursor:"pointer",textAlign:"left"},walletItemAccent:{background:H.accentGradient},walletIcon:{width:"40px",height:"40px",borderRadius:"10px",flexShrink:0},walletIconPlaceholder:{width:"40px",height:"40px",borderRadius:"10px",background:H.surfaceSubtle,flexShrink:0},walletInfo:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:"3px"},walletNameRow:{display:"flex",alignItems:"center",gap:"8px"},walletName:{fontSize:"15px",fontWeight:700,lineHeight:1.3,color:H.textPrimary},badge:{fontSize:"10px",fontWeight:600,padding:"2px 7px",borderRadius:"99px",lineHeight:1},badgeInstalled:{background:H.primarySoft,color:H.primary},badgeNotInstalled:{background:"rgba(255,255,255,0.05)",color:H.textTertiary},walletDesc:{fontSize:"11px",color:H.textSecondary,lineHeight:1.3},guideBtn:{display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",margin:"0 14px 14px",padding:"10px 12px",borderRadius:"10px",border:`1px solid ${H.warningBorder}`,background:H.warningBg,color:H.warningText,fontWeight:600,fontSize:"13px",cursor:"pointer"},troubleshoot:{margin:"0 12px 16px",background:H.surfaceDefault,borderRadius:"12px",padding:"14px 16px"},troubleshootTitle:{fontSize:"12px",fontWeight:700,color:H.textPrimary,margin:"0 0 8px"},troubleshootList:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:"8px"},troubleshootItem:{display:"flex",alignItems:"flex-start",gap:"8px",fontSize:"11px",color:H.textSecondary,lineHeight:1.5},troubleshootDot:{flexShrink:0,width:"4px",height:"4px",marginTop:"6px",borderRadius:"50%",background:H.textSecondary}};import{useOnRamp as pi,useOnRampEligibility as fi,OnRampProvider as gi}from"@nexus-cross/onramp/react";import{WalletInfo as yi,ConnectorId as wi}from"@nexus-cross/dapp-ui";import{AppLauncher as Ci,AppLauncherTrigger as ki,AppLauncherContent as xi,useGlobalMenu as Ti}from"@nexus-cross/dapp-ui";import{SkillsButton as Si}from"@nexus-cross/dapp-ui";import{OnRampError as Pi}from"@nexus-cross/connect-kit-core";import{ConnectionStatus as Ri,formatBalance as Bi,formatWei as _i}from"@nexus-cross/connect-kit-core";qt();export{Be as a,to as b,it as c,Tt as d,Bo as e,Bt as f,_t as g,Qr as h,ts as i,pi as j,fi as k,gi as l,yi as m,wi as n,Ci as o,ki as p,xi as q,Ti as r,Si as s,Pi as t,Ri as u,Bi as v,_i as w};