Skip to content

Commit

Permalink
feat: add get price by usdt (#489)
Browse files Browse the repository at this point in the history
* feat: add get price by usdt
  • Loading branch information
quangdz1704 authored Dec 11, 2023
1 parent a59a926 commit 78ee886
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 21 deletions.
17 changes: 8 additions & 9 deletions src/pages/UniversalSwap/SwapV3/InputSwapV3.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import styles from './InputSwap.module.scss';
import { CoinIcon, TokenItemType } from '@oraichain/oraidex-common';
import ArrowImg from 'assets/icons/arrow_new.svg';
import cn from 'classnames/bind';
import NumberFormat from 'react-number-format';
import TokenBalance from 'components/TokenBalance';
import ArrowImg from 'assets/icons/arrow_new.svg';
import { CoinGeckoPrices } from 'hooks/useCoingecko';
import NumberFormat from 'react-number-format';
import { TokenInfo } from 'types/token';
import { CoinGeckoId, CoinIcon, TokenItemType } from '@oraichain/oraidex-common';
import styles from './InputSwap.module.scss';

const cx = cn.bind(styles);

Expand All @@ -14,13 +13,13 @@ interface InputSwapProps {
setIsSelectFrom: (value: boolean) => void;
token: TokenItemType;
amount: number;
prices?: CoinGeckoPrices<CoinGeckoId>;
tokenFee: number;
onChangeAmount?: (amount: number | undefined) => void;
balance: string | bigint;
disable?: boolean;
originalToken?: TokenInfo;
setCoe?: React.Dispatch<React.SetStateAction<number>>;
usdPrice: string;
}

export default function InputSwapV3({
Expand All @@ -32,9 +31,9 @@ export default function InputSwapV3({
tokenFee,
balance,
disable,
prices,
originalToken,
setCoe
setCoe,
usdPrice
}: InputSwapProps) {
return (
<>
Expand All @@ -50,7 +49,7 @@ export default function InputSwapV3({
decimalScale={6}
/>
</div>
<div>≈ ${!amount ? 0 : (prices?.[originalToken?.coinGeckoId] * amount).toFixed(6)}</div>
<div>≈ ${amount ? usdPrice : 0}</div>
</div>
<div className={cx('input-swap-box')}>
<div className={cx('box-select')} onClick={() => setIsSelectFrom(true)}>
Expand Down
35 changes: 35 additions & 0 deletions src/pages/UniversalSwap/SwapV3/hooks/useGetPriceByUSD.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { CoinGeckoPrices } from 'hooks/useCoingecko';
import { CoinGeckoId } from '@oraichain/oraidex-common/build/network';
import { useQuery } from '@tanstack/react-query';
import axios from 'rest/request';

export type GetPriceHookParam = { denom?: string; contractAddress?: string; cachePrices: CoinGeckoPrices<CoinGeckoId> };

export const getPriceByUSDT = async (queries: { denom?: string; contractAddress?: string }): Promise<number> => {
try {
const res = await axios.get('/price-by-usdt/', { params: queries });
return res.data.price;
} catch (e) {
console.error('getPools', e);
return 0;
}
};

export const getPriceTokenInUSD = async ({
denom,
contractAddress,
cachePrices
}: GetPriceHookParam): Promise<number> => {
const priceByUsdt = await getPriceByUSDT({ denom, contractAddress });
return cachePrices['tether'] * priceByUsdt;
};

export const useGetPriceByUSD = ({ denom, contractAddress, cachePrices }: GetPriceHookParam) => {
const { data: price, refetch: refetchPrice } = useQuery(
['useGetPriceByUSDT', denom, contractAddress],
() => getPriceTokenInUSD({ denom, contractAddress, cachePrices }),
{ enabled: !!denom || !!contractAddress, refetchOnWindowFocus: true }
);

return { price, refetchPrice };
};
37 changes: 25 additions & 12 deletions src/pages/UniversalSwap/SwapV3/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import useTokenFee from 'hooks/useTokenFee';
import Metamask from 'libs/metamask';
import { getUsd, toSubAmount } from 'libs/utils';
import { calcMaxAmount } from 'pages/Balance/helpers';
import { numberWithCommas } from 'pages/Pools/helpers';
import { generateNewSymbol } from 'pages/UniversalSwap/helpers';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
Expand All @@ -59,9 +60,9 @@ import {
} from '../helpers';
import InputSwap from './InputSwapV3';
import { useGetTransHistory, useSimulate, useTaxRate } from './hooks';
import { useGetPriceByUSD } from './hooks/useGetPriceByUSD';
import { useRelayerFee } from './hooks/useRelayerFee';
import styles from './index.module.scss';
import { numberWithCommas } from 'pages/Pools/helpers';

const cx = cn.bind(styles);
const RELAYER_DECIMAL = 6; // TODO: hardcode decimal relayerFee
Expand Down Expand Up @@ -213,6 +214,13 @@ const SwapComponent: React.FC<{
INIT_AMOUNT
);

const { price } = useGetPriceByUSD({
denom: originalFromToken.denom,
contractAddress: originalFromToken.contractAddress,
cachePrices: prices
});
const usdPriceShow = ((price || prices?.[originalFromToken?.coinGeckoId]) * fromAmountToken).toFixed(6);

const relayerFee = useRelayerFee();
const relayerFeeToken = relayerFee.reduce((acc, cur) => {
if (
Expand All @@ -235,12 +243,12 @@ const SwapComponent: React.FC<{
const minimumReceive =
averageRatio && averageRatio.amount
? calculateMinReceive(
// @ts-ignore
Math.trunc(new BigDecimal(averageRatio.amount) / INIT_AMOUNT).toString(),
fromAmountTokenBalance.toString(),
userSlippage,
originalFromToken.decimals
)
// @ts-ignore
Math.trunc(new BigDecimal(averageRatio.amount) / INIT_AMOUNT).toString(),
fromAmountTokenBalance.toString(),
userSlippage,
originalFromToken.decimals
)
: '0';
const isWarningSlippage = +minimumReceive > +simulateData?.amount;

Expand Down Expand Up @@ -350,14 +358,14 @@ const SwapComponent: React.FC<{
<InputSwap
balance={fromTokenBalance}
originalToken={originalFromToken}
prices={prices}
Icon={FromIcon}
setIsSelectFrom={setIsSelectFrom}
token={originalFromToken}
amount={fromAmountToken}
onChangeAmount={onChangeFromAmount}
tokenFee={fromTokenFee}
setCoe={setCoe}
usdPrice={usdPriceShow}
/>
{isSelectFrom && (
<SelectTokenModalV2
Expand Down Expand Up @@ -433,12 +441,12 @@ const SwapComponent: React.FC<{
balance={toTokenBalance}
originalToken={originalToToken}
disable={true}
prices={prices}
Icon={ToIcon}
setIsSelectFrom={setIsSelectTo}
token={originalToToken}
amount={toAmountToken}
tokenFee={toTokenFee}
usdPrice={usdPriceShow}
/>
{isSelectTo && (
<SelectTokenModalV2
Expand All @@ -455,8 +463,9 @@ const SwapComponent: React.FC<{
)}

<div className={cx('ratio')}>
{`1 ${originalFromToken.name}${averageRatio ? (averageRatio.displayAmount / INIT_AMOUNT).toFixed(6) : '0'
} ${originalToToken.name}`}
{`1 ${originalFromToken.name}${
averageRatio ? (averageRatio.displayAmount / INIT_AMOUNT).toFixed(6) : '0'
} ${originalToToken.name}`}
</div>
</div>
</div>
Expand Down Expand Up @@ -496,7 +505,11 @@ const SwapComponent: React.FC<{
<span> Expected Output</span>
</div>
<div className={cx('value')}>
{simulateData?.displayAmount ? numberWithCommas(simulateData?.displayAmount, undefined, { minimumFractionDigits: 6 }) : "0"} {originalToToken.name}
{' '}
{simulateData?.displayAmount
? numberWithCommas(simulateData?.displayAmount, undefined, { minimumFractionDigits: 6 })
: '0'}{' '}
{originalToToken.name}
</div>
</div>
}
Expand Down

0 comments on commit 78ee886

Please sign in to comment.