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

Open
wants to merge 7 commits into
base: TW-1615-e-fix-failed-estimation-of-confirmation-for-in-wallet-swaps
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
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
92 changes: 55 additions & 37 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 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 Down Expand Up @@ -217,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 @@ -287,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 @@ -299,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 @@ -309,7 +320,8 @@ export const SwapForm: FC = () => {
fromRoute3Token,
toRoute3Token,
swapInputMinusFeeAtomic,
minimumReceivedAmountAtomic,
outputAtomicAmountBeforeFee,
slippageRatio,
swapParams.data
);

Expand Down Expand Up @@ -350,26 +362,30 @@ export const SwapForm: FC = () => {
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 @@ -378,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 @@ -390,29 +404,33 @@ export const SwapForm: FC = () => {
fromSymbol: toRoute3Token.symbol,
toSymbol: TEMPLE_TOKEN.symbol,
toTokenDecimals: TEMPLE_TOKEN.decimals,
amount: atomsToTokens(routingFeeFromOutputAtomic, toRoute3Token.decimals).toFixed(),
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 @@ -603,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
Loading