import{useEffect as T,useRef as S,useState as l}from"react";import{fetchQuote as v,swapFromSolana as D}from"@mayanfinance/swap-sdk";import{useConnection as P,useWallet as R}from"@solana/wallet-adapter-react";import{useToast as z}from"@chakra-ui/react";import g from"bignumber.js";import M from"axios";var s=i=>{switch(i){case"BONK":return{token:"DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",chain:"solana",quoteAmount:1e6};case"SOL":return{token:"0x0000000000000000000000000000000000000000",chain:"solana",quoteAmount:1};case"USDT":return{token:"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",chain:"solana",quoteAmount:1};case"ETH":return{token:"0x0000000000000000000000000000000000000000",chain:"ethereum",quoteAmount:1};default:return null}},N=({amountIn:i,fromCurrency:o,toCurrency:a})=>{let[m,q]=l({}),[B,p]=l(!1),[O,_]=l(0),{publicKey:w,signTransaction:E}=R(),{connection:x}=P(),A=z(),d=S(null),f=s(o)?.quoteAmount||1;T(()=>{let e=async()=>{try{p(!0);let t=await h(f);q(t)}catch(t){A({title:"Failed to fetch price",description:t.reason||t.message,status:"error",duration:1e3})}finally{p(!1)}};return o&&a&&o!==a&&(e(),d.current=setInterval(e,3e4)),()=>{clearInterval(d.current)}},[o,a]);let h=async e=>await v({amount:e,fromToken:s(o).token,toToken:s(a).token,fromChain:s(o).chain,toChain:s(a).chain,slippage:3}),r=async(e,t,c="finalized")=>{try{let n=await M.get(`https://explorer-api.mayan.finance/v1/swap/trx/${e}`);return n.data.status==="REDEEMED_ON_EVM"||c==="processed"?n.data:(await new Promise(u=>setTimeout(u,1e4)),r(e,0))}catch(n){if(console.log(n),t>0)return await new Promise(u=>setTimeout(u,1e4)),r(e,t-1);throw new Error("Failed to swap")}},F=async e=>{try{let t=await h(e),c=await D(t,w.toBase58(),w.toBase58(),1e5,E,x);return await r(c,100,"processed"),c}catch(t){throw console.log(t),new Error(t)}},k=o!==a&&m.expectedAmountOut?new g(i).multipliedBy(f).dividedBy(m.minAmountOut).toFixed(4):new g(i).toFixed(2);return{initSwap:F,verifySwapComplete:r,requiredAmount:k,isFetchingQuote:B}},H=N;export{H as default};
