Skip to content

Commit

Permalink
Merge pull request #1285 from Kwenta/main
Browse files Browse the repository at this point in the history
Merge main into dev
  • Loading branch information
platschi authored Aug 17, 2022
2 parents 6fca38c + f5f16e0 commit 150de11
Show file tree
Hide file tree
Showing 14 changed files with 106 additions and 98 deletions.
3 changes: 2 additions & 1 deletion constants/queryKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,9 @@ export const QUERY_KEYS = {
quoteCurrencyKey: string | undefined,
baseCurrencyKey: string | undefined,
amount: string,
synthUsdRate: number,
networkId: NetworkId
) => ['convert', '1inch', quoteCurrencyKey, baseCurrencyKey, amount, networkId],
) => ['convert', '1inch', quoteCurrencyKey, baseCurrencyKey, amount, networkId, synthUsdRate],
quoteSynthSwap: (
quoteCurrencyKey: string | undefined,
baseCurrencyKey: string | undefined,
Expand Down
36 changes: 28 additions & 8 deletions containers/Convert/Convert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ const useConvert = () => {
quoteTokenAddress: string,
baseTokenAddress: string,
amount: string,
decimals: number,
slippage: number
) => {
const params = get1InchQuoteSwapParams(quoteTokenAddress, baseTokenAddress, amount);

const params = get1InchQuoteSwapParams(quoteTokenAddress, baseTokenAddress, amount, decimals);
const res = await axios.get<OneInchSwapResponse>(oneInchApiUrl + 'swap', {
params: {
fromTokenAddress: params.fromTokenAddress,
Expand Down Expand Up @@ -93,7 +93,6 @@ const useConvert = () => {
decimals?: number
) => {
const params = get1InchQuoteSwapParams(quoteTokenAddress, baseTokenAddress, amount, decimals);

const response = await axios.get<OneInchQuoteResponse>(oneInchApiUrl + 'quote', {
params: {
fromTokenAddress: params.fromTokenAddress,
Expand All @@ -102,7 +101,6 @@ const useConvert = () => {
disableEstimate: true,
},
});

return ethers.utils
.formatUnits(response.data.toTokenAmount, response.data.toToken.decimals)
.toString();
Expand All @@ -112,15 +110,17 @@ const useConvert = () => {
fromToken: Token,
toToken: Token,
fromAmount: string,
decimals: number,
slippage: number = 1
) => {
return swapSynthSwap(fromToken, toToken, fromAmount, slippage, 'estimate_gas');
return swapSynthSwap(fromToken, toToken, fromAmount, decimals, slippage, 'estimate_gas');
};

const swapSynthSwap = async (
fromToken: Token,
toToken: Token,
fromAmount: string,
decimals: number,
slippage: number = 1,
metaOnly?: 'meta_tx' | 'estimate_gas'
) => {
Expand Down Expand Up @@ -149,7 +149,13 @@ const useConvert = () => {
synthAmountEth = formatEther(usdValue);
}

const params = await get1InchSwapParams(oneInchFrom, oneInchTo, synthAmountEth, slippage);
const params = await get1InchSwapParams(
oneInchFrom,
oneInchTo,
synthAmountEth,
decimals,
slippage
);

const formattedData = getFormattedSwapData(params, SYNTH_SWAP_OPTIMISM_ADDRESS);

Expand Down Expand Up @@ -202,10 +208,17 @@ const useConvert = () => {
quoteTokenAddress: string,
baseTokenAddress: string,
amount: string,
decimals: number,
slippage: number = 1,
metaOnly = false
) => {
const params = await get1InchSwapParams(quoteTokenAddress, baseTokenAddress, amount, slippage);
const params = await get1InchSwapParams(
quoteTokenAddress,
baseTokenAddress,
amount,
decimals,
slippage
);

const { from, to, data, value } = params.tx;

Expand All @@ -229,9 +242,16 @@ const useConvert = () => {
quoteTokenAddress: string,
baseTokenAddress: string,
amount: string,
decimals: number,
slippage: number = 1
) => {
const params = await get1InchSwapParams(quoteTokenAddress, baseTokenAddress, amount, slippage);
const params = await get1InchSwapParams(
quoteTokenAddress,
baseTokenAddress,
amount,
decimals,
slippage
);

const { gas } = params.tx;

Expand Down
74 changes: 44 additions & 30 deletions hooks/useExchange.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import useSynthetixQueries from '@synthetixio/queries';
import Wei, { wei } from '@synthetixio/wei';
import { ethers } from 'ethers';
import { BigNumber, ethers } from 'ethers';
import produce from 'immer';
import get from 'lodash/get';
import { useRouter } from 'next/router';
Expand Down Expand Up @@ -59,12 +59,7 @@ import { newGetExchangeRatesForCurrencies } from 'utils/currencies';
import { truncateNumbers, zeroBN } from 'utils/formatters/number';
import { hexToAsciiV2 } from 'utils/formatters/string';
import logError from 'utils/logError';
import {
normalizeGasLimit,
newGetTransactionPrice,
getTransactionPrice,
GasInfo,
} from 'utils/network';
import { normalizeGasLimit, getTransactionPrice } from 'utils/network';

type ExchangeCardProps = {
footerCardAttached?: boolean;
Expand Down Expand Up @@ -112,6 +107,8 @@ const useExchange = ({

const [isApproving, setIsApproving] = useState(false);
const [isApproved, setIsApproved] = useState(false);
const [gasInfo, setGasInfo] = useState<{ limit: number; l1Fee: Wei } | null>();

const [baseCurrencyAmount, setBaseCurrencyAmount] = useRecoilState(baseCurrencyAmountState);
const [quoteCurrencyAmount, setQuoteCurrencyAmount] = useRecoilState(quoteCurrencyAmountState);
const [isSubmitting, setIsSubmitting] = useState(false);
Expand Down Expand Up @@ -181,6 +178,8 @@ const useExchange = ({
300
);

const quoteDecimals = get(allTokensMap, [quoteCurrencyKey!, 'decimals'], undefined);

const selectedTokens = tokenList.filter(
(t) => t.symbol === baseCurrencyKey || t.symbol === quoteCurrencyKey
);
Expand Down Expand Up @@ -238,7 +237,7 @@ const useExchange = ({
}
: null,
quoteCurrencyAmountDebounced,
get(allTokensMap, [quoteCurrencyKey!, 'decimals'], undefined)
quoteDecimals
);

const oneInchApproveAddressQuery = use1InchApproveSpenderQuery({
Expand Down Expand Up @@ -641,8 +640,6 @@ const useExchange = ({
// eslint-disable-next-line
}, [exchangeTxn.hash]);

const [gasInfo, setGasInfo] = useState<GasInfo | null>();

const oneInchSlippage = useMemo(() => {
// ETH swaps often fail with lower slippage
if (
Expand All @@ -655,18 +652,21 @@ const useExchange = ({
}, [txProvider, baseCurrencyKey, quoteCurrencyKey, slippage]);

const getGasEstimateForExchange = useCallback(async () => {
if (isL2) return null;
if (!isL2) return null;
if (txProvider === 'synthswap') {
const gasEstimate = await swapSynthSwapGasEstimate(
allTokensMap[quoteCurrencyKey!],
allTokensMap[baseCurrencyKey!],
quoteCurrencyAmount,
quoteDecimals,
slippage
);

const metaTx = await swapSynthSwap(
allTokensMap[quoteCurrencyKey!],
allTokensMap[baseCurrencyKey!],
quoteCurrencyAmount,
quoteDecimals,
slippage,
'meta_tx'
);
Expand All @@ -682,12 +682,15 @@ const useExchange = ({
quoteCurrencyTokenAddress!,
baseCurrencyTokenAddress!,
quoteCurrencyAmount,
quoteDecimals,
oneInchSlippage
);

const metaTx = await swap1Inch(
quoteCurrencyTokenAddress!,
baseCurrencyTokenAddress!,
quoteCurrencyAmount,
quoteDecimals,
oneInchSlippage,
true
);
Expand All @@ -703,33 +706,40 @@ const useExchange = ({
allTokensMap,
baseCurrencyKey,
baseCurrencyTokenAddress,
getL1SecurityFee,
isL2,
quoteCurrencyAmount,
quoteCurrencyKey,
quoteCurrencyTokenAddress,
slippage,
txProvider,
gasPrice?.gasPrice,
oneInchSlippage,
quoteDecimals,
swap1Inch,
swap1InchGasEstimate,
swapSynthSwap,
swapSynthSwapGasEstimate,
txProvider,
gasPrice?.gasPrice,
oneInchSlippage,
getL1SecurityFee,
]);

// An attempt to show correct gas fees while making as few calls as possible. (as soon as the submission is "valid", compute it once)
useEffect(() => {
const getGasLimitEstimate = async () => {
if (gasInfo == null && submissionDisabledReason == null) {
const gasEstimate = await getGasEstimateForExchange();
setGasInfo(gasEstimate);
if (submissionDisabledReason == null) {
try {
const gasEstimate = await getGasEstimateForExchange();
setGasInfo(gasEstimate);
} catch (err) {
logError(err);
}
} else {
setGasInfo(null);
}
};
getGasLimitEstimate();

// eslint-disable-next-line
}, [submissionDisabledReason, gasInfo, txProvider]);
}, [submissionDisabledReason, txProvider, quoteCurrencyAmount, gasPrice?.gasPrice]);

const redeemableDeprecatedSynthsQuery = useRedeemableDeprecatedSynthsQuery(walletAddress);
const redeemableDeprecatedSynths =
Expand Down Expand Up @@ -864,20 +874,20 @@ const useExchange = ({
if (txProvider === 'synthswap' || txProvider === '1inch') {
// TODO: We should refactor this to use Wei, instead of numbers.
return getTransactionPrice(
gasPrice?.gasPrice?.toNumber() ?? null,
gasInfo?.limit,
ethPriceRate.toNumber(),
gasInfo?.l1Fee
gasPrice,
BigNumber.from(gasInfo?.limit || 0),
ethPriceRate,
gasInfo?.l1Fee || zeroBN
);
} else {
return newGetTransactionPrice(
return getTransactionPrice(
gasPrice,
exchangeTxn.gasLimit,
ethPriceRate,
exchangeTxn.optimismLayerOneFee
);
}
}, [gasPrice, ethPriceRate, exchangeTxn, gasInfo, txProvider]);
}, [gasPrice, ethPriceRate, exchangeTxn, gasInfo?.limit, gasInfo?.l1Fee, txProvider]);

const handleApprove = async () => {
setTxError(null);
Expand Down Expand Up @@ -919,17 +929,20 @@ const useExchange = ({

if (txProvider === '1inch' && oneInchTokensMap != null) {
// @ts-ignore is correct tx type

tx = await swap1Inch(
quoteCurrencyTokenAddress!,
baseCurrencyTokenAddress!,
quoteCurrencyAmount,
quoteDecimals,
oneInchSlippage
);
} else if (txProvider === 'synthswap') {
tx = await swapSynthSwap(
allTokensMap[quoteCurrencyKey!],
allTokensMap[baseCurrencyKey!],
quoteCurrencyAmount,
quoteDecimals,
slippage
);
} else {
Expand Down Expand Up @@ -974,18 +987,19 @@ const useExchange = ({
quoteCurrencyAmount,
quoteCurrencyKey,
quoteCurrencyTokenAddress,
setHasOrdersNotification,
setOrders,
swap1Inch,
quoteDecimals,
txProvider,
slippage,
oneInchTokensMap,
allTokensMap,
swapSynthSwap,
setTxError,
exchangeTxn,
oneInchSlippage,
monitorExchangeTxn,
setHasOrdersNotification,
setOrders,
swap1Inch,
swapSynthSwap,
setTxError,
]);

useEffect(() => {
Expand Down
9 changes: 6 additions & 3 deletions hooks/useGetL1SecurityGasFee.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { getContractFactory, predeploys } from '@eth-optimism/contracts';
import Wei from '@synthetixio/wei';
import { BytesLike, ethers } from 'ethers';
import { omit } from 'lodash';
import { useRecoilValue } from 'recoil';

import Connector from 'containers/Connector';
import { isL2State } from 'store/wallet';
import { weiFromWei, zeroBN } from 'utils/formatters/number';

type MetaTx = {
data?: BytesLike | undefined;
Expand All @@ -26,8 +28,8 @@ export const useGetL1SecurityFee = () => {
const isL2 = useRecoilValue(isL2State);
const { signer } = Connector.useContainer();

return async (metaTx: MetaTx): Promise<number> => {
if (!isL2) return 0;
return async (metaTx: MetaTx): Promise<Wei> => {
if (!isL2) return zeroBN;

if (!signer) return Promise.reject('Wallet not connected');
const contract = new ethers.Contract(OVMGasPriceOracle.address, contractAbi, signer);
Expand All @@ -41,6 +43,7 @@ export const useGetL1SecurityFee = () => {
};
const serializedTx = ethers.utils.serializeTransaction(txParams);
const gasFee = await contract.functions.getL1Fee(serializedTx);
return Number(gasFee.toString());

return weiFromWei(gasFee.toString());
};
};
2 changes: 2 additions & 0 deletions queries/1inch/use1InchQuoteQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const use1InchQuoteQuery = (
quoteCurrency?.address,
baseCurrency?.address,
amount,
synthUsdRate || 0,
network?.id!
),
async () => {
Expand Down Expand Up @@ -75,6 +76,7 @@ const use1InchQuoteQuery = (
usdAmount.toString(),
decimals
);

return estimatedAmount;
} else {
const estimatedAmount = await quote1Inch(
Expand Down
Loading

0 comments on commit 150de11

Please sign in to comment.