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

TW-1622 Implement swapping without 3Route liquidity baking proxy #1242

Merged
merged 11 commits into from
Dec 30, 2024
6 changes: 4 additions & 2 deletions src/app/hooks/use-swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ export const useSwap = () => {
fromRoute3Token: Route3Token,
toRoute3Token: Route3Token,
inputAmountAtomic: BigNumber,
minimumReceivedAtomic: BigNumber,
expectedReceivedAtomic: BigNumber,
slippageRatio: number,
hops: Route3SwapHops | Route3LiquidityBakingHops
) =>
getSwapTransferParams(
fromRoute3Token,
toRoute3Token,
inputAmountAtomic,
minimumReceivedAtomic,
expectedReceivedAtomic,
slippageRatio,
hops,
tezos,
publicKeyHash
Expand Down
19 changes: 17 additions & 2 deletions src/app/store/swap/state.mock.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { Route3SwapParamsResponse } from 'lib/route3/interfaces';
import { Route3SwapParamsResponse, Route3TreeNodeType } from 'lib/route3/interfaces';
import { createEntity, mockPersistedState } from 'lib/store';

import type { SwapState } from './state';

export const DEFAULT_SWAP_PARAMS: Route3SwapParamsResponse = { input: undefined, output: undefined, hops: [] };
export const DEFAULT_SWAP_PARAMS: Route3SwapParamsResponse = {
input: undefined,
output: undefined,
hops: [],
tree: {
type: Route3TreeNodeType.Empty,
items: [],
dexId: null,
tokenInId: 0,
tokenOutId: 1,
tokenInAmount: '0',
tokenOutAmount: '0',
width: 0,
height: 0
}
};

export const mockSwapState = mockPersistedState<SwapState>({
swapParams: createEntity(DEFAULT_SWAP_PARAMS),
Expand Down
39 changes: 21 additions & 18 deletions src/app/templates/InternalConfirmation.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React, { FC, useCallback, useEffect, useMemo } from 'react';

import { localForger } from '@taquito/local-forging';
import BigNumber from 'bignumber.js';
import classNames from 'clsx';
import { useDispatch } from 'react-redux';

Expand All @@ -21,8 +20,7 @@ import OperationsBanner from 'app/templates/OperationsBanner/OperationsBanner';
import RawPayloadView from 'app/templates/RawPayloadView';
import ViewsSwitcher from 'app/templates/ViewsSwitcher/ViewsSwitcher';
import { ViewsSwitcherItemProps } from 'app/templates/ViewsSwitcher/ViewsSwitcherItem';
import { TEZ_TOKEN_SLUG, toTokenSlug } from 'lib/assets';
import { useRawBalance } from 'lib/balances';
import { toTokenSlug } from 'lib/assets';
import { T, t } from 'lib/i18n';
import { useRetryableSWR } from 'lib/swr';
import { useChainIdValue, useNetwork, useRelevantAccounts, tryParseExpenses } from 'lib/temple/front';
Expand Down Expand Up @@ -87,24 +85,29 @@ const InternalConfirmation: FC<InternalConfiramtionProps> = ({ payload, onConfir
}));
}, [rawExpensesData]);

const { value: tezBalance } = useRawBalance(TEZ_TOKEN_SLUG, account.publicKeyHash);
useEffect(() => {
try {
const { errorDetails, errors, name } = payloadError.error[0];
if (
payload.type !== 'operations' ||
!errorDetails.toLowerCase().includes('estimation') ||
name !== 'TezosOperationError' ||
!Array.isArray(errors)
) {
return;
}

const totalTransactionCost = useMemo(() => {
if (payload.type === 'operations') {
return payload.opParams.reduce(
(accumulator, currentOpParam) => accumulator.plus(currentOpParam.amount),
new BigNumber(0)
);
}
const tezBalanceTooLow = errors.some(error => {
const { id, contract } = error ?? {};

return new BigNumber(0);
}, [payload]);
return id?.includes('balance_too_low') && contract === payload.sourcePkh;
});

useEffect(() => {
if (tezBalance && new BigNumber(tezBalance).isLessThanOrEqualTo(totalTransactionCost)) {
dispatch(setOnRampPossibilityAction(true));
}
}, [dispatch, tezBalance, totalTransactionCost]);
if (tezBalanceTooLow) {
dispatch(setOnRampPossibilityAction(true));
}
} catch {}
}, [dispatch, payload.sourcePkh, payload.type, payloadError]);

