Skip to content

Commit

Permalink
clean up + add lh override by query params
Browse files Browse the repository at this point in the history
  • Loading branch information
sukhsinghcodes committed Dec 3, 2024
1 parent edb58e9 commit 5bdc8ee
Show file tree
Hide file tree
Showing 15 changed files with 122 additions and 135 deletions.
20 changes: 20 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
##########
# If adding to this file, think about updating .eslintignore too
##########

# General #
##########
build/
coverage/
dist/
vars/
vendor/
.cache/
public/
CHANGELOG.md
generated/
.yarn
.github/workflows
diagnostics/**.md
*.tfstate
**/.gen
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"printWidth": 100,
"singleQuote": true,
"semi": true
}
10 changes: 5 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Header } from "@/components/header";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./components/ui/tabs";
import { SwapLiquidityHub } from "./trade/liquidity-hub/liquidity-hub-swap";
import { Settings } from "./trade/settings";
import { SwapTwap, SwapLimit } from "./trade/twap/twap";
import { Header } from '@/components/header';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './components/ui/tabs';
import { SwapLiquidityHub } from './trade/liquidity-hub/liquidity-hub-swap';
import { Settings } from './trade/settings';
import { SwapTwap, SwapLimit } from './trade/twap/twap';

export function App() {
return (
Expand Down
6 changes: 3 additions & 3 deletions src/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface AppStore {
slippage: number;
Expand All @@ -12,7 +12,7 @@ export const useAppState = create(
setSlippage: (slippage: number) => set({ slippage }),
}),
{
name: "main-store",
name: 'main-store',
}
)
);
84 changes: 31 additions & 53 deletions src/trade/liquidity-hub/context.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,19 @@
import { useDefaultTokens } from "@/lib";
import { Token } from "@/types";
import {
constructSDK,
LiquidityHubSDK,
Quote,
} from "@orbs-network/liquidity-hub-sdk";
import { OptimalRate } from "@paraswap/sdk";
import {
useContext,
ReactNode,
useReducer,
useCallback,
useMemo,
createContext,
useEffect,
} from "react";
import { useAccount } from "wagmi";
import { useToRawAmount } from "../hooks";
import { useDefaultTokens } from '@/lib';
import { Token } from '@/types';
import { constructSDK, LiquidityHubSDK, Quote } from '@orbs-network/liquidity-hub-sdk';
import { OptimalRate } from '@paraswap/sdk';
import { ReactNode, useReducer, useCallback, useMemo, createContext, useEffect } from 'react';
import { useAccount } from 'wagmi';
import { useToRawAmount } from '../hooks';

const initialState: State = {
inToken: null,
outToken: null,
inputAmount: "",
inputAmount: '',
acceptedQuote: undefined,
acceptedOptimalRate: undefined,
liquidityHubDisabled: false,
forceLiquidityHub: true,
forceLiquidityHub: false,
confirmationModalOpen: false,
proceedWithLiquidityHub: false,
};
Expand All @@ -40,16 +28,16 @@ interface State {
signature?: string;
confirmationModalOpen: boolean;
proceedWithLiquidityHub: boolean;
acceptedOptimalRate?: OptimalRate
acceptedOptimalRate?: OptimalRate;
}

type Action = { type: "UPDATE"; payload: Partial<State> } | { type: "RESET" };
type Action = { type: 'UPDATE'; payload: Partial<State> } | { type: 'RESET' };

const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "UPDATE":
case 'UPDATE':
return { ...state, ...action.payload };
case "RESET":
case 'RESET':
return initialState;
default:
return state;
Expand All @@ -64,62 +52,52 @@ interface ContextType {
parsedInputAmount?: string;
}

const Context = createContext({} as ContextType);
// eslint-disable-next-line react-refresh/only-export-components
export const useLiquidityHubSwapContext = () => {
return useContext(Context);
};
export const LiquidityHubContext = createContext({} as ContextType);

