Skip to content

Commit

Permalink
Merge pull request #1643 from orbs-network/dev2
Browse files Browse the repository at this point in the history
liquidity hub optimization
  • Loading branch information
sameepsi authored Dec 17, 2024
2 parents 3abd324 + f4ac369 commit 361c58d
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 58 deletions.
7 changes: 4 additions & 3 deletions src/components/Swap/SwapBestTrade.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,6 @@ const SwapBestTrade: React.FC<{
isLoading: liquidityHubQuoteLoading,
error: liquidityHubQuoteError,
refetch: fetchLiquidityHubQuote,
getLatestQuote,
} = useLiquidityHubQuote({
allowedSlippage,
inAmount: parsedAmount?.raw.toString(),
Expand Down Expand Up @@ -1279,6 +1278,8 @@ const SwapBestTrade: React.FC<{
}
}, [handleParaswap, onApprove, showApproveFlow]);

const getLatestOptimalRate = useCallback(() => optimalRate, [optimalRate]);

return (
<Box>
<TokenWarningModal
Expand All @@ -1294,9 +1295,9 @@ const SwapBestTrade: React.FC<{
isOpen={showLiquidityHubConfirm}
onDismiss={handleLiquidityHubConfirmDismiss}
quote={liquidityHubQuote}
getLatestQuote={getLatestQuote}
fetchLiquidityHubQuote={fetchLiquidityHubQuote}
onSwapFailed={onLiquidityHubSwapFailed}
optimalRate={optimalRate}
getOptimalRate={getLatestOptimalRate}
allowedSlippage={allowedSlippage}
onLiquidityHubSwapInProgress={setSwappingLiquidityHub}
/>
Expand Down
35 changes: 13 additions & 22 deletions src/components/Swap/orbs/ConfirmationModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -248,31 +248,40 @@ function ConfirmationContainer({

export const Error = () => {
const {
onDismiss,
onDismiss: _onDismiss,
inAmount,
state: { shouldUnwrap },
} = useConfirmationContext();
const { t } = useTranslation();
const { chainId } = useActiveWeb3React();
const nativeSymbol = ETHER[chainId].symbol;
const wSymbol = WETH[chainId].symbol;
const [isLoading, setIsLoading] = useState(false);

const { execute, wrapType } = useWrapCallback(
const { execute, inputError } = useWrapCallback(
WETH[chainId],
ETHER[chainId],
inAmount,
);

const [success, setSuccess] = useState(false);
const isLoading = wrapType === WrapType.UNWRAPPING;
const unwrap = useCallback(async () => {
try {
setIsLoading(true);
await execute?.();
setSuccess(true);
} catch (error) {
console.error(error);
} finally {
setIsLoading(false);
}
}, [execute]);

const onDismiss = useCallback(() => {
_onDismiss();
setSuccess(false);
}, [_onDismiss]);

if (success) {
return (
<Success
Expand Down Expand Up @@ -314,7 +323,7 @@ export const Error = () => {
</p>
)}
</Box>
{shouldUnwrap ? (
{!inputError && shouldUnwrap ? (
<Box className='orbsErrorContentButtons'>
<Button className='txSubmitButton' onClick={unwrap}>
{t('unwrap')}
Expand All @@ -334,24 +343,6 @@ export const Error = () => {
);
};

const SwapButton = ({
text,
onSubmit,
}: {
text?: string;
onSubmit: () => void;
}) => {
return (
<Box className='swapButtonWrapper'>
<Box width='100%'>
<Button fullWidth onClick={onSubmit}>
{text}
</Button>
</Box>
</Box>
);
};

export const Main = ({
parseSteps,
swapDetails,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,16 @@ import { useLiquidityHubSDK } from './hooks';
import useWrapCallback from 'hooks/useWrapCallback';
import { useSwapActionHandlers } from 'state/swap/hooks';
import { Field } from 'state/swap/actions';
import { useAppDispatch } from 'state';
import { updateUserBalance } from 'state/balance/actions';

export interface LiquidityHubConfirmationProps {
inCurrency?: Currency;
outCurrency?: Currency;
isOpen: boolean;
onDismiss: () => void;
getLatestQuote: () => Quote | undefined;
fetchLiquidityHubQuote: () => Promise<Quote | undefined>;
quote?: Quote | null;
onSwapFailed: () => void;
optimalRate?: OptimalRate;
getOptimalRate: () => OptimalRate | undefined;
allowedSlippage?: number;
onLiquidityHubSwapInProgress: (value: boolean) => void;
inAmount?: string;
Expand Down Expand Up @@ -363,15 +361,15 @@ const useSwapCallback = () => {

return useMutation({
mutationFn: async ({
acceptedQuote,
quote,
signature,
}: {
acceptedQuote: Quote;
quote: Quote;
signature: string;
}) => {
const txParams = await getParaswapTxParams();

const txHash = await liquidityHub.swap(acceptedQuote, signature, {
const txHash = await liquidityHub.swap(quote, signature, {
data: txParams?.data || '',
to: txParams?.to,
});
Expand All @@ -389,9 +387,8 @@ const useLiquidityHubSwapCallback = () => {
onAcceptQuote,
inCurrency,
outCurrency,
getLatestQuote,
fetchLiquidityHubQuote,
onLiquidityHubSwapInProgress,
quote,
} = useLiquidityHubConfirmationContext();
const { mutateAsync: signCallback } = useSignEIP712Callback();
const getSteps = useGetStepsCallback();
Expand Down Expand Up @@ -433,31 +430,34 @@ const useLiquidityHubSwapCallback = () => {
await approvalCallback();
}

const acceptedQuote = getLatestQuote() || quote;
const latestQuote = await fetchLiquidityHubQuote();

if (!acceptedQuote) {
if (!latestQuote) {
throw new Error('missing quote');
}

onAcceptQuote(acceptedQuote);
onAcceptQuote(latestQuote);
updateStore({ currentStep: Steps.SWAP });
const signature = await signCallback(acceptedQuote.permitData);
const signature = await signCallback(latestQuote.permitData);
onSignature(signature);

const txHash = await swapCallback({
acceptedQuote,
quote: latestQuote,
signature,
});

const details = await liquidityHubSdk.getTransactionDetails(
txHash,
acceptedQuote,
latestQuote,
);
console.log('lh swap success', details);

if (!details) {
throw new Error('missing transaction details');
}

onUserInput(Field.INPUT, '');
updateStore({ swapStatus: SwapStatus.SUCCESS });
onTradeSuccess(acceptedQuote);
onTradeSuccess(latestQuote);
} catch (error) {
const isRejectedOrTimeout =
isRejectedError(error) || isTimeoutError(error);
Expand Down Expand Up @@ -508,10 +508,14 @@ const useOnTradeSuccessCallback = () => {
const useParaswapTxParamsCallback = () => {
const paraswap = useParaswap();
const { account } = useActiveWeb3React();
const { allowedSlippage, optimalRate } = useLiquidityHubConfirmationContext();
const {
allowedSlippage,
getOptimalRate,
} = useLiquidityHubConfirmationContext();

return useMutation({
mutationFn: async () => {
const optimalRate = getOptimalRate();
if (!optimalRate || !allowedSlippage || !account) {
throw new Error('useParaswapTxParamsCallback missing args');
}
Expand Down
24 changes: 9 additions & 15 deletions src/components/Swap/orbs/LiquidityHub/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,20 +69,15 @@ export const useLiquidityHubQuote = ({
: wrappedCurrency(outCurrency, chainId)?.address;
}, [outCurrency, isNativeCurrency, chainId]);

const queryKey = useMemo(
() => [
const query = useQuery<Quote>({
queryKey: [
'useLiquidityHubQuote',
fromToken,
toToken,
inAmount,
allowedSlippage,
chainId,
],
[fromToken, toToken, inAmount, allowedSlippage, chainId],
);

const query = useQuery<Quote>({
queryKey,
queryFn: async ({ signal }) => {
if (!fromToken || !toToken || !inAmount || !chainId || !allowedSlippage) {
throw new Error('useLiquidityHubQuote Missing required parameters');
Expand Down Expand Up @@ -118,15 +113,14 @@ export const useLiquidityHubQuote = ({
isSupported,
});

const queryClient = useQueryClient();
const refetch = useCallback(async () => {
return (await query.refetch()).data;
}, [query.refetch]);

return useMemo(() => {
return {
...query,
getLatestQuote: () => queryClient.getQueryData<Quote>(queryKey),
refetch: async () => (await query.refetch()).data,
};
}, [query, queryClient, queryKey]);
return {
...query,
refetch,
};
};

export const useGetBetterPrice = (
Expand Down

0 comments on commit 361c58d

Please sign in to comment.