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 2 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
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
58 changes: 46 additions & 12 deletions src/lib/apis/route3/fetch-route3-swap-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ import {
Route3LbSwapParamsRequest,
Route3LiquidityBakingParamsResponse,
Route3SwapParamsRequest,
Route3TraditionalSwapParamsResponse
Route3TraditionalSwapParamsResponse,
Route3TreeNode,
Route3TreeNodeType
} from 'lib/route3/interfaces';
import { ONE_MINUTE_S } from 'lib/utils/numbers';

import { ROUTE3_BASE_URL } from './route3.api';

const parser = (origJSON: string): ReturnType<typeof JSON['parse']> => {
const stringedJSON = origJSON
.replace(/input":\s*([-+Ee0-9.]+)/g, 'input":"$1"')
.replace(/output":\s*([-+Ee0-9.]+)/g, 'output":"$1"');
const stringedJSON = origJSON.replace(/(input|output|tokenInAmount|tokenOutAmount)":\s*([-+Ee0-9.]+)/g, '$1":"$2"');

return JSON.parse(stringedJSON);
};
Expand Down Expand Up @@ -71,6 +71,34 @@ const getLbSubsidyCausedXtzDeviation = memoizee(
{ promise: true, maxAge: 1000 * ONE_MINUTE_S * 5 }
);

const correctFinalOutput = <T extends Route3TreeNode>(tree: T, multiplier: BigNumber, decimals: number): T => {
const correctedTokenOutAmount = new BigNumber(tree.tokenOutAmount)
.times(multiplier)
.decimalPlaces(decimals, BigNumber.ROUND_FLOOR)
.toFixed();

switch (tree.type) {
case Route3TreeNodeType.Empty:
case Route3TreeNodeType.Dex:
return { ...tree, tokenOutAmount: correctedTokenOutAmount };
case Route3TreeNodeType.High:
return {
...tree,
tokenOutAmount: correctedTokenOutAmount,
// TODO: Fix output value for the last item; the sum of outputs for all subitems should be equal to the output of the parent item
items: tree.items.map(item => correctFinalOutput(item, multiplier, decimals))
};
default:
return {
...tree,
tokenOutAmount: correctedTokenOutAmount,
items: tree.items.map((item, index, subitems) =>
index === subitems.length - 1 ? correctFinalOutput(item, multiplier, decimals) : item
)
};
}
};

const fetchRoute3LiquidityBakingParams = (
params: Route3LbSwapParamsRequest
): Promise<Route3LiquidityBakingParamsResponse> =>
Expand Down Expand Up @@ -98,29 +126,34 @@ const fetchRoute3LiquidityBakingParams = (
const initialXtzInput = new BigNumber(originalParams.xtzHops[0].tokenInAmount);
const correctedXtzInput = initialXtzInput.times(1 - lbSubsidyCausedXtzDeviation).integerValue();
const initialOutput = new BigNumber(originalParams.output);
const multiplier = new BigNumber(correctedXtzInput).div(initialXtzInput);
// The difference between inputs is usually pretty small, so we can use the following formula
const correctedOutput = initialOutput
.times(correctedXtzInput)
.div(initialXtzInput)
.decimalPlaces(toTokenDecimals, BigNumber.ROUND_FLOOR);
const correctedOutput = initialOutput.times(multiplier).decimalPlaces(toTokenDecimals, BigNumber.ROUND_FLOOR);
const correctedXtzTree = correctFinalOutput(originalParams.xtzTree, multiplier, toTokenDecimals);

return {
...originalParams,
output: correctedOutput.toString(),
output: correctedOutput.toFixed(),
xtzHops: [
{
...originalParams.xtzHops[0],
tokenInAmount: correctedXtzInput.toFixed()
}
].concat(originalParams.xtzHops.slice(1))
].concat(originalParams.xtzHops.slice(1)),
xtzTree: correctedXtzTree
};
} catch (err) {
console.error(err);
return originalParams;
}
});

export const fetchRoute3SwapParams = ({ fromSymbol, toSymbol, dexesLimit, ...restParams }: Route3SwapParamsRequest) => {
export const fetchRoute3SwapParams = ({
fromSymbol,
toSymbol,
dexesLimit,
...restParams
}: Omit<Route3SwapParamsRequest, 'showTree'>) => {
const isLbUnderlyingTokenSwap = intersection([fromSymbol, toSymbol], ['TZBTC', 'XTZ']).length > 0;

return [fromSymbol, toSymbol].includes(THREE_ROUTE_SIRS_TOKEN.symbol)
Expand All @@ -130,7 +163,8 @@ export const fetchRoute3SwapParams = ({ fromSymbol, toSymbol, dexesLimit, ...res
// XTZ <-> SIRS and TZBTC <-> SIRS swaps have either XTZ or TZBTC hops, so a total number of hops cannot exceed the limit
xtzDexesLimit: isLbUnderlyingTokenSwap ? dexesLimit : Math.ceil(dexesLimit / 2),
tzbtcDexesLimit: isLbUnderlyingTokenSwap ? dexesLimit : Math.floor(dexesLimit / 2),
showTree: true,
...restParams
})
: fetchRoute3TraditionalSwapParams({ fromSymbol, toSymbol, dexesLimit, ...restParams });
: fetchRoute3TraditionalSwapParams({ fromSymbol, toSymbol, dexesLimit, showTree: true, ...restParams });
};
9 changes: 9 additions & 0 deletions src/lib/assets/three-route-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,12 @@ export const THREE_ROUTE_TEZ_TOKEN: Route3Token = {
tokenId: null,
decimals: 6
};

export const THREE_ROUTE_TZBTC_TOKEN: Route3Token = {
id: 2,
symbol: 'TZBTC',
standard: Route3TokenStandardEnum.fa12,
contract: 'KT1PWx2mnDueood7fEmfbBDKx1D9BAnnXitn',
tokenId: null,
decimals: 8
};
Loading
Loading