export const LiquidityHubSwapProvider = ({
children,
}: {
children: ReactNode;
}) => {
export const LiquidityHubSwapProvider = ({ children }: { children: ReactNode }) => {
const [_state, dispatch] = useReducer(reducer, initialState);
const defaultTokens = useDefaultTokens();
const chainId = useAccount().chainId;


const state = useMemo(() => {
return {
..._state,
inToken: _state.inToken || defaultTokens?.inToken || null,
inToken: _state.inToken || defaultTokens?.inToken || null,
outToken: _state.outToken || defaultTokens?.outToken || null,
};
}, [_state, defaultTokens]);


const parsedInputAmount = useToRawAmount(
state.inputAmount,
state.inToken?.decimals
);
const parsedInputAmount = useToRawAmount(state.inputAmount, state.inToken?.decimals);

const updateState = useCallback(
(payload: Partial<State>) => {
dispatch({ type: "UPDATE", payload });
dispatch({ type: 'UPDATE', payload });
},
[dispatch]
);

const resetState = useCallback(() => {
dispatch({ type: "RESET" });
dispatch({ type: 'RESET' });
}, [dispatch]);

useEffect(() => {
if(chainId) {
if (chainId) {
resetState();
}
}, [chainId, resetState])

}, [chainId, resetState]);

const sdk = useMemo(() => constructSDK({ partner: 'widget', chainId }), [chainId]);

const sdk = useMemo(
() => constructSDK({ partner: "widget", chainId }),
[chainId]
);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const lh = params.get('lh');
if (lh) {
updateState({ forceLiquidityHub: true });
}
}, [updateState]);

return (
<Context.Provider
<LiquidityHubContext.Provider
value={{
state,
parsedInputAmount,
Expand All @@ -129,6 +107,6 @@ export const LiquidityHubSwapProvider = ({
}}
>
{children}
</Context.Provider>
</LiquidityHubContext.Provider>
);
};
4 changes: 2 additions & 2 deletions src/trade/liquidity-hub/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { permit2Address } from "@orbs-network/liquidity-hub-sdk";
import { useMemo, useCallback } from "react";
import { Address } from "viem";
import { useAccount } from "wagmi";
import { useLiquidityHubSwapContext } from "./context";
import { useLiquidityHubSwapContext } from "./useLiquidityHubSwapContext";
import { QUOTE_REFETCH_INTERVAL } from "./consts";


Expand Down Expand Up @@ -59,7 +59,7 @@ const useNetwork = () => {

const useNativeOrWrapped = (address?: string) => {
const callback = useNativeOrWrappedAddressCallback();
return useMemo(() => callback(address), [address]);
return useMemo(() => callback(address), [address, callback]);
};

const useNativeOrWrappedAddressCallback = () => {
Expand Down
18 changes: 3 additions & 15 deletions src/trade/liquidity-hub/liquidity-hub-confirmation-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
useUsdAmount,
} from "@/lib";
import { useAccount } from "wagmi";
import { useLiquidityHubSwapContext } from "./context";
import { useLiquidityHubSwapContext } from "./useLiquidityHubSwapContext";
import {
useLiquidityHubApproval,
useOptimalRate,
Expand All @@ -23,7 +23,6 @@ import {
SwapConfirmationDialog,
useSwapProgress,
} from "../swap-confirmation-dialog";
import { _TypedDataEncoder } from "@ethersproject/hash";
import { useToExactAmount } from "../hooks";
import { useLiquidityHubSwapCallback } from "./useLiquidityHubSwapCallback";
import { useParaswapSwapCallback } from "./useParaswapSwapCallback";
Expand Down Expand Up @@ -100,12 +99,7 @@ export function LiquidityHubConfirmationDialog() {
} else {
swapWithLiquidityHub();
}
}, [
isLiquidityHubTrade,
swapWithLiquidityHub,
swapWithParaswap,
updateProgressState,
]);
}, [isLiquidityHubTrade, swapWithLiquidityHub, swapWithParaswap]);

