@turtleclub/earn-widget 0.0.6 → 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -22,6 +22,7 @@ interface WidgetStyleConfig {
22
22
  theme?: "light" | "dark" | "auto";
23
23
  widgetWidth?: "default" | "full" | "custom";
24
24
  customWidth?: string;
25
+ showNavigation?: boolean;
25
26
  padding?: "none" | "sm" | "default" | "md" | "lg";
26
27
  rounding?: "none" | "sm" | "default" | "lg" | "xl" | "full";
27
28
  fontFamily?: string;
package/dist/index.d.ts CHANGED
@@ -22,6 +22,7 @@ interface WidgetStyleConfig {
22
22
  theme?: "light" | "dark" | "auto";
23
23
  widgetWidth?: "default" | "full" | "custom";
24
24
  customWidth?: string;
25
+ showNavigation?: boolean;
25
26
  padding?: "none" | "sm" | "default" | "md" | "lg";
26
27
  rounding?: "none" | "sm" | "default" | "lg" | "xl" | "full";
27
28
  fontFamily?: string;
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {createContext,useContext,useState,useEffect,useMemo,useRef,useCallback}from'react';import {atom,useAtomValue,useSetAtom,useAtom}from'jotai';import {clsx}from'clsx';import {jsx,jsxs}from'react/jsx-runtime';import {NavigationBar,NavigationItem,Button,OpportunityItem,Card,cn,Select,SelectTrigger,SelectContent,SelectItem,SwapInput,SwapDetails,TxStatus,OpportunityDetailsV1}from'@turtleclub/ui';import {useEarnDeals,useEarnWalletBalances,useEarnRoute}from'@turtleclub/hooks';import {formatUnits}from'viem';import {ArrowLeft,X as X$1}from'lucide-react';function z(...e){return clsx(e)}var le={theme:"dark",widgetWidth:"default",customWidth:"100%",padding:"default",rounding:"default",fontFamily:"Montserrat",fontSecondary:"DM Sans",deals:[],campaigns:[],styles:{background:"#141514",background_dark:"#F9F9F9",foreground:"#F9F9F9",foreground_dark:"#141514",card:"#141514",card_dark:"#F9F9F9",muted_foreground:"#FFFFFF80",muted_foreground_dark:"#14151480",primary:"#73F36C",primary_dark:"#73F36C"}};var B=atom(le),M=atom(false);atom(false);atom(null);atom({amount:"",tokenAddress:"",tokenDecimals:0,chain:""});var U=atom({status:"idle",hash:void 0,error:void 0});atom(e=>e(U).status,(e,t,o)=>{let r=e(U);t(U,{...r,status:o});});atom(e=>e(U).hash,(e,t,o)=>{let r=e(U);t(U,{...r,hash:o});});function be(e,t){let o=t==="dark",r={"--color-brand-black":o?e.background_dark:e.background,"--color-brand-white":o?e.foreground_dark:e.foreground,"--color-brand-green":o?e.primary_dark:e.primary};return (e.card!==void 0||e.card_dark!==void 0)&&(r["--color-surface-primary"]=o?e.card_dark??e.card??e.background_dark:e.card??e.card_dark??e.background),(e.muted_foreground!==void 0||e.muted_foreground_dark!==void 0)&&(r["--muted-foreground"]=o?e.muted_foreground_dark??e.muted_foreground??e.foreground_dark:e.muted_foreground??e.muted_foreground_dark??e.foreground),r}var ve={background:"#F9F9F9",background_dark:"#141514",foreground:"#141514",foreground_dark:"#F9F9F9",primary:"#73F36C",primary_dark:"#73F36C",card:"#F9F9F9",card_dark:"#141514",muted_foreground:"#14151480",muted_foreground_dark:"#FFFFFF80"},ye="dark",ke="Montserrat, sans-serif",Se="DM Sans, sans-serif";function q(){let e=useAtomValue(B),t=e?.theme??ye,o=e?.fontFamily??ke,r=e?.fontSecondary??Se,s=e?.widgetWidth??"default",n=e?.customWidth??"100%",a=e?.padding??"default",i=e?.rounding??"default",m=e?.styles??ve,h=be(m,t==="auto"?"dark":t);return {theme:t,coreTokenCSS:h,fontPrimary:o,fontSecondary:r,widgetWidth:s,customWidth:n,padding:a,rounding:i,config:e,widgetStyles:m}}function Ce({config:e,children:t}){let o=useSetAtom(B),{theme:r,coreTokenCSS:s,fontPrimary:n,fontSecondary:a,widgetWidth:i}=q();return useEffect(()=>{o(e);},[e,o]),jsx("div",{className:z("turtle-widget-root","antialiased transition-all duration-700 ease-linear h-full w-full",r==="dark"?"dark":""),style:{...s,"--font-primary":n,"--font-secondary":a,fontFamily:n},children:jsx("div",{className:z("flex flex-col items-center gap-2 h-full",i==="full"?"w-full":i==="custom"?"":"max-w-[450px]"),style:{...i==="custom"&&e.customWidth?{width:e.customWidth}:{}},children:t})})}function yt(e){return e?`${e.slice(0,10)}...${e.slice(-4)}`:"Connect Wallet"}function we({userAddress:e}){return jsx("div",{className:"flex items-center justify-between rounded-full bg-secondary px-4 py-2 gap-3 border border-border cursor-pointer transition-colors hover:border-primary",children:jsx("span",{className:"text-foreground font-medium text-sm",children:yt(e)})})}var V=[{value:"ethereum",symbol:"ETH",name:"Ethereum",icon:"https://assets.coingecko.com/coins/images/279/large/ethereum.png?1746019748",chainId:1},{value:"bitcoin",symbol:"BTC",name:"Bitcoin",icon:"https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1747033579",chainId:0},{value:"solana",symbol:"SOL",name:"Solana",icon:"https://assets.coingecko.com/coins/images/4128/large/solana.png?1640133422",chainId:0},{value:"polygon",symbol:"MATIC",name:"Polygon",icon:"https://assets.coingecko.com/coins/images/4713/large/polygon.png?1698233745",chainId:137},{value:"arbitrum",symbol:"ARB",name:"Arbitrum",icon:"https://assets.coingecko.com/coins/images/16547/large/photo_2023-03-29_21.47.00.jpeg?1680097313",chainId:42161}];function Ne({selectedChainId:e=1,onChainChange:t}){let[o,r]=useState(V.find(a=>a.chainId===e)?.value||V[0].value),s=V.find(a=>a.value===o)||V[0],n=a=>{r(a);let i=V.find(m=>m.value===a);i&&t?.(i.chainId);};return jsxs("div",{className:"relative flex items-center h-10",children:[jsx("span",{className:"absolute left-0 top-1/2 -translate-y-1/2 z-10 flex items-center justify-center h-11 w-11 rounded-full ring-1 ring-primary/60 bg-background",children:jsx("img",{src:s.icon,alt:s.name,className:"w-8 h-8 rounded-full"})}),jsxs(Select,{value:o,onValueChange:n,children:[jsx(SelectTrigger,{className:"flex items-center justify-between rounded-full bg-card pl-14 pr-3 gap-3 border border-border w-auto h-10 cursor-pointer transition-colors hover:border-primary focus:border-primary focus:ring-0",children:jsx("div",{className:"flex items-center justify-end gap-2",children:jsx("span",{className:"text-foreground font-medium text-sm",children:s.symbol})})}),jsx(SelectContent,{className:"bg-card border-border rounded-lg w-[82%]",children:V.map(a=>jsx(SelectItem,{value:a.value,className:"flex items-center gap-2 cursor-pointer hover:bg-secondary rounded-md transition-colors data-[state=checked]:bg-secondary data-[state=checked]:text-primary",children:jsxs("div",{className:"flex items-center gap-2 w-full",children:[jsx("img",{src:a.icon,alt:a.name,className:"w-8 h-8 rounded-full"}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"text-foreground font-medium text-sm",children:a.symbol}),jsx("span",{className:"text-muted-foreground text-xs",children:a.name})]})]})},a.value))})]})]})}var Fe=createContext(null),Re=createContext(""),ce=({adapter:e,distributorId:t,children:o})=>jsx(Fe.Provider,{value:e,children:jsx(Re.Provider,{value:t,children:o})}),E=()=>{let e=useContext(Fe);if(!e)throw new Error("useAdapter must be used within an AdapterProvider");return e},Pe=()=>useContext(Re),wt=()=>{let e=E();return {user:e.user,network:e.network,isConnected:!!e.user,openConnectionModal:e.openConnectionModal}},Nt=()=>{let e=E();return {sendTransaction:e.sendTransaction,signMessage:e.signMessage,changeNetwork:e.changeNetwork}},At=()=>{let e=E();return {network:e.network,changeNetwork:e.changeNetwork}};function de(){let e=E(),t=e.user,o=!!e.user,r=e.network;return jsxs("div",{className:"flex w-full items-center justify-between gap-4",children:[o&&t&&jsx(we,{userAddress:t}),jsx(Ne,{selectedChainId:r,onChainChange:async n=>{try{await e.changeNetwork(n);}catch(a){console.error("Failed to change network:",a);}}})]})}function _e(e,t){let[o,r=""]=e.split("."),s=r.padEnd(t,"0").slice(0,t),n=o+s;return BigInt(n)}var Le={user:"",chain:1,slippage:.5,tokenIn:"",tokenOut:"",amount:"",distributor_id:"",id:void 0,selectedDeal:null,selectedToken:null,distributorId:"2c86d3a1-cfe8-486d-915d-1b9ff5e924e9",resetTrigger:0},p=atom(Le),Oe=atom(e=>{let t=e(p);if(!t.user||!t.tokenIn||!t.tokenOut||!t.amount||!t.selectedToken)return;let o=_e(t.amount,t.selectedToken.decimals).toString();return {user:t.user,chain:t.chain,slippage:t.slippage,tokenIn:t.tokenIn,tokenOut:t.tokenOut,amount:o,referral:t.distributor_id,id:t.id}}),H=atom(e=>e(p).amount,(e,t,o)=>{let r=e(p);t(p,{...r,amount:o});}),T=atom(e=>e(p).selectedDeal,(e,t,o)=>{let r=e(p);t(p,{...r,selectedDeal:o,tokenOut:o?.tokenAddress||""});}),G=atom(e=>e(p).selectedToken,(e,t,o)=>{let r=e(p);t(p,{...r,selectedToken:o,tokenIn:o?.address||""});});atom(e=>e(p).slippage,(e,t,o)=>{let r=e(p);t(p,{...r,slippage:o});});var K=atom(e=>e(p).resetTrigger,(e,t,o)=>{let r=e(p);t(p,{...r,resetTrigger:o});});atom(e=>e(p).distributorId,(e,t,o)=>{let r=e(p);t(p,{...r,distributorId:o,distributor_id:o});});atom(e=>{let t=e(p);return !!(t.user&&t.tokenIn&&t.tokenOut&&t.amount&&t.selectedToken&&parseFloat(t.amount)>0)});atom(null,(e,t)=>{let o=e(p);t(p,{...Le,user:o.user,chain:o.chain,distributorId:o.distributorId,distributor_id:o.distributor_id,resetTrigger:o.resetTrigger+1});});var Ft="2c86d3a1-cfe8-486d-915d-1b9ff5e924e9";function $e(){let{data:e,isLoading:t,error:o}=useEarnDeals({campaignId:Ft});return {deals:e?.deals?.map(s=>({id:s.metadata.id,tokenAddress:s.token.address,tokenName:s.token.symbol,tvl:s.data.tvl,iconToken:s.token.logos[0]||"",iconDeal:s.metadata.iconUrl,yieldPercentage:s.data.apy}))||[],isLoading:t,error:o}}function Z(){let e=useSetAtom(T),t=useAtomValue(T),{deals:o,isLoading:r,error:s}=$e();return useEffect(()=>{o.length>0&&!t&&e(o[0]);},[o,t,e]),{deals:o,dealsFormatted:o,isLoading:r,error:s,selectedDeal:t}}function ue(e,t=0){if(e===void 0)return t;try{let o=Number.parseFloat(e.toString());return Number.isNaN(o)?t:o}catch{return t}}function Ue(...e){let t=Number.MAX_VALUE;for(let o of e)o>=t||(t=o);return t}function Lt(e){let t=e.toString(),o=t.split(".");if(o.length<2)return t;let[r,s]=o,n=s.length;for(let i=s.length-1;i>=0&&s[i]==="0";i--)n--;let a=s.slice(0,n);return `${r}${a.length>0?`.${a}`:""}`}var Be=["k","m","b","t","q","qq","qqq","qqqq","qqqqq","qqqqqq","qqqqqqq","qqqqqqqq"];function Ot(e,t){let o=ue(e),r=Math.floor(Ue(Math.log10(o)/3,Be.length));return r<1?[o,""]:[Number.parseFloat((o/10**(r*3)).toFixed(t)),Be[r-1]]}function P(e,t=2,o=false,r=true){typeof e=="string"&&(e=ue(e)),e=e.toFixed(t);let[s,n]=[e,""];if(o){let i;[i,n]=Ot(e,t),s=i.toString();}let a=`${s.replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g,",")}${n}`;return r||(a=Lt(a)),a}function X(e,t,o=false,r=false,s=9){let n=BigInt(e),a=formatUnits(n,t.decimals);return `${P(a,s??t.decimals/2,o,r)}`}function $t(e){return {icon:e.logo?jsx("img",{src:e.logo,alt:e.symbol,className:"w-4 h-4 rounded-full"}):jsx("div",{className:"w-4 h-4 rounded-full bg-muted flex items-center justify-center text-xs",children:e.symbol.charAt(0)}),symbol:e.symbol,address:e.address}}function Me(e){return e.map($t)}function te(e){return {icon:e.iconDeal?jsx("img",{src:e.iconDeal,alt:e.tokenName,className:"w-8 h-8 rounded-full"}):jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center text-sm",children:e.tokenName.charAt(0)}),name:e.tokenName,tvl:Ut(e.tvl),yield:`${e.yieldPercentage}%`}}function Ut(e){return e>=1e9?`$${(e/1e9).toFixed(1)}B`:e>=1e6?`$${(e/1e6).toFixed(1)}M`:e>=1e3?`$${(e/1e3).toFixed(1)}K`:`$${e.toFixed(0)}`}function qe(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}function Xe(){let e=E(),t=e.user,o=!!e.user,{data:r}=useEarnWalletBalances(t&&o?{chain:1,user:t}:void 0),[s,n]=useAtom(G),[a,i]=useAtom(H),m=useAtomValue(K);useEffect(()=>{if(!s)if(r?.balances&&r.balances.length>0){let c=r.balances[0];n({address:c.token.address,name:c.token.name,symbol:c.token.symbol,decimals:c.token.decimals,logo:c.token.logos?.[0],balance:c.amount,price:c.token.price??void 0});}else {let c=k[0];n({address:c.address,name:c.name,symbol:c.symbol,decimals:c.decimals,logo:c.logo,balance:c.balance,price:c.price});}},[r,s,n]),useEffect(()=>{i("");},[s]),useEffect(()=>{m>0&&i("");},[m]);let x=()=>{if(s){let c=s.balance==="0"?"0":s.balance,f=X(c,s),u=P(f,5,false,false);i(u);}},h=s?P(X(s.balance,s),5,false,false):"0",k=[{address:"0x0000000000000000000000000000000000000000",name:"Ethereum",symbol:"ETH",decimals:18,logo:void 0,balance:"0",price:0}],w=r?.balances?r.balances.map(c=>({address:c.token.address,name:c.token.name,symbol:c.token.symbol,decimals:c.token.decimals,logo:c.token.logos?.[0],balance:c.amount,price:c.token.price??void 0})):k,C=Me(w),l=parseFloat(a)||0,d=s?parseFloat(X(s.balance,s)):0,b=l>d&&o,A=s&&a?b?"Insufficient balance":qe(parseFloat(a)*(s.price||0)):void 0;return jsxs("div",{className:"flex flex-col gap-2 items-start justify-start",children:[jsx("h3",{className:"text-md font-medium",children:"Deposit"}),jsxs("div",{className:"relative",children:[jsx(SwapInput,{value:a,onChange:i,tokens:C,selectedToken:s?.address,onTokenChange:c=>{let f=r?.balances?.find(u=>u.token.address===c);if(f)n({address:f.token.address,name:f.token.name,symbol:f.token.symbol,decimals:f.token.decimals,logo:f.token.logos?.[0],balance:f.amount,price:f.token.price??void 0});else {let u=k.find(S=>S.address===c);u&&n({address:u.address,name:u.name,symbol:u.symbol,decimals:u.decimals,logo:u.logo,balance:u.balance,price:u.price});}},usdValue:b?void 0:A,balance:h,onMaxClick:x,placeholder:o?"0":"Connect wallet to continue",disabled:!o,className:`w-full [&_button]:w-32 [&_button]:min-w-32 ${b?"border-destructive/50":""}`}),b&&jsx("div",{className:"absolute bottom-3 left-4 text-sm text-destructive",children:"Insufficient balance"})]})]})}function ze({tokenName:e,tvl:t,iconToken:o,yieldPercentage:r,iconDeal:s,id:n,tokenAddress:a,showPanelOnClick:i=false,onAnimatedClose:m,className:x}){let h=useSetAtom(M),k=useSetAtom(T),w=()=>{k({tokenName:e,tvl:t,iconToken:o,yieldPercentage:r,iconDeal:s,id:n,tokenAddress:a}),i?h(true):m?m():h(false);},C=te({tokenName:e,tvl:t,yieldPercentage:r,iconDeal:s});return jsx(OpportunityItem,{...C,onSelect:w,className:x})}function Q({children:e,className:t,variant:o,padding:r,rounding:s,...n}){let{padding:a,rounding:i}=q(),m=r??a,x=s??i;return jsx(Card,{className:z(t),...n,variant:o,padding:m,rounded:x,children:e})}function Qe(){let e=useAtomValue(T);return jsxs("div",{className:"flex flex-col gap-2 items-start justify-start",children:[jsx("h3",{className:"text-sm font-medium text-foreground",children:"Earn"}),e?jsx(ze,{...e,showPanelOnClick:true}):jsx(Qt,{})]})}function Qt(){return jsx(Q,{variant:"simple",className:"w-full animate-pulse",children:jsxs("div",{className:"flex justify-between items-center p-1",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsxs("div",{className:"flex gap-2 items-center justify-start",children:[jsx("div",{className:"w-7 h-7 bg-muted rounded-full"}),jsx("div",{className:"w-24 h-5 bg-muted rounded"})]}),jsx("div",{className:"w-32 h-4 bg-muted rounded"})]}),jsx("div",{className:"w-16 h-8 bg-muted rounded"})]})})}function Ge({earnRoute:e,userAddress:t,sendTransaction:o,onError:r=()=>{},onSuccess:s=()=>{}}){let[n,a]=useState({steps:[],currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false}),i=useMemo(()=>{if(!e)return null;let l=e.steps?.map(d=>`${d.id}-${d.to}-${d.data}`).join("|")||"";return {...e,_stepsKey:l}},[e?.success,e?.estimatedGas,e?.estimatedTime,e?.outputAmount,e?.steps?.map(l=>`${l.id}-${l.to}-${l.data}`).join("|")]);useEffect(()=>{if(i&&i.success&&i.steps.length>0){let l=i.steps.map((d,b)=>({id:d.id,label:d.title,description:d.description,txData:{to:d.to,data:d.data,value:d.value,gasLimit:d.gasLimit},completed:false,current:b===0}));a({steps:l,currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false});}else a({steps:[],currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false});},[i]);let m=useRef(n),x=useRef({userAddress:t,sendTransaction:o,onError:r,onSuccess:s});useEffect(()=>{m.current=n;},[n]),useEffect(()=>{x.current={userAddress:t,sendTransaction:o,onError:r,onSuccess:s};},[t,o,r,s]);let h=useCallback(async()=>{let l=m.current,{userAddress:d,sendTransaction:b,onError:A,onSuccess:c}=x.current;if(!d||!b||l.isExecuting)return;let f=l.steps[l.currentIndex];if(!(!f||f.completed)){a(u=>({...u,isExecuting:true,hasError:false,cancelled:false,error:void 0}));try{let u=await b({to:f.txData.to,data:f.txData.data,value:f.txData.value?BigInt(f.txData.value):void 0,chainId:1}),S=typeof u=="object"&&"hash"in u?u.hash:String(u);a(g=>{let y=[...g.steps];return y[g.currentIndex]={...y[g.currentIndex],txHash:S},{...g,steps:y}});try{typeof u=="object"&&"wait"in u&&await u.wait();}catch(g){console.warn("Could not wait for transaction confirmation, proceeding anyway:",g);}a(g=>{let y=[...g.steps];y[g.currentIndex]={...y[g.currentIndex],completed:!0,current:!1};let O=g.currentIndex+1,$=O>=y.length;$||(y[O]={...y[O],current:!0});let Y=$;return Y&&c&&c(),{...g,steps:y,currentIndex:$?g.currentIndex:O,isExecuting:!1,allCompleted:Y}});}catch(u){let S=u instanceof Error?u.message:String(u),g=S.toLowerCase().includes("user rejected")||S.toLowerCase().includes("user denied")||S.toLowerCase().includes("user cancelled")||S.toLowerCase().includes("cancelled by user")||S.toLowerCase().includes("transaction rejected")||S.includes("4001");a(y=>({...y,isExecuting:false,hasError:!g,cancelled:g,error:g?"Transaction cancelled by user":u instanceof Error?u.message:"Transaction failed"})),A&&!g&&A(u instanceof Error?u:new Error("Transaction failed"));}}},[]),k=useCallback(()=>{if(i&&i.success&&i.steps.length>0){let l=i.steps.map((d,b)=>({id:d.id,label:d.title,description:d.description,txData:{to:d.to,data:d.data,value:d.value,gasLimit:d.gasLimit},completed:false,current:b===0}));a({steps:l,currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false});}},[i]),w=n.steps[n.currentIndex]||null,C=!!(t&&n.steps.length>0&&!n.isExecuting&&!n.allCompleted&&!n.cancelled);return useEffect(()=>{if(n.steps.length<=1)return;let l=n.currentIndex-1,d=l>=0&&n.steps[l]?.completed,b=n.currentIndex<n.steps.length&&!n.steps[n.currentIndex]?.completed,A=n.currentIndex<n.steps.length;if(d&&b&&A&&!n.isExecuting&&!n.allCompleted&&!n.cancelled){let f=setTimeout(()=>{h();},1e3);return ()=>clearTimeout(f)}},[n.steps,n.currentIndex,n.isExecuting,n.allCompleted,n.cancelled,h]),{...n,currentStep:w,canExecute:C,executeCurrentTransaction:h,resetQueue:k,totalSteps:n.steps.length,completedSteps:n.steps.filter(l=>l.completed).length,progress:n.steps.length>0?n.steps.filter(l=>l.completed).length/n.steps.length*100:0}}function Ke(e){let t=e!==void 0&&!!e.user&&!!e.amount&&parseFloat(e.amount)>0,{data:o,isLoading:r,error:s}=useEarnRoute(t?{user:e.user,chain:e.chain||1,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amount:e.amount,slippage:e.slippage||.1,referral:e.distributor_id||"",id:e.id||""}:void 0);return {data:o?{success:true,steps:o.steps?.map((a,i)=>({id:`step-${i}`,type:a.kind==="approve"?"approval":"deposit",title:a.kind==="approve"?"Approve Token":"Execute Transaction",description:a.kind==="approve"&&"token"in a?`Approve ${a.token.symbol}`:"Execute routing transaction",to:a.tx.to,data:a.tx.data,value:a.tx.value,gasLimit:a.tx.gas.toString()}))||[],estimatedGas:"0",estimatedTime:void 0,outputAmount:o.amount_out,metadata:void 0}:null,isLoading:r,error:s}}function Ze(){let e=useAtomValue(Oe);return {...Ke(e),isReady:!!e,hasRequiredParams:!!(e?.user&&e?.tokenIn&&e?.tokenOut&&e?.amount)}}function et(){let{data:e,error:t,isLoading:o}=Ze();return {fetchedRoute:e??null,routeError:t,isLoadingRoute:o}}function ot({userAddress:e,openConnectionModal:t,fetchedRoute:o,routeError:r,isLoadingRoute:s,canExecute:n,isExecuting:a,hasError:i,cancelled:m,error:x,executeCurrentTransaction:h,totalSteps:k,completedSteps:w,showingTransactionStatus:C,hasInsufficientBalance:l,className:d}){let A=!!E().user,c=async()=>{n&&await h();};return C?jsx("div",{className:d}):!e||!A?jsx(Button,{onClick:()=>t(),className:d,variant:"green",size:"lg",children:"Connect Wallet"}):s?jsx(Button,{disabled:true,className:d,size:"lg",children:"Loading route..."}):r?jsx(Button,{disabled:true,variant:"transparentWhite",className:d,size:"lg",children:"Route Error"}):!o||!o.steps||o.steps.length===0?jsx(Button,{disabled:true,variant:"transparentWhite",className:d,size:"lg",children:"Enter amount to continue"}):l?jsx(Button,{disabled:true,variant:"transparentWhite",className:d,size:"lg",children:"Insufficient Balance"}):jsxs("div",{className:`space-y-2 ${d||""}`,children:[jsxs(Button,{onClick:c,disabled:!n||a,size:"lg",className:"w-full",children:[a&&"Executing...",i&&"Retry Transaction",m&&"Try Again",!a&&!i&&!m&&(k>1?`Confirm Transaction (${w}/${k})`:"Confirm Transaction")]}),i&&x&&jsx("div",{className:"text-sm text-destructive text-center",children:x})]})}function nt({steps:e,currentStep:t,allCompleted:o,cancelled:r,estimatedTime:s,tokenSymbol:n,amount:a,resetQueue:i}){let[,m]=useAtom(K),x=useSetAtom(H),h=e.filter(l=>l.completed&&l.txHash).pop(),k=t?.txHash?t:null,w=o?h?.txHash:k?.txHash||h?.txHash,C=useMemo(()=>({title:r?"Transaction Cancelled":o?"Transaction Completed!":"Processing Transaction",description:r?"Transaction was cancelled by user":o?"Your deposit has been successfully processed.":"Please wait while your transaction is being confirmed...",txHash:w,explorerUrl:"https://etherscan.io",estimatedTime:void 0,amount:`${a?P(a,5,false,false):"0"}`,token:n,protocol:"Turtle Protocol",completed:o,cancelled:r,onViewDetails:void 0,onClose:()=>{i(),x(""),m(0);},steps:e.map(l=>({label:l.label,completed:l.completed,current:l.current,txHash:l.txHash}))}),[e,t,o,r,s,n,a,i]);return jsx("div",{className:"h-full overflow-hidden",children:jsx(TxStatus,{...C,className:"h-full bg-background border-border text-foreground"})})}function at({dealSelected:e}){if(!e)return jsx("div",{className:"h-full overflow-hidden",children:jsx("div",{className:"text-sm text-muted-foreground p-4 h-full overflow-y-auto",children:jsx("p",{children:"Loading opportunity details..."})})});let t=useMemo(()=>({title:`${e.tokenName} Vault`,titleIcon:e.iconDeal?jsx("img",{src:e.iconDeal,alt:e.tokenName,className:"w-8 h-8 rounded-full"}):jsx("div",{className:"w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center",children:jsx("span",{className:"text-sm font-bold text-primary",children:e.tokenName.charAt(0)})}),topCards:[{title:"Native Yield",value:`${e.yieldPercentage.toFixed(2)}%`,color:"primary"},{title:"Total Yield",value:`${(e.yieldPercentage*1.2).toFixed(2)}%`,color:"accent"},{title:"Net Fees",value:"0.5%",color:"secondary"}],bottomCards:[{title:"TVL",value:`$${(e.tvl/1e6).toFixed(2)}M`,color:"primary"},{title:"Yield Source",value:"Multi-chain",color:"secondary"},{title:"Rewards",value:"Deposit Bonus",color:"accent"},{title:"Lock Period",value:"Flexible",color:"success"}]}),[e]);return jsx("div",{className:"h-full overflow-hidden",children:jsx(OpportunityDetailsV1,{...t,className:"h-full w-full overflow-y-auto"})})}function st({amountToDeposit:e,symbol:t,tokenPrice:o,networkFee:r=void 0,networkFeeInUsd:s=void 0,showFree:n=false,defaultOpen:a=false}){let i=useMemo(()=>{let m=e?P(parseFloat(e),6,false,false):"0";return {swapFee:void 0,slippageInUsd:"0.05",deposit:e?`${m} ${t||"ETH"}`:"0 ETH",receive:e?`${m} ${t||"ETH"}`:"0 ETH",equivalentInUsd:e&&o?(parseFloat(e)*o).toFixed(2):"0.00",networkFee:r??"0.002 ETH",networkFeeInUsd:s??"5.65",showFree:n,defaultOpen:a}},[e,t,o,r,s,n,a]);return jsx(SwapDetails,{...i})}function it(){let e=useAtomValue(G),t=useAtomValue(H),o=useAtomValue(T),r=E(),{sendTransaction:s,openConnectionModal:n,user:a}=r,{fetchedRoute:i,routeError:m,isLoadingRoute:x}=et(),{steps:h,currentStep:k,canExecute:w,isExecuting:C,allCompleted:l,hasError:d,cancelled:b,error:A,executeCurrentTransaction:c,resetQueue:f,totalSteps:u,completedSteps:S}=Ge({earnRoute:i,userAddress:a,sendTransaction:s}),g=useMemo(()=>C||l||b||h.length>0&&S>0,[C,l,b,h.length,S]),y=!!r.user,O=e?parseFloat(X(e.balance,e)):0,$=useMemo(()=>(parseFloat(t)||0)>O&&y,[t,e,y]),Y=useMemo(()=>t&&parseFloat(t)>0,[t]);return jsxs("div",{className:"flex flex-col gap-4 flex-1 min-h-0 h-full",children:[jsx("div",{className:"flex-shrink-0",children:jsx(Qe,{})}),jsx("div",{className:"flex-shrink-0",children:jsx(Xe,{})}),Y&&jsx("div",{className:"flex-shrink-0",children:jsx(st,{amountToDeposit:t,symbol:e?.symbol||"",tokenPrice:e?.price||0})}),jsx("div",{className:"flex-1 min-h-0",children:g?jsx(nt,{steps:h,currentStep:k,allCompleted:l,cancelled:b,estimatedTime:i?.estimatedTime||0,tokenSymbol:e?.symbol||"",amount:t,resetQueue:f}):jsx(at,{dealSelected:o})}),jsx("div",{className:"flex-shrink-0",children:jsx(ot,{userAddress:a||"",openConnectionModal:n,fetchedRoute:i,routeError:m,isLoadingRoute:x,canExecute:w&&!$,isExecuting:C,hasError:d,cancelled:b,error:A,executeCurrentTransaction:c,totalSteps:u,completedSteps:S,showingTransactionStatus:g,hasInsufficientBalance:$,className:"w-full"})})]})}function lt(){return Z(),jsxs("div",{className:"w-full h-full flex flex-col gap-4",children:[jsx("div",{className:"flex-shrink-0",children:jsx(de,{})}),jsx("div",{className:"flex-1 min-h-0",children:jsx(it,{})})]})}function ut(){let e=useSetAtom(M),t=useSetAtom(T),{dealsFormatted:o,isLoading:r,error:s}=Z(),n=()=>{e(false);},a=i=>{t(i),n();};return s?jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-background",children:[jsx("p",{className:"text-muted-foreground",children:"Error loading deals"}),jsxs(Button,{onClick:n,variant:"transparentWhite",className:"mt-2",children:[jsx(ArrowLeft,{className:"w-4 h-4 mr-2"}),"Back"]})]}):r?jsx("div",{className:"w-full h-full flex items-center justify-center bg-background",children:jsx("p",{className:"text-muted-foreground",children:"Loading deals..."})}):jsxs("div",{className:"w-full h-full flex flex-col bg-background",children:[jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Choose Opportunity"}),jsx(Button,{onClick:n,variant:"transparentWhite",size:"icon",className:"text-foreground hover:text-primary",children:jsx(X$1,{className:"w-5 h-5"})})]}),jsx("div",{className:"flex-1 p-4 space-y-3 overflow-y-auto",children:o.map(i=>{let m=te(i);return jsx(OpportunityItem,{...m,onSelect:()=>a(i),className:"w-full cursor-pointer hover:bg-accent/50 transition-colors"},i.tokenAddress)})})]})}var mt={sm:"h-8 text-2xl",md:"h-12 text-4xl",lg:"h-16 text-6xl"};function xe({light:e,dark:t,fallback:o="Turtle Club",className:r,size:s="lg"}){let[n,a]=useState(false),{theme:i}=q(),x=i==="dark"?t||e:e||t;return x&&!n?jsx("div",{className:cn("flex justify-center items-center",r),children:jsx("img",{src:x,alt:o,className:cn("object-contain",mt[s]),onError:()=>a(true),onLoad:()=>a(false)})}):jsx("div",{className:cn("flex justify-center items-center",r),children:jsx("span",{className:cn("font-bold text-primary",mt[s]),children:o})})}function pt(){let e=E(),t=Pe(),o=useAtomValue(T),r=useSetAtom(p);useEffect(()=>{r(s=>({...s,user:e.user||"",chain:e.network||1,distributorId:t,distributor_id:t,id:o?.id||""}));},[e.user,e.network,t,o?.id,r]);}function ft(){let e=useAtomValue(B);return {light:e?.logo?.light,dark:e?.logo?.dark,fallback:e?.logo?.fallback||"Turtle Club"}}var Eo=[{value:"portfolio",label:"Portfolio"},{value:"earn",label:"Earn"},{value:"discover",label:"Discover"}];function Co({config:e}){pt();let[t,o]=useState("earn"),r=useAtomValue(M),{light:s,dark:n,fallback:a}=ft();return jsx(Ce,{config:e,children:jsxs("div",{className:"max-w-md w-full h-full flex flex-col",children:[jsx("div",{className:"flex-shrink-0",children:jsx(NavigationBar,{activeValue:t,variant:"menuBar",children:Eo.map(i=>jsx(NavigationItem,{active:t===i.value,onClick:()=>o(i.value),value:i.value,variant:"menuBarDefault",children:i.label},i.value))})}),jsx("div",{className:"flex-1 min-h-0 mt-5",children:t==="earn"&&r?jsx("div",{className:"w-full h-full overflow-hidden",children:jsx(ut,{})}):jsxs(Q,{variant:"container",className:"w-full h-full flex flex-col",children:[jsx("div",{className:"flex-shrink-0 py-4",children:jsx(xe,{light:s,dark:n,fallback:a,size:"lg"})}),jsx("div",{className:"flex-1 min-h-0 w-full",children:jsxs("div",{className:"h-full",children:[t==="earn"&&jsx(lt,{}),t==="portfolio"&&jsx("div",{className:"p-6 bg-background rounded-xl",children:jsx("p",{className:"text-foreground",children:"Portfolio Coming Soon..."})}),t==="discover"&&jsx("div",{className:"p-6 bg-background rounded-xl",children:jsx("p",{className:"text-foreground",children:"Discover Coming Soon..."})})]})})]})})]})})}function To({adapter:e,config:t,distributorId:o}){return jsx(ce,{adapter:e,distributorId:o,children:jsx(Co,{config:t})})}
2
- export{ce as AdapterProvider,To as EarnWidget,le as defaultWidgetStyleConfig,E as useAdapter,At as useNetworkMethods,Nt as useTransactionMethods,wt as useWalletConnection};//# sourceMappingURL=index.js.map
1
+ import {createContext,useContext,useState,useEffect,useMemo,useRef,useCallback}from'react';import {atom,useAtomValue,useSetAtom,useAtom}from'jotai';import {clsx}from'clsx';import {jsx,jsxs}from'react/jsx-runtime';import {NavigationBar,NavigationItem,Button,OpportunityItem,Card,cn,Select,SelectTrigger,SelectContent,SelectItem,SwapInput,SwapDetails,TxStatus,OpportunityDetailsV1}from'@turtleclub/ui';import {useEarnDeals,useEarnWalletBalances,useEarnRoute}from'@turtleclub/hooks';import {formatUnits}from'viem';import {ArrowLeft,X as X$1}from'lucide-react';function z(...e){return clsx(e)}var le={theme:"dark",widgetWidth:"default",customWidth:"100%",padding:"default",rounding:"default",fontFamily:"Montserrat",fontSecondary:"DM Sans",deals:[],campaigns:[],styles:{background:"#141514",background_dark:"#F9F9F9",foreground:"#F9F9F9",foreground_dark:"#141514",card:"#141514",card_dark:"#F9F9F9",muted_foreground:"#FFFFFF80",muted_foreground_dark:"#14151480",primary:"#73F36C",primary_dark:"#73F36C"}};var M=atom(le),q=atom(false);atom(false);atom(null);atom({amount:"",tokenAddress:"",tokenDecimals:0,chain:""});var B=atom({status:"idle",hash:void 0,error:void 0});atom(e=>e(B).status,(e,t,o)=>{let r=e(B);t(B,{...r,status:o});});atom(e=>e(B).hash,(e,t,o)=>{let r=e(B);t(B,{...r,hash:o});});function be(e,t){let o=t==="dark",r={"--color-brand-black":o?e.background_dark:e.background,"--color-brand-white":o?e.foreground_dark:e.foreground,"--color-brand-green":o?e.primary_dark:e.primary};return (e.card!==void 0||e.card_dark!==void 0)&&(r["--color-surface-primary"]=o?e.card_dark??e.card??e.background_dark:e.card??e.card_dark??e.background),(e.muted_foreground!==void 0||e.muted_foreground_dark!==void 0)&&(r["--muted-foreground"]=o?e.muted_foreground_dark??e.muted_foreground??e.foreground_dark:e.muted_foreground??e.muted_foreground_dark??e.foreground),r}var ve={background:"#F9F9F9",background_dark:"#141514",foreground:"#141514",foreground_dark:"#F9F9F9",primary:"#73F36C",primary_dark:"#73F36C",card:"#F9F9F9",card_dark:"#141514",muted_foreground:"#14151480",muted_foreground_dark:"#FFFFFF80"},ye="dark",ke="Montserrat, sans-serif",Se="DM Sans, sans-serif";function P(){let e=useAtomValue(M),t=e?.theme??ye,o=e?.fontFamily??ke,r=e?.fontSecondary??Se,s=e?.widgetWidth??"default",n=e?.customWidth??"100%",a=e?.showNavigation??true,i=e?.padding??"default",u=e?.rounding??"default",f=e?.styles??ve,y=be(f,t==="auto"?"dark":t);return {theme:t,coreTokenCSS:y,fontPrimary:o,fontSecondary:r,widgetWidth:s,customWidth:n,showNavigation:a,padding:i,rounding:u,config:e,widgetStyles:f}}function Ee({config:e,children:t}){let o=useSetAtom(M),{theme:r,coreTokenCSS:s,fontPrimary:n,fontSecondary:a,widgetWidth:i}=P();return useEffect(()=>{o(e);},[e,o]),jsx("div",{className:z("turtle-widget-root","antialiased transition-all duration-700 ease-linear h-full w-full",r==="dark"?"dark":""),style:{...s,"--font-primary":n,"--font-secondary":a,fontFamily:n},children:jsx("div",{className:z("flex flex-col gap-2 h-full",i==="full"?"w-full items-center":i==="custom"?"w-full items-stretch":"w-full max-w-[600px] items-center"),style:{...i==="custom"&&e.customWidth?{width:e.customWidth}:{}},children:t})})}function yt(e){return e?`${e.slice(0,10)}...${e.slice(-4)}`:"Connect Wallet"}function Te({userAddress:e}){return jsx("div",{className:"flex items-center justify-between rounded-full bg-secondary px-4 py-2 gap-3 border border-border cursor-pointer transition-colors hover:border-primary",children:jsx("span",{className:"text-foreground font-medium text-sm",children:yt(e)})})}var V=[{value:"ethereum",symbol:"ETH",name:"Ethereum",icon:"https://assets.coingecko.com/coins/images/279/large/ethereum.png?1746019748",chainId:1},{value:"bitcoin",symbol:"BTC",name:"Bitcoin",icon:"https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1747033579",chainId:0},{value:"solana",symbol:"SOL",name:"Solana",icon:"https://assets.coingecko.com/coins/images/4128/large/solana.png?1640133422",chainId:0},{value:"polygon",symbol:"MATIC",name:"Polygon",icon:"https://assets.coingecko.com/coins/images/4713/large/polygon.png?1698233745",chainId:137},{value:"arbitrum",symbol:"ARB",name:"Arbitrum",icon:"https://assets.coingecko.com/coins/images/16547/large/photo_2023-03-29_21.47.00.jpeg?1680097313",chainId:42161}];function Ne({selectedChainId:e=1,onChainChange:t}){let[o,r]=useState(V.find(a=>a.chainId===e)?.value||V[0].value),s=V.find(a=>a.value===o)||V[0],n=a=>{r(a);let i=V.find(u=>u.value===a);i&&t?.(i.chainId);};return jsxs("div",{className:"relative flex items-center h-10",children:[jsx("span",{className:"absolute left-0 top-1/2 -translate-y-1/2 z-10 flex items-center justify-center h-11 w-11 rounded-full ring-1 ring-primary/60 bg-background",children:jsx("img",{src:s.icon,alt:s.name,className:"w-8 h-8 rounded-full"})}),jsxs(Select,{value:o,onValueChange:n,children:[jsx(SelectTrigger,{className:"flex items-center justify-between rounded-full bg-card pl-14 pr-3 gap-3 border border-border w-auto h-10 cursor-pointer transition-colors hover:border-primary focus:border-primary focus:ring-0",children:jsx("div",{className:"flex items-center justify-end gap-2",children:jsx("span",{className:"text-foreground font-medium text-sm",children:s.symbol})})}),jsx(SelectContent,{className:"bg-card border-border rounded-lg w-[82%]",children:V.map(a=>jsx(SelectItem,{value:a.value,className:"flex items-center gap-2 cursor-pointer hover:bg-secondary rounded-md transition-colors data-[state=checked]:bg-secondary data-[state=checked]:text-primary",children:jsxs("div",{className:"flex items-center gap-2 w-full",children:[jsx("img",{src:a.icon,alt:a.name,className:"w-8 h-8 rounded-full"}),jsxs("div",{className:"flex flex-col",children:[jsx("span",{className:"text-foreground font-medium text-sm",children:a.symbol}),jsx("span",{className:"text-muted-foreground text-xs",children:a.name})]})]})},a.value))})]})]})}var Fe=createContext(null),Re=createContext(""),ce=({adapter:e,distributorId:t,children:o})=>jsx(Fe.Provider,{value:e,children:jsx(Re.Provider,{value:t,children:o})}),w=()=>{let e=useContext(Fe);if(!e)throw new Error("useAdapter must be used within an AdapterProvider");return e},Pe=()=>useContext(Re),Tt=()=>{let e=w();return {user:e.user,network:e.network,isConnected:!!e.user,openConnectionModal:e.openConnectionModal}},Nt=()=>{let e=w();return {sendTransaction:e.sendTransaction,signMessage:e.signMessage,changeNetwork:e.changeNetwork}},At=()=>{let e=w();return {network:e.network,changeNetwork:e.changeNetwork}};function de(){let e=w(),t=e.user,o=!!e.user,r=e.network;return jsxs("div",{className:"flex w-full items-center justify-between gap-4",children:[o&&t&&jsx(Te,{userAddress:t}),jsx(Ne,{selectedChainId:r,onChainChange:async n=>{try{await e.changeNetwork(n);}catch(a){console.error("Failed to change network:",a);}}})]})}function _e(e,t){let[o,r=""]=e.split("."),s=r.padEnd(t,"0").slice(0,t),n=o+s;return BigInt(n)}var Le={user:"",chain:1,slippage:.5,tokenIn:"",tokenOut:"",amount:"",distributor_id:"",id:void 0,selectedDeal:null,selectedToken:null,distributorId:"2c86d3a1-cfe8-486d-915d-1b9ff5e924e9",resetTrigger:0},p=atom(Le),Oe=atom(e=>{let t=e(p);if(!t.user||!t.tokenIn||!t.tokenOut||!t.amount||!t.selectedToken)return;let o=_e(t.amount,t.selectedToken.decimals).toString();return {user:t.user,chain:t.chain,slippage:t.slippage,tokenIn:t.tokenIn,tokenOut:t.tokenOut,amount:o,referral:t.distributor_id,id:t.id}}),H=atom(e=>e(p).amount,(e,t,o)=>{let r=e(p);t(p,{...r,amount:o});}),C=atom(e=>e(p).selectedDeal,(e,t,o)=>{let r=e(p);t(p,{...r,selectedDeal:o,tokenOut:o?.tokenAddress||""});}),G=atom(e=>e(p).selectedToken,(e,t,o)=>{let r=e(p);t(p,{...r,selectedToken:o,tokenIn:o?.address||""});});atom(e=>e(p).slippage,(e,t,o)=>{let r=e(p);t(p,{...r,slippage:o});});var K=atom(e=>e(p).resetTrigger,(e,t,o)=>{let r=e(p);t(p,{...r,resetTrigger:o});});atom(e=>e(p).distributorId,(e,t,o)=>{let r=e(p);t(p,{...r,distributorId:o,distributor_id:o});});atom(e=>{let t=e(p);return !!(t.user&&t.tokenIn&&t.tokenOut&&t.amount&&t.selectedToken&&parseFloat(t.amount)>0)});atom(null,(e,t)=>{let o=e(p);t(p,{...Le,user:o.user,chain:o.chain,distributorId:o.distributorId,distributor_id:o.distributor_id,resetTrigger:o.resetTrigger+1});});var Ft="2c86d3a1-cfe8-486d-915d-1b9ff5e924e9";function $e(){let{data:e,isLoading:t,error:o}=useEarnDeals({campaignId:Ft});return {deals:e?.deals?.map(s=>({id:s.metadata.id,tokenAddress:s.token.address,tokenName:s.token.symbol,tvl:s.data.tvl,iconToken:s.token.logos[0]||"",iconDeal:s.metadata.iconUrl,yieldPercentage:s.data.apy}))||[],isLoading:t,error:o}}function Z(){let e=useSetAtom(C),t=useAtomValue(C),{deals:o,isLoading:r,error:s}=$e();return useEffect(()=>{o.length>0&&!t&&e(o[0]);},[o,t,e]),{deals:o,dealsFormatted:o,isLoading:r,error:s,selectedDeal:t}}function ue(e,t=0){if(e===void 0)return t;try{let o=Number.parseFloat(e.toString());return Number.isNaN(o)?t:o}catch{return t}}function Ue(...e){let t=Number.MAX_VALUE;for(let o of e)o>=t||(t=o);return t}function Lt(e){let t=e.toString(),o=t.split(".");if(o.length<2)return t;let[r,s]=o,n=s.length;for(let i=s.length-1;i>=0&&s[i]==="0";i--)n--;let a=s.slice(0,n);return `${r}${a.length>0?`.${a}`:""}`}var Be=["k","m","b","t","q","qq","qqq","qqqq","qqqqq","qqqqqq","qqqqqqq","qqqqqqqq"];function Ot(e,t){let o=ue(e),r=Math.floor(Ue(Math.log10(o)/3,Be.length));return r<1?[o,""]:[Number.parseFloat((o/10**(r*3)).toFixed(t)),Be[r-1]]}function W(e,t=2,o=false,r=true){typeof e=="string"&&(e=ue(e)),e=e.toFixed(t);let[s,n]=[e,""];if(o){let i;[i,n]=Ot(e,t),s=i.toString();}let a=`${s.replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g,",")}${n}`;return r||(a=Lt(a)),a}function X(e,t,o=false,r=false,s=9){let n=BigInt(e),a=formatUnits(n,t.decimals);return `${W(a,s??t.decimals/2,o,r)}`}function $t(e){return {icon:e.logo?jsx("img",{src:e.logo,alt:e.symbol,className:"w-4 h-4 rounded-full"}):jsx("div",{className:"w-4 h-4 rounded-full bg-muted flex items-center justify-center text-xs",children:e.symbol.charAt(0)}),symbol:e.symbol,address:e.address}}function Me(e){return e.map($t)}function te(e){return {icon:e.iconDeal?jsx("img",{src:e.iconDeal,alt:e.tokenName,className:"w-8 h-8 rounded-full"}):jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center text-sm",children:e.tokenName.charAt(0)}),name:e.tokenName,tvl:Ut(e.tvl),yield:`${e.yieldPercentage}%`}}function Ut(e){return e>=1e9?`$${(e/1e9).toFixed(1)}B`:e>=1e6?`$${(e/1e6).toFixed(1)}M`:e>=1e3?`$${(e/1e3).toFixed(1)}K`:`$${e.toFixed(0)}`}function qe(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}function Xe(){let e=w(),t=e.user,o=!!e.user,{data:r}=useEarnWalletBalances(t&&o?{chain:1,user:t}:void 0),[s,n]=useAtom(G),[a,i]=useAtom(H),u=useAtomValue(K);useEffect(()=>{if(!s)if(r?.balances&&r.balances.length>0){let c=r.balances[0];n({address:c.token.address,name:c.token.name,symbol:c.token.symbol,decimals:c.token.decimals,logo:c.token.logos?.[0],balance:c.amount,price:c.token.price??void 0});}else {let c=y[0];n({address:c.address,name:c.name,symbol:c.symbol,decimals:c.decimals,logo:c.logo,balance:c.balance,price:c.price});}},[r,s,n]),useEffect(()=>{i("");},[s]),useEffect(()=>{u>0&&i("");},[u]);let f=()=>{if(s){let c=s.balance==="0"?"0":s.balance,g=X(c,s),m=W(g,5,false,false);i(m);}},b=s?W(X(s.balance,s),5,false,false):"0",y=[{address:"0x0000000000000000000000000000000000000000",name:"Ethereum",symbol:"ETH",decimals:18,logo:void 0,balance:"0",price:0}],T=r?.balances?r.balances.map(c=>({address:c.token.address,name:c.token.name,symbol:c.token.symbol,decimals:c.token.decimals,logo:c.token.logos?.[0],balance:c.amount,price:c.token.price??void 0})):y,E=Me(T),l=parseFloat(a)||0,d=s?parseFloat(X(s.balance,s)):0,h=l>d&&o,A=s&&a?h?"Insufficient balance":qe(parseFloat(a)*(s.price||0)):void 0;return jsxs("div",{className:"w-full flex flex-col gap-2 items-start justify-start",children:[jsx("h3",{className:"text-md font-medium",children:"Deposit"}),jsxs("div",{className:"w-full relative",children:[jsx(SwapInput,{value:a,onChange:i,tokens:E,selectedToken:s?.address,onTokenChange:c=>{let g=r?.balances?.find(m=>m.token.address===c);if(g)n({address:g.token.address,name:g.token.name,symbol:g.token.symbol,decimals:g.token.decimals,logo:g.token.logos?.[0],balance:g.amount,price:g.token.price??void 0});else {let m=y.find(S=>S.address===c);m&&n({address:m.address,name:m.name,symbol:m.symbol,decimals:m.decimals,logo:m.logo,balance:m.balance,price:m.price});}},usdValue:h?void 0:A,balance:b,onMaxClick:f,placeholder:o?"0":"Connect wallet to continue",disabled:!o,className:`w-full [&_button]:w-32 [&_button]:min-w-32 ${h?"border-destructive/50":""}`}),h&&jsx("div",{className:"absolute bottom-3 left-4 text-sm text-destructive",children:"Insufficient balance"})]})]})}function ze({tokenName:e,tvl:t,iconToken:o,yieldPercentage:r,iconDeal:s,id:n,tokenAddress:a,showPanelOnClick:i=false,onAnimatedClose:u,className:f}){let b=useSetAtom(q),y=useSetAtom(C),T=()=>{y({tokenName:e,tvl:t,iconToken:o,yieldPercentage:r,iconDeal:s,id:n,tokenAddress:a}),i?b(true):u?u():b(false);},E=te({tokenName:e,tvl:t,yieldPercentage:r,iconDeal:s});return jsx(OpportunityItem,{...E,onSelect:T,className:f})}function Q({children:e,className:t,variant:o,padding:r,rounding:s,...n}){let{padding:a,rounding:i}=P(),u=r??a,f=s??i;return jsx(Card,{className:z(t),...n,variant:o,padding:u,rounded:f,children:e})}function Qe(){let e=useAtomValue(C);return jsxs("div",{className:"w-full flex flex-col gap-2 items-start justify-start",children:[jsx("h3",{className:"text-sm font-medium text-foreground",children:"Earn"}),e?jsx(ze,{...e,showPanelOnClick:true}):jsx(Qt,{})]})}function Qt(){return jsx(Q,{variant:"simple",className:"w-full animate-pulse",children:jsxs("div",{className:"flex justify-between items-center p-1",children:[jsxs("div",{className:"flex flex-col gap-2",children:[jsxs("div",{className:"flex gap-2 items-center justify-start",children:[jsx("div",{className:"w-7 h-7 bg-muted rounded-full"}),jsx("div",{className:"w-24 h-5 bg-muted rounded"})]}),jsx("div",{className:"w-32 h-4 bg-muted rounded"})]}),jsx("div",{className:"w-16 h-8 bg-muted rounded"})]})})}function Ge({earnRoute:e,userAddress:t,sendTransaction:o,onError:r=()=>{},onSuccess:s=()=>{}}){let[n,a]=useState({steps:[],currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false}),i=useMemo(()=>{if(!e)return null;let l=e.steps?.map(d=>`${d.id}-${d.to}-${d.data}`).join("|")||"";return {...e,_stepsKey:l}},[e?.success,e?.estimatedGas,e?.estimatedTime,e?.outputAmount,e?.steps?.map(l=>`${l.id}-${l.to}-${l.data}`).join("|")]);useEffect(()=>{if(i&&i.success&&i.steps.length>0){let l=i.steps.map((d,h)=>({id:d.id,label:d.title,description:d.description,txData:{to:d.to,data:d.data,value:d.value,gasLimit:d.gasLimit},completed:false,current:h===0}));a({steps:l,currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false});}else a({steps:[],currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false});},[i]);let u=useRef(n),f=useRef({userAddress:t,sendTransaction:o,onError:r,onSuccess:s});useEffect(()=>{u.current=n;},[n]),useEffect(()=>{f.current={userAddress:t,sendTransaction:o,onError:r,onSuccess:s};},[t,o,r,s]);let b=useCallback(async()=>{let l=u.current,{userAddress:d,sendTransaction:h,onError:A,onSuccess:c}=f.current;if(!d||!h||l.isExecuting)return;let g=l.steps[l.currentIndex];if(!(!g||g.completed)){a(m=>({...m,isExecuting:true,hasError:false,cancelled:false,error:void 0}));try{let m=await h({to:g.txData.to,data:g.txData.data,value:g.txData.value?BigInt(g.txData.value):void 0,chainId:1}),S=typeof m=="object"&&"hash"in m?m.hash:String(m);a(x=>{let k=[...x.steps];return k[x.currentIndex]={...k[x.currentIndex],txHash:S},{...x,steps:k}});try{typeof m=="object"&&"wait"in m&&await m.wait();}catch(x){console.warn("Could not wait for transaction confirmation, proceeding anyway:",x);}a(x=>{let k=[...x.steps];k[x.currentIndex]={...k[x.currentIndex],completed:!0,current:!1};let $=x.currentIndex+1,U=$>=k.length;U||(k[$]={...k[$],current:!0});let Y=U;return Y&&c&&c(),{...x,steps:k,currentIndex:U?x.currentIndex:$,isExecuting:!1,allCompleted:Y}});}catch(m){let S=m instanceof Error?m.message:String(m),x=S.toLowerCase().includes("user rejected")||S.toLowerCase().includes("user denied")||S.toLowerCase().includes("user cancelled")||S.toLowerCase().includes("cancelled by user")||S.toLowerCase().includes("transaction rejected")||S.includes("4001");a(k=>({...k,isExecuting:false,hasError:!x,cancelled:x,error:x?"Transaction cancelled by user":m instanceof Error?m.message:"Transaction failed"})),A&&!x&&A(m instanceof Error?m:new Error("Transaction failed"));}}},[]),y=useCallback(()=>{if(i&&i.success&&i.steps.length>0){let l=i.steps.map((d,h)=>({id:d.id,label:d.title,description:d.description,txData:{to:d.to,data:d.data,value:d.value,gasLimit:d.gasLimit},completed:false,current:h===0}));a({steps:l,currentIndex:0,isExecuting:false,allCompleted:false,hasError:false,cancelled:false});}},[i]),T=n.steps[n.currentIndex]||null,E=!!(t&&n.steps.length>0&&!n.isExecuting&&!n.allCompleted&&!n.cancelled);return useEffect(()=>{if(n.steps.length<=1)return;let l=n.currentIndex-1,d=l>=0&&n.steps[l]?.completed,h=n.currentIndex<n.steps.length&&!n.steps[n.currentIndex]?.completed,A=n.currentIndex<n.steps.length;if(d&&h&&A&&!n.isExecuting&&!n.allCompleted&&!n.cancelled){let g=setTimeout(()=>{b();},1e3);return ()=>clearTimeout(g)}},[n.steps,n.currentIndex,n.isExecuting,n.allCompleted,n.cancelled,b]),{...n,currentStep:T,canExecute:E,executeCurrentTransaction:b,resetQueue:y,totalSteps:n.steps.length,completedSteps:n.steps.filter(l=>l.completed).length,progress:n.steps.length>0?n.steps.filter(l=>l.completed).length/n.steps.length*100:0}}function Ke(e){let t=e!==void 0&&!!e.user&&!!e.amount&&parseFloat(e.amount)>0,{data:o,isLoading:r,error:s}=useEarnRoute(t?{user:e.user,chain:e.chain||1,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amount:e.amount,slippage:e.slippage||.1,referral:e.distributor_id||"",id:e.id||""}:void 0);return {data:o?{success:true,steps:o.steps?.map((a,i)=>({id:`step-${i}`,type:a.kind==="approve"?"approval":"deposit",title:a.kind==="approve"?"Approve Token":"Execute Transaction",description:a.kind==="approve"&&"token"in a?`Approve ${a.token.symbol}`:"Execute routing transaction",to:a.tx.to,data:a.tx.data,value:a.tx.value,gasLimit:a.tx.gas.toString()}))||[],estimatedGas:"0",estimatedTime:void 0,outputAmount:o.amount_out,metadata:void 0}:null,isLoading:r,error:s}}function Ze(){let e=useAtomValue(Oe);return {...Ke(e),isReady:!!e,hasRequiredParams:!!(e?.user&&e?.tokenIn&&e?.tokenOut&&e?.amount)}}function et(){let{data:e,error:t,isLoading:o}=Ze();return {fetchedRoute:e??null,routeError:t,isLoadingRoute:o}}function ot({userAddress:e,openConnectionModal:t,fetchedRoute:o,routeError:r,isLoadingRoute:s,canExecute:n,isExecuting:a,hasError:i,cancelled:u,error:f,executeCurrentTransaction:b,totalSteps:y,completedSteps:T,showingTransactionStatus:E,hasInsufficientBalance:l,className:d}){let A=!!w().user,c=async()=>{n&&await b();};return E?jsx("div",{className:d}):!e||!A?jsx(Button,{onClick:()=>t(),className:d,variant:"green",size:"lg",children:"Connect Wallet"}):s?jsx(Button,{disabled:true,className:d,size:"lg",children:"Loading route..."}):r?jsx(Button,{disabled:true,variant:"transparentWhite",className:d,size:"lg",children:"Route Error"}):!o||!o.steps||o.steps.length===0?jsx(Button,{disabled:true,variant:"transparentWhite",className:d,size:"lg",children:"Enter amount to continue"}):l?jsx(Button,{disabled:true,variant:"transparentWhite",className:d,size:"lg",children:"Insufficient Balance"}):jsxs("div",{className:`space-y-2 ${d||""}`,children:[jsxs(Button,{onClick:c,disabled:!n||a,size:"lg",className:"w-full",children:[a&&"Executing...",i&&"Retry Transaction",u&&"Try Again",!a&&!i&&!u&&(y>1?`Confirm Transaction (${T}/${y})`:"Confirm Transaction")]}),i&&f&&jsx("div",{className:"text-sm text-destructive text-center",children:f})]})}function nt({steps:e,currentStep:t,allCompleted:o,cancelled:r,estimatedTime:s,tokenSymbol:n,amount:a,resetQueue:i}){let[,u]=useAtom(K),f=useSetAtom(H),b=e.filter(l=>l.completed&&l.txHash).pop(),y=t?.txHash?t:null,T=o?b?.txHash:y?.txHash||b?.txHash,E=useMemo(()=>({title:r?"Transaction Cancelled":o?"Transaction Completed!":"Processing Transaction",description:r?"Transaction was cancelled by user":o?"Your deposit has been successfully processed.":"Please wait while your transaction is being confirmed...",txHash:T,explorerUrl:"https://etherscan.io",estimatedTime:void 0,amount:`${a?W(a,5,false,false):"0"}`,token:n,protocol:"Turtle Protocol",completed:o,cancelled:r,onViewDetails:void 0,onClose:()=>{i(),f(""),u(0);},steps:e.map(l=>({label:l.label,completed:l.completed,current:l.current,txHash:l.txHash}))}),[e,t,o,r,s,n,a,i]);return jsx("div",{className:"h-full overflow-hidden",children:jsx(TxStatus,{...E,className:"h-full bg-background border-border text-foreground"})})}function at({dealSelected:e}){if(!e)return jsx("div",{className:"h-full overflow-hidden",children:jsx("div",{className:"text-sm text-muted-foreground p-4 h-full overflow-y-auto",children:jsx("p",{children:"Loading opportunity details..."})})});let t=useMemo(()=>({title:`${e.tokenName} Vault`,titleIcon:e.iconDeal?jsx("img",{src:e.iconDeal,alt:e.tokenName,className:"w-8 h-8 rounded-full"}):jsx("div",{className:"w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center",children:jsx("span",{className:"text-sm font-bold text-primary",children:e.tokenName.charAt(0)})}),topCards:[{title:"Native Yield",value:`${e.yieldPercentage.toFixed(2)}%`,color:"primary"},{title:"Total Yield",value:`${(e.yieldPercentage*1.2).toFixed(2)}%`,color:"accent"},{title:"Net Fees",value:"0.5%",color:"secondary"}],bottomCards:[{title:"TVL",value:`$${(e.tvl/1e6).toFixed(2)}M`,color:"primary"},{title:"Yield Source",value:"Multi-chain",color:"secondary"},{title:"Rewards",value:"Deposit Bonus",color:"accent"},{title:"Lock Period",value:"Flexible",color:"success"}]}),[e]);return jsx("div",{className:"h-full overflow-hidden",children:jsx(OpportunityDetailsV1,{...t,className:"h-full w-full overflow-y-auto"})})}function st({amountToDeposit:e,symbol:t,tokenPrice:o,networkFee:r=void 0,networkFeeInUsd:s=void 0,showFree:n=false,defaultOpen:a=false}){let i=useMemo(()=>{let u=e?W(parseFloat(e),6,false,false):"0";return {swapFee:void 0,slippageInUsd:"0.05",deposit:e?`${u} ${t||"ETH"}`:"0 ETH",receive:e?`${u} ${t||"ETH"}`:"0 ETH",equivalentInUsd:e&&o?(parseFloat(e)*o).toFixed(2):"0.00",networkFee:r??"0.002 ETH",networkFeeInUsd:s??"5.65",showFree:n,defaultOpen:a}},[e,t,o,r,s,n,a]);return jsx(SwapDetails,{...i})}function it(){let e=useAtomValue(G),t=useAtomValue(H),o=useAtomValue(C),r=w(),{sendTransaction:s,openConnectionModal:n,user:a}=r,{fetchedRoute:i,routeError:u,isLoadingRoute:f}=et(),{steps:b,currentStep:y,canExecute:T,isExecuting:E,allCompleted:l,hasError:d,cancelled:h,error:A,executeCurrentTransaction:c,resetQueue:g,totalSteps:m,completedSteps:S}=Ge({earnRoute:i,userAddress:a,sendTransaction:s}),x=useMemo(()=>E||l||h||b.length>0&&S>0,[E,l,h,b.length,S]),k=!!r.user,$=e?parseFloat(X(e.balance,e)):0,U=useMemo(()=>(parseFloat(t)||0)>$&&k,[t,e,k]),Y=useMemo(()=>t&&parseFloat(t)>0,[t]);return jsxs("div",{className:"w-full flex flex-col gap-4 flex-1 min-h-0 h-full",children:[jsx("div",{className:"flex-shrink-0",children:jsx(Qe,{})}),jsx("div",{className:"flex-shrink-0",children:jsx(Xe,{})}),Y&&jsx("div",{className:"flex-shrink-0",children:jsx(st,{amountToDeposit:t,symbol:e?.symbol||"",tokenPrice:e?.price||0})}),jsx("div",{className:"flex-1 min-h-0",children:x?jsx(nt,{steps:b,currentStep:y,allCompleted:l,cancelled:h,estimatedTime:i?.estimatedTime||0,tokenSymbol:e?.symbol||"",amount:t,resetQueue:g}):jsx(at,{dealSelected:o})}),jsx("div",{className:"flex-shrink-0",children:jsx(ot,{userAddress:a||"",openConnectionModal:n,fetchedRoute:i,routeError:u,isLoadingRoute:f,canExecute:T&&!U,isExecuting:E,hasError:d,cancelled:h,error:A,executeCurrentTransaction:c,totalSteps:m,completedSteps:S,showingTransactionStatus:x,hasInsufficientBalance:U,className:"w-full"})})]})}function lt(){return Z(),jsxs("div",{className:"w-full h-full flex flex-col gap-4",children:[jsx("div",{className:"flex-shrink-0",children:jsx(de,{})}),jsx("div",{className:"flex-1 min-h-0",children:jsx(it,{})})]})}function ut(){let e=useSetAtom(q),t=useSetAtom(C),{dealsFormatted:o,isLoading:r,error:s}=Z(),n=()=>{e(false);},a=i=>{t(i),n();};return s?jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center bg-background",children:[jsx("p",{className:"text-muted-foreground",children:"Error loading deals"}),jsxs(Button,{onClick:n,variant:"transparentWhite",className:"mt-2",children:[jsx(ArrowLeft,{className:"w-4 h-4 mr-2"}),"Back"]})]}):r?jsx("div",{className:"w-full h-full flex items-center justify-center bg-background",children:jsx("p",{className:"text-muted-foreground",children:"Loading deals..."})}):jsxs("div",{className:"w-full h-full flex flex-col bg-background",children:[jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Choose Opportunity"}),jsx(Button,{onClick:n,variant:"transparentWhite",size:"icon",className:"text-foreground hover:text-primary",children:jsx(X$1,{className:"w-5 h-5"})})]}),jsx("div",{className:"flex-1 p-4 space-y-3 overflow-y-auto",children:o.map(i=>{let u=te(i);return jsx(OpportunityItem,{...u,onSelect:()=>a(i),className:"w-full cursor-pointer hover:bg-accent/50 transition-colors"},i.tokenAddress)})})]})}var mt={sm:"h-8 text-2xl",md:"h-12 text-4xl",lg:"h-16 text-6xl"};function xe({light:e,dark:t,fallback:o="Turtle Club",className:r,size:s="lg"}){let[n,a]=useState(false),{theme:i}=P(),f=i==="dark"?t||e:e||t;return f&&!n?jsx("div",{className:cn("flex justify-center items-center",r),children:jsx("img",{src:f,alt:o,className:cn("object-contain",mt[s]),onError:()=>a(true),onLoad:()=>a(false)})}):jsx("div",{className:cn("flex justify-center items-center",r),children:jsx("span",{className:cn("font-bold text-primary",mt[s]),children:o})})}function pt(){let e=w(),t=Pe(),o=useAtomValue(C),r=useSetAtom(p);useEffect(()=>{r(s=>({...s,user:e.user||"",chain:e.network||1,distributorId:t,distributor_id:t,id:o?.id||""}));},[e.user,e.network,t,o?.id,r]);}function ft(){let e=useAtomValue(M);return {light:e?.logo?.light,dark:e?.logo?.dark,fallback:e?.logo?.fallback||"Turtle Club"}}var wo=[{value:"portfolio",label:"Portfolio"},{value:"earn",label:"Earn"},{value:"discover",label:"Discover"}];function Eo({config:e}){pt();let[t,o]=useState("earn"),r=useAtomValue(q),{light:s,dark:n,fallback:a}=ft(),{showNavigation:i}=P();return jsx(Ee,{config:e,children:jsxs("div",{className:"w-full h-full flex flex-col",children:[i&&jsx("div",{className:"flex-shrink-0",children:jsx(NavigationBar,{activeValue:t,variant:"menuBar",children:wo.map(u=>jsx(NavigationItem,{active:t===u.value,onClick:()=>o(u.value),value:u.value,variant:"menuBarDefault",children:u.label},u.value))})}),jsx("div",{className:`flex-1 min-h-0 ${i?"mt-5":""}`,children:t==="earn"&&r?jsx("div",{className:"w-full h-full overflow-hidden",children:jsx(ut,{})}):jsxs(Q,{variant:"container",className:"w-full h-full flex flex-col",children:[jsx("div",{className:"flex-shrink-0 py-4",children:jsx(xe,{light:s,dark:n,fallback:a,size:"lg"})}),jsx("div",{className:"flex-1 min-h-0 w-full",children:jsxs("div",{className:"h-full",children:[t==="earn"&&jsx(lt,{}),t==="portfolio"&&jsx("div",{className:"p-6 bg-background rounded-xl",children:jsx("p",{className:"text-foreground",children:"Portfolio Coming Soon..."})}),t==="discover"&&jsx("div",{className:"p-6 bg-background rounded-xl",children:jsx("p",{className:"text-foreground",children:"Discover Coming Soon..."})})]})})]})})]})})}function Co({adapter:e,config:t,distributorId:o}){return jsx(ce,{adapter:e,distributorId:o,children:jsx(Eo,{config:t})})}
2
+ export{ce as AdapterProvider,Co as EarnWidget,le as defaultWidgetStyleConfig,w as useAdapter,At as useNetworkMethods,Nt as useTransactionMethods,Tt as useWalletConnection};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map