Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration of CrocSmartSwapPlan for multihop swaps #4500

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"private": true,
"type": "module",
"dependencies": {
"@crocswap-libs/sdk": "^1.1.2",
"@crocswap-libs/sdk": "^1.2.0",
"@d3fc/d3fc-extent": "^4.0.2",
"@emotion/react": "^11.13.5",
"@emotion/styled": "^11.10.5",
Expand Down
31 changes: 23 additions & 8 deletions src/App/functions/calcImpact.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,38 @@
import { CrocEnv, CrocImpact } from '@crocswap-libs/sdk';
import { CrocEnv, CrocSmartSwapImpact } from '@crocswap-libs/sdk';
import { getSwapPlan } from '../../ambient-utils/dataLayer';
import { SinglePoolDataIF } from '../../ambient-utils/types';

// Should be a multiple of `batchMaxCount` from BatchedJsonRpcProvider to
// maximize the number of routes that are evaluated in one `eth_call`.
const MAX_IMPACTS_PER_CALL = 40;

export const calcImpact = async (
isQtySell: boolean,
env: CrocEnv,
crocEnv: CrocEnv,
sellTokenAddress: string,
buyTokenAddress: string,
slippageTolerancePercentage: number,
qty: string,
): Promise<CrocImpact | undefined> => {
allPoolStats: SinglePoolDataIF[],
directSwapsOnly?: boolean,
): Promise<CrocSmartSwapImpact | undefined> => {
try {
const args = { slippage: slippageTolerancePercentage };
const swapPlan = isQtySell
? env.sell(sellTokenAddress, qty).for(buyTokenAddress, args)
: env.buy(buyTokenAddress, qty).with(sellTokenAddress, args);
return await swapPlan.impact;
const plan = getSwapPlan({
crocEnv,
isQtySell,
qty,
buyTokenAddress,
sellTokenAddress,
slippageTolerancePercentage,
allPoolStats,
directSwapsOnly,
});
return await plan.calcImpacts(MAX_IMPACTS_PER_CALL);

// For valid pools, the impact calculation will fail only if liquidity
// in the pool is insufficient
} catch (e) {
console.error('calcImpact error:', e);
return undefined;
}
};
35 changes: 10 additions & 25 deletions src/App/functions/calcL1Gas.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { CrocEnv, estimateScrollL1Gas } from '@crocswap-libs/sdk';
import {
CrocEnv,
CrocSmartSwapImpact,
estimateScrollL1Gas,
} from '@crocswap-libs/sdk';
import { getSwapPlan } from '../../ambient-utils/dataLayer';

interface SimulateSwapParams {
crocEnv: CrocEnv;
Expand All @@ -9,35 +14,15 @@ interface SimulateSwapParams {
slippageTolerancePercentage: number; // TODO: add comments about params and their expected values
isWithdrawFromDexChecked?: boolean;
isSaveAsDexSurplusChecked?: boolean;
lastImpact: CrocSmartSwapImpact;
}
export const getFauxRawTx = async (
params: SimulateSwapParams,
): Promise<`0x${string}` | undefined> => {
const {
crocEnv,
isQtySell,
qty,
buyTokenAddress,
sellTokenAddress,
slippageTolerancePercentage,
isWithdrawFromDexChecked = true,
isSaveAsDexSurplusChecked = false,
} = params;
const { lastImpact } = params;
try {
const plan = isQtySell
? crocEnv.sell(sellTokenAddress, qty).for(buyTokenAddress, {
slippage: slippageTolerancePercentage / 100,
})
: crocEnv.buy(buyTokenAddress, qty).with(sellTokenAddress, {
slippage: slippageTolerancePercentage / 100,
});

const raw = await plan.getFauxRawTx({
settlement: {
sellDexSurplus: isWithdrawFromDexChecked,
buyDexSurplus: isSaveAsDexSurplusChecked,
},
});
const plan = getSwapPlan(params);
const raw = await plan.getFauxRawTx(lastImpact);
return raw;
} catch (e) {
console.log({ e });
Expand Down
38 changes: 38 additions & 0 deletions src/App/hooks/useDirectSwapsOnlyPref.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { useMemo, useState } from 'react';

export interface directSwapsOnlyIF {
isEnabled: boolean;
setValue: (newVal: boolean) => void;
enable: () => void;
disable: () => void;
toggle: () => void;
}

export const useDirectSwapsOnly = (): directSwapsOnlyIF => {
const localStorageKey = 'direct_swaps_only';

const checkPref = (): boolean | undefined => {
const output: boolean =
JSON.parse(localStorage.getItem(localStorageKey) as string) ||
false;
return output;
};

const [pref, setPref] = useState<boolean>(checkPref() ?? false);

const updatePref = (newVal: boolean): void => {
localStorage.setItem(localStorageKey, JSON.stringify(newVal));
setPref(newVal);
};

return useMemo(
() => ({
isEnabled: pref,
setValue: updatePref,
enable: () => updatePref(true),
disable: () => updatePref(false),
toggle: () => updatePref(!pref),
}),
[pref],
);
};
4 changes: 3 additions & 1 deletion src/App/hooks/useFetchPoolStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ const useFetchPoolStats = (
setPoolPriceDisplay(undefined);
setLocalPoolPriceNonDisplay(undefined);
setPoolPriceDisplayNum(undefined);
setIsPoolInitialized(false);
// setIsPoolInitialized(false); // TODO: revert
}
})();
}
Expand Down Expand Up @@ -335,6 +335,7 @@ const useFetchPoolStats = (
lastPriceLiq: currentPoolStats?.lastPriceLiq || 0,
lastPriceSwap: currentPoolStats?.lastPriceSwap || 0,
latestTime: currentPoolStats?.latestTime || 0,
events: currentPoolStats?.events || 0,
isHistorical: false,
};

Expand Down Expand Up @@ -362,6 +363,7 @@ const useFetchPoolStats = (
lastPriceLiq: currentPoolStats?.lastPriceLiq || 0,
lastPriceSwap: currentPoolStats?.lastPriceSwap || 0,
latestTime: currentPoolStats?.latestTime || 0,
events: currentPoolStats?.events || 0,
isHistorical: true,
};

Expand Down
2 changes: 1 addition & 1 deletion src/App/hooks/useSimulatedIsPoolInitialized.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const useSimulatedIsPoolInitialized = () => {
if (isUserOnline) {
// Simulate the pool initialization for the first 10 seconds
const timeoutId = setTimeout(() => {
setSimulatedIsPoolInitialized(false);
// setSimulatedIsPoolInitialized(false); // TODO: revert
}, 10000);
// Clean up the timeout when the component unmounts
return () => clearTimeout(timeoutId);
Expand Down
1 change: 1 addition & 0 deletions src/ambient-utils/dataLayer/functions/getPoolStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ interface PoolStatsServerIF {
lastPriceIndic: number;
lastPriceSwap: number;
feeRate: number;
events: number;
isHistorical: boolean;
}

Expand Down
42 changes: 27 additions & 15 deletions src/ambient-utils/dataLayer/transactions/swap.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { CrocEnv } from '@crocswap-libs/sdk';
import {
CrocEnv,
CrocSmartSwapImpact,
CrocSmartSwapPoolRouter,
} from '@crocswap-libs/sdk';
import { SinglePoolDataIF } from '../../types';

interface PerformSwapParams {
crocEnv: CrocEnv;
Expand All @@ -9,9 +14,11 @@ interface PerformSwapParams {
slippageTolerancePercentage: number; // TODO: add comments about params and their expected values
isWithdrawFromDexChecked?: boolean;
isSaveAsDexSurplusChecked?: boolean;
allPoolStats?: SinglePoolDataIF[];
directSwapsOnly?: boolean;
}

export async function performSwap(params: PerformSwapParams) {
export function getSwapPlan(params: PerformSwapParams) {
const {
crocEnv,
isQtySell,
Expand All @@ -23,20 +30,25 @@ export async function performSwap(params: PerformSwapParams) {
isSaveAsDexSurplusChecked = false,
} = params;

const plan = isQtySell
? crocEnv.sell(sellTokenAddress, qty).for(buyTokenAddress, {
slippage: slippageTolerancePercentage / 100,
})
: crocEnv.buy(buyTokenAddress, qty).with(sellTokenAddress, {
slippage: slippageTolerancePercentage / 100,
});
const plan = crocEnv
.smartSwap(sellTokenAddress, buyTokenAddress, qty, !isQtySell, {
slippage: slippageTolerancePercentage / 100,
settlement: {
fromSurplus: isWithdrawFromDexChecked || false,
toSurplus: isSaveAsDexSurplusChecked || false,
},
disableMultihop: params.directSwapsOnly || false,
})
.withRouter(new CrocSmartSwapPoolRouter(params.allPoolStats || []));

const tx = await plan.swap({
settlement: {
sellDexSurplus: isWithdrawFromDexChecked,
buyDexSurplus: isSaveAsDexSurplusChecked,
},
});
return plan;
}

export async function performSwap(
params: PerformSwapParams,
lastImpact: CrocSmartSwapImpact,
) {
const plan = getSwapPlan(params);
const tx = await plan.swap(lastImpact);
return tx;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.main_container {
display: flex;
justify-content: space-between;
flex-direction: row;
align-items: center;

color: var(--text2);
font-size: var(--body-size);
line-height: var(--body-lh);
margin: 1rem;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { Dispatch, SetStateAction, useContext, useId } from 'react';
import { AiOutlineInfoCircle } from 'react-icons/ai';
import { AppStateContext } from '../../../contexts/AppStateContext';
import { FlexContainer } from '../../../styled/Common';
import { ExplanationButton } from '../../Form/Icons/Icons.styles';
import Toggle from '../../Form/Toggle';
import styles from './DirectSwapsOnlyControl.module.css';

interface propsIF {
tempDirectSwapsOnly: boolean;
setTempDirectSwapsOnly: Dispatch<SetStateAction<boolean>>;
displayInSettings?: boolean;
}

export default function DirectSwapsOnlyModalControl(props: propsIF) {
const { tempDirectSwapsOnly, setTempDirectSwapsOnly, displayInSettings } =
props;
const {
globalPopup: { open: openGlobalPopup },
} = useContext(AppStateContext);

const compKey = useId();

const toggleAriaLabel = `${
tempDirectSwapsOnly ? 'disable save' : 'save'
} to exchange balance for future trading at lower gas costs`;

return (
<div className={styles.main_container}>
{displayInSettings ? (
<FlexContainer alignItems='center' gap={8}>
<p tabIndex={0}>{'Direct swaps only'}</p>
<ExplanationButton
onClick={() =>
openGlobalPopup(
<div>
Forcing direct swaps may result in reduced
swap output compared to multihop swaps but
with lower fees.
</div>,
'Direct swaps only',
'right',
)
}
aria-label='Open direct swaps explanation popup.'
>
<AiOutlineInfoCircle color='var(--text2)' />
</ExplanationButton>
</FlexContainer>
) : (
<p tabIndex={0}>Send to exchange balance</p>
)}

<Toggle
key={compKey}
isOn={tempDirectSwapsOnly}
disabled={false}
handleToggle={() =>
setTempDirectSwapsOnly(!tempDirectSwapsOnly)
}
id='disabled_confirmation_modal_toggle'
aria-label={toggleAriaLabel}
/>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default function SaveToDexBalanceModalControl(props: propsIF) {
'right',
)
}
aria-label='Open range width explanation popup.'
aria-label='Open exchange balance explanation popup.'
>
<AiOutlineInfoCircle color='var(--text2)' />
</ExplanationButton>
Expand Down
Loading
Loading