const onClose = useCallback(() => {
updateState({
Expand All @@ -121,13 +115,7 @@ export function LiquidityHubConfirmationDialog() {
setTimeout(() => {
resetProgressState();
}, 5_00);
}, [
progressState.swapStatus,
progressState.currentStep,
resetProgressState,
updateState,
refetchBalances,
]);
}, [progressState.swapStatus, resetProgressState, updateState, refetchBalances]);

const usd = useUSD();
const outAmount = useOutAmount();
Expand Down
68 changes: 26 additions & 42 deletions src/trade/liquidity-hub/liquidity-hub-swap.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import { TokenCard } from "@/components/tokens/token-card";
import { SwitchButton } from "@/components/ui/switch-button";
import { useCallback, useMemo } from "react";
import { useAccount } from "wagmi";
import { Button } from "@/components/ui/button";
import { _TypedDataEncoder } from "@ethersproject/hash";
import { Token } from "@/types";
import { ErrorCodes } from "@/lib";
import "../style.css";
import { useConnectModal } from "@rainbow-me/rainbowkit";
import {
LiquidityHubSwapProvider,
useLiquidityHubSwapContext,
} from "./context";
import { useToExactAmount } from "../hooks";
import { LiquidityHubConfirmationDialog } from "./liquidity-hub-confirmation-dialog";
import { useLiquidityHubInputError, useOptimalRate } from "./hooks";
import { SwapDetails } from "./swap-details";
import { useLiquidityHubQuote } from "./useLiquidityHubQuote";
import { useIsLiquidityHubTrade } from "./useIsLiquidityHubTrade";
import { TokenCard } from '@/components/tokens/token-card';
import { SwitchButton } from '@/components/ui/switch-button';
import { useCallback, useMemo } from 'react';
import { useAccount } from 'wagmi';
import { Button } from '@/components/ui/button';
import { Token } from '@/types';
import { ErrorCodes } from '@/lib';
import '../style.css';
import { useConnectModal } from '@rainbow-me/rainbowkit';
import { LiquidityHubSwapProvider } from './context';
import { useToExactAmount } from '../hooks';
import { LiquidityHubConfirmationDialog } from './liquidity-hub-confirmation-dialog';
import { useLiquidityHubInputError, useOptimalRate } from './hooks';
import { SwapDetails } from './swap-details';
import { useIsLiquidityHubTrade } from './useIsLiquidityHubTrade';
import { useLiquidityHubSwapContext } from './useLiquidityHubSwapContext';

function SwapPanel() {
return (
Expand All @@ -44,7 +40,7 @@ const Switch = () => {
updateState({
inToken: outToken,
outToken: inToken,
inputAmount: "",
inputAmount: '',
});
}, [inToken, outToken, updateState]);

Expand All @@ -58,8 +54,7 @@ const Switch = () => {
const ShowConfirmationButton = () => {
const account = useAccount().address;
const openConnectModal = useConnectModal().openConnectModal;
const { data: liquidityHubQuote } = useLiquidityHubQuote();
const { data: optimalRate, isLoading: optimalRateLoading } = useOptimalRate();
const { data: optimalRate } = useOptimalRate();
const inputError = useLiquidityHubInputError();
const proceedWithLiquidityHub = useIsLiquidityHubTrade();

Expand All @@ -75,40 +70,32 @@ const ShowConfirmationButton = () => {
const { text, onClick } = useMemo(() => {
if (!account) {
return {
text: "Connect wallet",
text: 'Connect wallet',
onClick: openConnectModal,
};
}
if (inputError === ErrorCodes.InsufficientBalance) {
return {
text: "Insufficient balance",
text: 'Insufficient balance',
};
}
if (inputError === ErrorCodes.EnterAmount) {
return {
text: "Enter amount",
text: 'Enter amount',
};
}

if (!optimalRate && inputAmount) {
return {
text: "Fetching rate...",
text: 'Fetching rate...',
};
}

return {
text: "Swap",
text: 'Swap',
onClick: onOpenConfirmation,
};
}, [
inputError,
inputAmount,
liquidityHubQuote,
optimalRate,
optimalRateLoading,
openConnectModal,
onOpenConfirmation,
]);
}, [account, inputError, optimalRate, inputAmount, onOpenConfirmation, openConnectModal]);

return (
<Button className="mt-2" size="lg" onClick={onClick} disabled={!onClick}>
Expand Down Expand Up @@ -158,10 +145,7 @@ const OutTokenCard = () => {
state: { outToken },
updateState,
} = useLiquidityHubSwapContext();
const destAmount = useToExactAmount(
optimalRate?.destAmount,
outToken?.decimals
);
const destAmount = useToExactAmount(optimalRate?.destAmount, outToken?.decimals);

const onSelectToken = useCallback(
(outToken: Token) => {
Expand All @@ -173,7 +157,7 @@ const OutTokenCard = () => {
return (
<TokenCard
label="Buy"
amount={destAmount ?? ""}
amount={destAmount ?? ''}
amountUsd={optimalRate?.destUSD}
selectedToken={outToken}
onSelectToken={onSelectToken}
Expand Down
Loading

0 comments on commit 5bdc8ee

Please sign in to comment.