const signPayloadFormats: ViewsSwitcherItemProps[] = useMemo(() => {
if (payload.type === 'operations') {
Expand Down
118 changes: 67 additions & 51 deletions src/app/templates/SwapForm/SwapForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ import { ZERO } from 'lib/utils/numbers';
import { parseTransferParamsToParamsWithKind } from 'lib/utils/parse-transfer-params';
import {
calculateSidePaymentsFromInput,
calculateOutputFeeAtomic,
getRoutingFeeTransferParams
getRoutingFeeTransferParams,
multiplyAtomicAmount,
calculateOutputAmounts
} from 'lib/utils/swap.utils';
import { HistoryAction, navigate } from 'lib/woozie';

Expand All @@ -58,10 +59,10 @@ import { slippageToleranceInputValidationFn } from './SwapFormInput/SlippageTole
import { SwapFormInput } from './SwapFormInput/SwapFormInput';
import { SwapMinimumReceived } from './SwapMinimumReceived/SwapMinimumReceived';

// These values have been set after some experimentation. They are different to the respective values in
// templewallet-mobile because the mobile app still uses taquito v19.0.0, which has a different gas estimation algorithm.
const SINGLE_SWAP_IN_BATCH_MAX_DEXES = 12;
const LB_OPERATION_DEXES_COST = 3;
const CASHBACK_SWAP_MAX_DEXES = 3;
// Actually, at most 2 dexes for each of underlying SIRS -> tzBTC -> X swap and SIRS -> XTZ -> X swap
const MAIN_SIRS_SWAP_MAX_DEXES = 4;
const MAIN_NON_SIRS_SWAP_MAX_DEXES = 3;

export const SwapForm: FC = () => {
const dispatch = useDispatch();
Expand Down Expand Up @@ -104,15 +105,23 @@ export const SwapForm: FC = () => {
const [isAlertVisible, setIsAlertVisible] = useState(false);

const slippageRatio = useMemo(() => getPercentageRatio(slippageTolerance ?? 0), [slippageTolerance]);
const minimumReceivedAmountAtomic = useMemo(() => {
if (isDefined(swapParams.data.output)) {
return tokensToAtoms(new BigNumber(swapParams.data.output), outputAssetMetadata.decimals)
.multipliedBy(slippageRatio)
.integerValue(BigNumber.ROUND_DOWN);
} else {
return ZERO;
}
}, [swapParams.data.output, outputAssetMetadata.decimals, slippageRatio]);
const { outputAtomicAmountBeforeFee, minimumReceivedAtomic, outputFeeAtomicAmount } = useMemo(
() =>
calculateOutputAmounts(
inputValue.amount,
inputAssetMetadata.decimals,
swapParams.data.output,
outputAssetMetadata.decimals,
slippageRatio
),
[
inputValue.amount,
inputAssetMetadata.decimals,
swapParams.data.output,
outputAssetMetadata.decimals,
slippageRatio
]
);

const hopsAreAbsent = isLiquidityBakingParamsResponse(swapParams.data)
? swapParams.data.tzbtcHops.length === 0 && swapParams.data.xtzHops.length === 0
Expand All @@ -134,17 +143,13 @@ export const SwapForm: FC = () => {
const isOutputTokenTempleToken = outputAssetSlug === KNOWN_TOKENS_SLUGS.TEMPLE;
const isSirsSwap = inputAssetSlug === KNOWN_TOKENS_SLUGS.SIRS || outputAssetSlug === KNOWN_TOKENS_SLUGS.SIRS;
const isSwapAmountMoreThreshold = inputAmountInUsd.isGreaterThanOrEqualTo(SWAP_THRESHOLD_TO_GET_CASHBACK);
const totalMaxDexes = SINGLE_SWAP_IN_BATCH_MAX_DEXES - (isSirsSwap ? LB_OPERATION_DEXES_COST : 0);
const cashbackSwapMaxDexes = Math.ceil(totalMaxDexes / (isSirsSwap ? 3 : 2));
const mainSwapMaxDexes =
totalMaxDexes - (isSwapAmountMoreThreshold && !isInputTokenTempleToken ? cashbackSwapMaxDexes : 0);
const mainSwapMaxDexes = isSirsSwap ? MAIN_SIRS_SWAP_MAX_DEXES : MAIN_NON_SIRS_SWAP_MAX_DEXES;

return {
isInputTokenTempleToken,
isOutputTokenTempleToken,
isSwapAmountMoreThreshold,
mainSwapMaxDexes,
cashbackSwapMaxDexes
mainSwapMaxDexes
};
},
[allUsdToTokenRates]
Expand Down Expand Up @@ -221,21 +226,24 @@ export const SwapForm: FC = () => {
amount: undefined
});
} else {
const outputAtomicAmountBeforeFee = tokensToAtoms(new BigNumber(currentOutput), outputAssetMetadata.decimals);
const outputFeeAtomic = calculateOutputFeeAtomic(
tokensToAtoms(inputValue.amount ?? ZERO, inputAssetMetadata.decimals),
outputAtomicAmountBeforeFee
const { expectedReceivedAtomic } = calculateOutputAmounts(
inputValue.amount,
inputAssetMetadata.decimals,
currentOutput,
outputAssetMetadata.decimals,
slippageRatio
);
setValue('output', {
assetSlug: outputValue.assetSlug,
amount: atomsToTokens(outputAtomicAmountBeforeFee.minus(outputFeeAtomic), outputAssetMetadata.decimals)
amount: atomsToTokens(expectedReceivedAtomic, outputAssetMetadata.decimals)
});
}

if (isSubmitButtonPressedRef.current) {
triggerValidation();
}
}, [
slippageRatio,
swapParams.data.output,
setValue,
triggerValidation,
Expand Down Expand Up @@ -291,7 +299,6 @@ export const SwapForm: FC = () => {
inputFeeAtomic: routingFeeFromInputAtomic,
cashbackSwapInputAtomic: cashbackSwapInputFromInAtomic
} = calculateSidePaymentsFromInput(atomsInputValue);
const routingFeeFromOutputAtomic = calculateOutputFeeAtomic(atomsInputValue, minimumReceivedAmountAtomic);

if (!fromRoute3Token || !toRoute3Token || !swapParams.data.output || !inputValue.assetSlug) {
return;
Expand All @@ -303,7 +310,7 @@ export const SwapForm: FC = () => {
const allSwapParams: Array<TransferParams> = [];
let routingOutputFeeTransferParams: TransferParams[] = await getRoutingFeeTransferParams(
toRoute3Token,
routingFeeFromOutputAtomic,
outputFeeAtomicAmount,
publicKeyHash,
ROUTING_FEE_ADDRESS,
tezos
Expand All @@ -313,16 +320,19 @@ export const SwapForm: FC = () => {
fromRoute3Token,
toRoute3Token,
swapInputMinusFeeAtomic,
minimumReceivedAmountAtomic,
outputAtomicAmountBeforeFee,
slippageRatio,
swapParams.data
);

if (route3SwapOpParams.length === 0) {
return;
}

const { isInputTokenTempleToken, isOutputTokenTempleToken, isSwapAmountMoreThreshold, cashbackSwapMaxDexes } =
getSwapWithFeeParams(inputValue, outputValue);
const { isInputTokenTempleToken, isOutputTokenTempleToken, isSwapAmountMoreThreshold } = getSwapWithFeeParams(
inputValue,
outputValue
);

if (isInputTokenTempleToken && isSwapAmountMoreThreshold) {
const routingInputFeeOpParams = await getRoutingFeeTransferParams(
Expand All @@ -348,30 +358,34 @@ export const SwapForm: FC = () => {
toSymbol: TEMPLE_TOKEN.symbol,
toTokenDecimals: TEMPLE_TOKEN.decimals,
amount: atomsToTokens(routingFeeFromInputAtomic, fromRoute3Token.decimals).toFixed(),
dexesLimit: cashbackSwapMaxDexes,
dexesLimit: CASHBACK_SWAP_MAX_DEXES,
rpcUrl: tezos.rpc.getRpcUrl()
});

const templeOutputAtomic = tokensToAtoms(
const templeExpectedOutputAtomic = tokensToAtoms(
new BigNumber(swapToTempleParams.output ?? ZERO),
TEMPLE_TOKEN.decimals
)
.multipliedBy(ROUTING_FEE_SLIPPAGE_RATIO)
.integerValue(BigNumber.ROUND_DOWN);
);
const templeMinOutputAtomic = multiplyAtomicAmount(
templeExpectedOutputAtomic,
ROUTING_FEE_SLIPPAGE_RATIO,
BigNumber.ROUND_DOWN
);

const swapToTempleTokenOpParams = await getSwapParams(
fromRoute3Token,
TEMPLE_TOKEN,
routingFeeFromInputAtomic,
templeOutputAtomic,
templeExpectedOutputAtomic,
ROUTING_FEE_SLIPPAGE_RATIO,
swapToTempleParams
);

allSwapParams.push(...swapToTempleTokenOpParams);

const routingFeeOpParams = await getRoutingFeeTransferParams(
TEMPLE_TOKEN,
templeOutputAtomic.times(ROUTING_FEE_RATIO - SWAP_CASHBACK_RATIO).dividedToIntegerBy(ROUTING_FEE_RATIO),
templeMinOutputAtomic.times(ROUTING_FEE_RATIO - SWAP_CASHBACK_RATIO).dividedToIntegerBy(ROUTING_FEE_RATIO),
publicKeyHash,
BURN_ADDREESS,
tezos
Expand All @@ -380,9 +394,7 @@ export const SwapForm: FC = () => {
} else if (!isInputTokenTempleToken && isSwapAmountMoreThreshold && isOutputTokenTempleToken) {
routingOutputFeeTransferParams = await getRoutingFeeTransferParams(
TEMPLE_TOKEN,
routingFeeFromOutputAtomic
.times(ROUTING_FEE_RATIO - SWAP_CASHBACK_RATIO)
.dividedToIntegerBy(ROUTING_FEE_RATIO),
outputFeeAtomicAmount.times(ROUTING_FEE_RATIO - SWAP_CASHBACK_RATIO).dividedToIntegerBy(ROUTING_FEE_RATIO),
publicKeyHash,
BURN_ADDREESS,
tezos
Expand All @@ -392,29 +404,33 @@ export const SwapForm: FC = () => {
fromSymbol: toRoute3Token.symbol,
toSymbol: TEMPLE_TOKEN.symbol,
toTokenDecimals: TEMPLE_TOKEN.decimals,
amount: atomsToTokens(routingFeeFromOutputAtomic, toRoute3Token.decimals).toFixed(),
dexesLimit: cashbackSwapMaxDexes,
amount: atomsToTokens(outputFeeAtomicAmount, toRoute3Token.decimals).toFixed(),
dexesLimit: CASHBACK_SWAP_MAX_DEXES,
rpcUrl: tezos.rpc.getRpcUrl()
});

const templeOutputAtomic = tokensToAtoms(
const templeExpectedOutputAtomic = tokensToAtoms(
new BigNumber(swapToTempleParams.output ?? ZERO),
TEMPLE_TOKEN.decimals
)
.multipliedBy(ROUTING_FEE_SLIPPAGE_RATIO)
.integerValue(BigNumber.ROUND_DOWN);
);
const templeMinOutputAtomic = multiplyAtomicAmount(
templeExpectedOutputAtomic,
ROUTING_FEE_SLIPPAGE_RATIO,
BigNumber.ROUND_DOWN
);

const swapToTempleTokenOpParams = await getSwapParams(
toRoute3Token,
TEMPLE_TOKEN,
routingFeeFromOutputAtomic,
templeOutputAtomic,
outputFeeAtomicAmount,
templeExpectedOutputAtomic,
ROUTING_FEE_SLIPPAGE_RATIO,
swapToTempleParams
);

const routingFeeOpParams = await getRoutingFeeTransferParams(
TEMPLE_TOKEN,
templeOutputAtomic.times(ROUTING_FEE_RATIO - SWAP_CASHBACK_RATIO).dividedToIntegerBy(ROUTING_FEE_RATIO),
templeMinOutputAtomic.times(ROUTING_FEE_RATIO - SWAP_CASHBACK_RATIO).dividedToIntegerBy(ROUTING_FEE_RATIO),
publicKeyHash,
BURN_ADDREESS,
tezos
Expand Down Expand Up @@ -605,7 +621,7 @@ export const SwapForm: FC = () => {
</td>
<td className="text-right text-gray-600">
<SwapMinimumReceived
minimumReceivedAmount={minimumReceivedAmountAtomic}
minimumReceivedAmount={minimumReceivedAtomic}
outputAssetMetadata={outputAssetMetadata}
/>
</td>
Expand Down
Loading