Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f989a4da8d | ||
|
|
df3119555f | ||
|
|
3a8b40d7a5 | ||
|
|
be38813a33 | ||
|
|
bf70dc33ec |
@@ -4,7 +4,7 @@ The front-end monorepo provides a toolkit for building apps that interact with V
|
||||
|
||||
This repository is managed using [Nx](https://nx.dev).
|
||||
|
||||
# 🔎 Applications in this repo
|
||||
## 🔎 Applications in this repo
|
||||
|
||||
### [Block explorer](./apps/explorer)
|
||||
|
||||
@@ -30,7 +30,7 @@ Hosting for static content being shared across apps, for example fonts.
|
||||
|
||||
The utility dApp for validators wishing to add or remove themselves as a signer of the multisig contract.
|
||||
|
||||
# 🧱 Libraries in this repo
|
||||
## 🧱 Libraries in this repo
|
||||
|
||||
### [UI toolkit](./libs/ui-toolkit)
|
||||
|
||||
@@ -53,7 +53,7 @@ A utility library for connecting to the Ethereum network and interacting with Ve
|
||||
|
||||
Generic react helpers that can be used across multiple applications, along with other utilities.
|
||||
|
||||
# 💻 Develop
|
||||
## 💻 Develop
|
||||
|
||||
### Set up
|
||||
|
||||
@@ -103,7 +103,7 @@ In CI linting, formatting and also run. These checks can be seen in the [CI work
|
||||
|
||||
Visit the [Nx Documentation](https://nx.dev/getting-started/intro) to learn more.
|
||||
|
||||
# 🐋 Hosting a console
|
||||
## 🐋 Hosting a console
|
||||
|
||||
To host a console there are two possible build scenarios for running the frontends: nx performed **outside** or **inside** docker build. For specific build instructions follow [build instructions](#build-instructions).
|
||||
|
||||
@@ -226,6 +226,6 @@ Note: The script is only needed if capsule was built for first time or fresh. To
|
||||
vega wallet service run -n DV --load-tokens --tokens-passphrase-file passphrase --no-version-check --automatic-consent --home ~/.vegacapsule/testnet/wallet
|
||||
```
|
||||
|
||||
# 📑 License
|
||||
## 📑 License
|
||||
|
||||
[MIT](./LICENSE)
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
useFundingRate,
|
||||
useMarketTradingMode,
|
||||
useExternalTwap,
|
||||
getQuoteName,
|
||||
} from '@vegaprotocol/markets';
|
||||
import { MarketState as State } from '@vegaprotocol/types';
|
||||
import { HeaderStat } from '../../components/header';
|
||||
@@ -41,6 +42,7 @@ export const MarketHeaderStats = ({ market }: MarketHeaderStatsProps) => {
|
||||
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
|
||||
|
||||
const asset = getAsset(market);
|
||||
const quoteUnit = getQuoteName(market);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -60,6 +62,8 @@ export const MarketHeaderStats = ({ market }: MarketHeaderStatsProps) => {
|
||||
<Last24hVolume
|
||||
marketId={market.id}
|
||||
positionDecimalPlaces={market.positionDecimalPlaces}
|
||||
marketDecimals={market.decimalPlaces}
|
||||
quoteUnit={quoteUnit}
|
||||
/>
|
||||
</HeaderStat>
|
||||
<HeaderStatMarketTradingMode
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
useDataGridEvents,
|
||||
} from '@vegaprotocol/datagrid';
|
||||
import type { MarketMaybeWithData } from '@vegaprotocol/markets';
|
||||
import { useColumnDefs } from './use-column-defs';
|
||||
import { useMarketsColumnDefs } from './use-column-defs';
|
||||
import type { DataGridStore } from '../../stores/datagrid-store-slice';
|
||||
import { type StateCreator, create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
@@ -50,7 +50,7 @@ export const useMarketsStore = create<DataGridSlice>()(
|
||||
);
|
||||
|
||||
export const MarketListTable = (props: Props) => {
|
||||
const columnDefs = useColumnDefs();
|
||||
const columnDefs = useMarketsColumnDefs();
|
||||
const gridStore = useMarketsStore((store) => store.gridStore);
|
||||
const updateGridStore = useMarketsStore((store) => store.updateGridStore);
|
||||
|
||||
|
||||
@@ -7,21 +7,31 @@ import type {
|
||||
} from '@vegaprotocol/datagrid';
|
||||
import { COL_DEFS, SetFilter } from '@vegaprotocol/datagrid';
|
||||
import * as Schema from '@vegaprotocol/types';
|
||||
import { addDecimalsFormatNumber, toBigNum } from '@vegaprotocol/utils';
|
||||
import {
|
||||
addDecimalsFormatNumber,
|
||||
formatNumber,
|
||||
toBigNum,
|
||||
} from '@vegaprotocol/utils';
|
||||
import { ButtonLink, Tooltip } from '@vegaprotocol/ui-toolkit';
|
||||
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
|
||||
import type {
|
||||
MarketFieldsFragment,
|
||||
MarketMaybeWithData,
|
||||
MarketMaybeWithDataAndCandles,
|
||||
} from '@vegaprotocol/markets';
|
||||
import { MarketActionsDropdown } from './market-table-actions';
|
||||
import { calcCandleVolume, getAsset } from '@vegaprotocol/markets';
|
||||
import {
|
||||
calcCandleVolume,
|
||||
calcCandleVolumePrice,
|
||||
getAsset,
|
||||
getQuoteName,
|
||||
} from '@vegaprotocol/markets';
|
||||
import { MarketCodeCell } from './market-code-cell';
|
||||
import { useT } from '../../lib/use-t';
|
||||
|
||||
const { MarketTradingMode, AuctionTrigger } = Schema;
|
||||
|
||||
export const useColumnDefs = () => {
|
||||
export const useMarketsColumnDefs = () => {
|
||||
const t = useT();
|
||||
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
|
||||
return useMemo<ColDef[]>(
|
||||
@@ -158,11 +168,25 @@ export const useColumnDefs = () => {
|
||||
}: ValueFormatterParams<MarketMaybeWithDataAndCandles, 'candles'>) => {
|
||||
const candles = data?.candles;
|
||||
const vol = candles ? calcCandleVolume(candles) : '0';
|
||||
const quoteName = getQuoteName(data as MarketFieldsFragment);
|
||||
const volPrice =
|
||||
candles &&
|
||||
calcCandleVolumePrice(
|
||||
candles,
|
||||
data.decimalPlaces,
|
||||
data.positionDecimalPlaces
|
||||
);
|
||||
|
||||
const volume =
|
||||
data && vol && vol !== '0'
|
||||
? addDecimalsFormatNumber(vol, data.positionDecimalPlaces)
|
||||
: '0.00';
|
||||
return volume;
|
||||
const volumePrice =
|
||||
volPrice && formatNumber(volPrice, data?.decimalPlaces);
|
||||
|
||||
return volumePrice
|
||||
? `${volume} (${volumePrice} ${quoteName})`
|
||||
: volume;
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { formatNumber } from '@vegaprotocol/utils';
|
||||
import { getNumberFormat } from '@vegaprotocol/utils';
|
||||
import sortBy from 'lodash/sortBy';
|
||||
import omit from 'lodash/omit';
|
||||
import { useReferralProgramQuery } from './__generated__/CurrentReferralProgram';
|
||||
@@ -107,7 +107,9 @@ export const useReferralProgram = () => {
|
||||
discountFactor: Number(t.referralDiscountFactor),
|
||||
discount: BigNumber(t.referralDiscountFactor).times(100).toFixed(2) + '%',
|
||||
minimumVolume: Number(t.minimumRunningNotionalTakerVolume),
|
||||
volume: formatNumber(t.minimumRunningNotionalTakerVolume, 0),
|
||||
volume: getNumberFormat(0).format(
|
||||
Number(t.minimumRunningNotionalTakerVolume)
|
||||
),
|
||||
epochs: Number(t.minimumEpochs),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -14,9 +14,9 @@ import {
|
||||
import { useVegaWallet } from '@vegaprotocol/wallet';
|
||||
import {
|
||||
addDecimalsFormatNumber,
|
||||
formatNumber,
|
||||
getDateFormat,
|
||||
getDateTimeFormat,
|
||||
getNumberFormat,
|
||||
getUserLocale,
|
||||
removePaginationWrapper,
|
||||
} from '@vegaprotocol/utils';
|
||||
@@ -323,7 +323,7 @@ export const Statistics = ({
|
||||
}
|
||||
description={<QUSDTooltip />}
|
||||
>
|
||||
{formatNumber(totalCommissionValue, 0)}
|
||||
{getNumberFormat(0).format(Number(totalCommissionValue))}
|
||||
</StatTile>
|
||||
);
|
||||
|
||||
@@ -563,8 +563,8 @@ export const RefereesTable = ({
|
||||
)
|
||||
.map((r) => ({
|
||||
...r,
|
||||
volume: formatNumber(r.volume, 0),
|
||||
commission: formatNumber(r.commission, 0),
|
||||
volume: getNumberFormat(0).format(r.volume),
|
||||
commission: getNumberFormat(0).format(r.commission),
|
||||
}))
|
||||
.reverse()}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Splash } from '@vegaprotocol/ui-toolkit';
|
||||
import { formatNumber } from '@vegaprotocol/utils';
|
||||
import { getNumberFormat } from '@vegaprotocol/utils';
|
||||
import { type useTeams } from '../../lib/hooks/use-teams';
|
||||
import { useT } from '../../lib/use-t';
|
||||
import { Table } from '../table';
|
||||
@@ -15,7 +15,8 @@ export const CompetitionsLeaderboard = ({
|
||||
}) => {
|
||||
const t = useT();
|
||||
|
||||
const num = (n?: number | string) => (!n ? '-' : formatNumber(n, 0));
|
||||
const num = (n?: number | string) =>
|
||||
!n ? '-' : getNumberFormat(0).format(Number(n));
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return <Splash>{t('Could not find any teams')}</Splash>;
|
||||
|
||||
@@ -81,6 +81,7 @@ export const Settings = () => {
|
||||
intent={Intent.Primary}
|
||||
onClick={() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
window.location.reload();
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -37,7 +37,7 @@ def test_market_lifecycle(proposed_market, vega: VegaServiceNull, page: Page):
|
||||
# 6002-MDET-004
|
||||
expect(page.get_by_test_id("market-change")).to_have_text("Change (24h)0.00%0.00")
|
||||
# 6002-MDET-005
|
||||
expect(page.get_by_test_id("market-volume")).to_have_text("Volume (24h)-")
|
||||
expect(page.get_by_test_id("market-volume")).to_have_text("Volume (24h)- (- BTC)")
|
||||
# 6002-MDET-008
|
||||
expect(page.get_by_test_id("market-settlement-asset")).to_have_text(
|
||||
"Settlement assettDAI"
|
||||
|
||||
@@ -94,7 +94,7 @@ export const LiquidityTable = ({
|
||||
return `${addDecimalsFormatNumberQuantum(
|
||||
value,
|
||||
assetDecimalPlaces ?? 0,
|
||||
quantum ?? 1
|
||||
quantum ?? 0
|
||||
)}`;
|
||||
};
|
||||
|
||||
@@ -165,7 +165,7 @@ export const LiquidityTable = ({
|
||||
return `${addDecimalsFormatNumberQuantum(
|
||||
newValue,
|
||||
assetDecimalPlaces ?? 0,
|
||||
quantum ?? 1
|
||||
quantum ?? 0
|
||||
)}`;
|
||||
};
|
||||
|
||||
@@ -227,7 +227,7 @@ export const LiquidityTable = ({
|
||||
addDecimalsFormatNumberQuantum(
|
||||
pendingCommitmentAmount,
|
||||
assetDecimalPlaces ?? 0,
|
||||
quantum ?? 1
|
||||
quantum ?? 0
|
||||
);
|
||||
|
||||
if (
|
||||
@@ -238,7 +238,7 @@ export const LiquidityTable = ({
|
||||
addDecimalsFormatNumberQuantum(
|
||||
currentCommitmentAmount,
|
||||
assetDecimalPlaces ?? 0,
|
||||
quantum ?? 1
|
||||
quantum ?? 0
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -286,7 +286,7 @@ export const LiquidityTable = ({
|
||||
addDecimalsFormatNumberQuantum(
|
||||
pendingCommitmentAmount,
|
||||
assetDecimalPlaces ?? 0,
|
||||
quantum ?? 1
|
||||
quantum ?? 0
|
||||
);
|
||||
|
||||
if (
|
||||
@@ -297,7 +297,7 @@ export const LiquidityTable = ({
|
||||
addDecimalsFormatNumberQuantum(
|
||||
currentCommitmentAmount,
|
||||
assetDecimalPlaces ?? 0,
|
||||
quantum ?? 1
|
||||
quantum ?? 0
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { DepthChart } from 'pennant';
|
||||
import throttle from 'lodash/throttle';
|
||||
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
|
||||
import { addDecimal, formatNumber } from '@vegaprotocol/utils';
|
||||
import { addDecimal, getNumberFormat } from '@vegaprotocol/utils';
|
||||
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
|
||||
import { useDataProvider } from '@vegaprotocol/data-provider';
|
||||
import { marketDepthProvider } from './market-depth-provider';
|
||||
@@ -216,12 +216,13 @@ export const DepthChartContainer = ({ marketId }: DepthChartManagerProps) => {
|
||||
|
||||
const volumeFormat = useCallback(
|
||||
(volume: number) =>
|
||||
formatNumber(volume, market?.positionDecimalPlaces || 0),
|
||||
getNumberFormat(market?.positionDecimalPlaces || 0).format(volume),
|
||||
[market?.positionDecimalPlaces]
|
||||
);
|
||||
|
||||
const priceFormat = useCallback(
|
||||
(price: number) => formatNumber(price, market?.decimalPlaces || 0),
|
||||
(price: number) =>
|
||||
getNumberFormat(market?.decimalPlaces || 0).format(price),
|
||||
[market?.decimalPlaces]
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { calcCandleVolume } from '../../market-utils';
|
||||
import { addDecimalsFormatNumber, isNumeric } from '@vegaprotocol/utils';
|
||||
import { calcCandleVolume, calcCandleVolumePrice } from '../../market-utils';
|
||||
import {
|
||||
addDecimalsFormatNumber,
|
||||
formatNumber,
|
||||
isNumeric,
|
||||
} from '@vegaprotocol/utils';
|
||||
import { Tooltip } from '@vegaprotocol/ui-toolkit';
|
||||
import { useCandles } from '../../hooks';
|
||||
import { useT } from '../../use-t';
|
||||
@@ -9,13 +13,17 @@ interface Props {
|
||||
positionDecimalPlaces?: number;
|
||||
formatDecimals?: number;
|
||||
initialValue?: string;
|
||||
marketDecimals?: number;
|
||||
quoteUnit?: string;
|
||||
}
|
||||
|
||||
export const Last24hVolume = ({
|
||||
marketId,
|
||||
marketDecimals,
|
||||
positionDecimalPlaces,
|
||||
formatDecimals,
|
||||
initialValue,
|
||||
quoteUnit,
|
||||
}: Props) => {
|
||||
const t = useT();
|
||||
const { oneDayCandles, fiveDaysCandles } = useCandles({
|
||||
@@ -28,6 +36,11 @@ export const Last24hVolume = ({
|
||||
(!oneDayCandles || oneDayCandles?.length === 0)
|
||||
) {
|
||||
const candleVolume = calcCandleVolume(fiveDaysCandles);
|
||||
const candleVolumePrice = calcCandleVolumePrice(
|
||||
fiveDaysCandles,
|
||||
marketDecimals,
|
||||
positionDecimalPlaces
|
||||
);
|
||||
const candleVolumeValue =
|
||||
candleVolume && isNumeric(positionDecimalPlaces)
|
||||
? addDecimalsFormatNumber(
|
||||
@@ -42,8 +55,8 @@ export const Last24hVolume = ({
|
||||
<div>
|
||||
<span className="flex flex-col">
|
||||
{t(
|
||||
'24 hour change is unavailable at this time. The volume change in the last 120 hours is {{candleVolumeValue}}',
|
||||
{ candleVolumeValue }
|
||||
'24 hour change is unavailable at this time. The volume change in the last 120 hours is {{candleVolumeValue}} ({{candleVolumePrice}} {{quoteUnit}})',
|
||||
{ candleVolumeValue, candleVolumePrice, quoteUnit }
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -57,10 +70,18 @@ export const Last24hVolume = ({
|
||||
? calcCandleVolume(oneDayCandles)
|
||||
: initialValue;
|
||||
|
||||
const candleVolumePrice = oneDayCandles
|
||||
? calcCandleVolumePrice(
|
||||
oneDayCandles,
|
||||
marketDecimals,
|
||||
positionDecimalPlaces
|
||||
)
|
||||
: initialValue;
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
description={t(
|
||||
'The total number of contracts traded in the last 24 hours.'
|
||||
'The total number of contracts traded in the last 24 hours. (Total value of contracts traded in the last 24 hours)'
|
||||
)}
|
||||
>
|
||||
<span>
|
||||
@@ -70,7 +91,12 @@ export const Last24hVolume = ({
|
||||
positionDecimalPlaces,
|
||||
formatDecimals
|
||||
)
|
||||
: '-'}
|
||||
: '-'}{' '}
|
||||
(
|
||||
{candleVolumePrice && isNumeric(positionDecimalPlaces)
|
||||
? formatNumber(candleVolumePrice, formatDecimals)
|
||||
: '-'}{' '}
|
||||
{quoteUnit})
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
@@ -155,6 +155,7 @@ export const MarketVolumeInfoPanel = ({ market }: MarketInfoProps) => {
|
||||
<Last24hVolume
|
||||
marketId={market.id}
|
||||
positionDecimalPlaces={market.positionDecimalPlaces}
|
||||
marketDecimals={market.decimalPlaces}
|
||||
/>
|
||||
),
|
||||
openInterest: dash(data?.openInterest),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Schema from '@vegaprotocol/types';
|
||||
import type { Market, MarketMaybeWithDataAndCandles } from './markets-provider';
|
||||
import {
|
||||
calcCandleVolumePrice,
|
||||
calcTradedFactor,
|
||||
filterAndSortMarkets,
|
||||
sumFeesFactors,
|
||||
@@ -145,3 +146,31 @@ describe('sumFeesFactors', () => {
|
||||
).toEqual(0.6);
|
||||
});
|
||||
});
|
||||
|
||||
describe('calcCandleVolumePrice', () => {
|
||||
it('calculates the volume price', () => {
|
||||
const candles = [
|
||||
{
|
||||
volume: '1000',
|
||||
high: '100',
|
||||
low: '10',
|
||||
open: '15',
|
||||
close: '90',
|
||||
periodStart: '2022-05-18T13:08:27.693537312Z',
|
||||
},
|
||||
{
|
||||
volume: '1000',
|
||||
high: '100',
|
||||
low: '10',
|
||||
open: '15',
|
||||
close: '90',
|
||||
periodStart: '2022-05-18T14:08:27.693537312Z',
|
||||
},
|
||||
];
|
||||
const marketDecimals = 3;
|
||||
const positionDecimalPlaces = 2;
|
||||
expect(
|
||||
calcCandleVolumePrice(candles, marketDecimals, positionDecimalPlaces)
|
||||
).toEqual('2');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { formatNumberPercentage, toBigNum } from '@vegaprotocol/utils';
|
||||
import {
|
||||
addDecimal,
|
||||
formatNumberPercentage,
|
||||
toBigNum,
|
||||
} from '@vegaprotocol/utils';
|
||||
import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import orderBy from 'lodash/orderBy';
|
||||
@@ -147,10 +151,51 @@ export const calcCandleHigh = (candles: Candle[]): string | undefined => {
|
||||
.toString();
|
||||
};
|
||||
|
||||
/**
|
||||
* The total number of contracts traded in the last 24 hours.
|
||||
*
|
||||
* @param candles
|
||||
* @returns the volume of a given set of candles
|
||||
*/
|
||||
export const calcCandleVolume = (candles: Candle[]): string | undefined =>
|
||||
candles &&
|
||||
candles.reduce((acc, c) => new BigNumber(acc).plus(c.volume).toString(), '0');
|
||||
|
||||
/**
|
||||
* The total number of contracts traded in the last 24 hours. (Total value of contracts traded in the last 24 hours)
|
||||
* The volume is calculated as the sum of the product of the volume and the high price of each candle.
|
||||
* The result is formatted using positionDecimalPlaces to account for the position size.
|
||||
* The result is formatted using marketDecimals to account for the market precision.
|
||||
*
|
||||
* @param candles
|
||||
* @param marketDecimals
|
||||
* @param positionDecimalPlaces
|
||||
* @returns the volume (in quote price) of a given set of candles
|
||||
*/
|
||||
export const calcCandleVolumePrice = (
|
||||
candles: Candle[],
|
||||
marketDecimals: number = 1,
|
||||
positionDecimalPlaces: number = 1
|
||||
): string | undefined =>
|
||||
candles &&
|
||||
candles.reduce(
|
||||
(acc, c) =>
|
||||
new BigNumber(acc)
|
||||
.plus(
|
||||
BigNumber(addDecimal(c.volume, positionDecimalPlaces)).times(
|
||||
addDecimal(c.high, marketDecimals)
|
||||
)
|
||||
)
|
||||
.toString(),
|
||||
'0'
|
||||
);
|
||||
|
||||
/**
|
||||
* Calculates the traded factor of a given market.
|
||||
*
|
||||
* @param m
|
||||
* @returns
|
||||
*/
|
||||
export const calcTradedFactor = (m: MarketMaybeWithDataAndCandles) => {
|
||||
const volume = Number(calcCandleVolume(m.candles || []) || 0);
|
||||
const price = m.data?.markPrice ? Number(m.data.markPrice) : 0;
|
||||
|
||||
@@ -23,7 +23,6 @@ describe('number utils', () => {
|
||||
{ v: new BigNumber(123000), d: 1, o: '12,300.0' },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01' },
|
||||
{ v: new BigNumber(123001000), d: 2, o: '1,230,010.00' },
|
||||
{ v: '100000000000000000001', d: 18, o: '100.000000000000000001' },
|
||||
])(
|
||||
'formats with addDecimalsFormatNumber given number correctly',
|
||||
({ v, d, o }) => {
|
||||
@@ -32,10 +31,27 @@ describe('number utils', () => {
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ v: '1234000000000000000', d: 18, q: '1000000000000000000', o: '1.23' }, //vega
|
||||
{ v: '1235000000000000000', d: 18, q: '1000000000000000000', o: '1.24' }, //vega
|
||||
{ v: '1230012', d: 6, q: '1000000', o: '1.23' }, // USDT
|
||||
{ v: '1234560000000000000', d: 18, q: '500000000000000', o: '1.2346' }, // WEth
|
||||
{ v: new BigNumber(123000), d: 5, o: '1.23', q: 0.1 },
|
||||
{ v: new BigNumber(123000), d: 3, o: '123.00', q: 0.1 },
|
||||
{ v: new BigNumber(123000), d: 1, o: '12,300.00', q: 0.1 },
|
||||
{ v: new BigNumber(123001000), d: 2, o: '1,230,010.00', q: 0.1 },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01', q: 100 },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01', q: 0.1 },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01', q: 1 },
|
||||
{
|
||||
v: BigNumber('123456789123456789'),
|
||||
d: 10,
|
||||
o: '12,345,678.91234568',
|
||||
q: '0.00003846',
|
||||
},
|
||||
{
|
||||
v: BigNumber('123456789123456789'),
|
||||
d: 10,
|
||||
o: '12,345,678.91234568',
|
||||
q: '1',
|
||||
},
|
||||
// USDT / USDC
|
||||
{ v: new BigNumber(12345678), d: 6, o: '12.35', q: 1000000 },
|
||||
])(
|
||||
'formats with addDecimalsFormatNumberQuantum given number correctly',
|
||||
({ v, d, o, q }) => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import isNil from 'lodash/isNil';
|
||||
import memoize from 'lodash/memoize';
|
||||
|
||||
import { getUserLocale } from '../get-user-locale';
|
||||
@@ -52,36 +53,36 @@ export function removeDecimal(
|
||||
return new BigNumber(value || 0).times(times).toFixed(0);
|
||||
}
|
||||
|
||||
export const getDecimalSeparator = memoize(
|
||||
() =>
|
||||
new Intl.NumberFormat(getUserLocale())
|
||||
.formatToParts(1.1)
|
||||
.find((part) => part.type === 'decimal')?.value ?? '.'
|
||||
);
|
||||
|
||||
export const getGroupFormat = memoize(() => {
|
||||
const parts = new Intl.NumberFormat(getUserLocale()).formatToParts(
|
||||
100000000000.1
|
||||
);
|
||||
const groupSeparator = parts.find((part) => part.type === 'group')?.value;
|
||||
const groupSize =
|
||||
(groupSeparator &&
|
||||
parts.reverse().find((part) => part.type === 'integer')?.value.length) ||
|
||||
0;
|
||||
return {
|
||||
groupSize,
|
||||
groupSeparator,
|
||||
};
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
|
||||
export const getNumberFormat = memoize((digits: number) => {
|
||||
if (isNil(digits) || digits < 0) {
|
||||
return new Intl.NumberFormat(getUserLocale());
|
||||
}
|
||||
return new Intl.NumberFormat(getUserLocale(), {
|
||||
minimumFractionDigits: Math.min(Math.max(0, digits), MIN_FRACTION_DIGITS),
|
||||
maximumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
|
||||
});
|
||||
});
|
||||
|
||||
const getFormat = memoize(() => ({
|
||||
decimalSeparator: getDecimalSeparator(),
|
||||
...getGroupFormat(),
|
||||
}));
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
|
||||
export const getFixedNumberFormat = memoize((digits: number) => {
|
||||
if (isNil(digits) || digits < 0) {
|
||||
return new Intl.NumberFormat(getUserLocale());
|
||||
}
|
||||
return new Intl.NumberFormat(getUserLocale(), {
|
||||
minimumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
|
||||
maximumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* formatNumber will format the number with maximum number of decimals
|
||||
* trailing zeros are removed but min(MIN_FRACTION_DIGITS, formatDecimals) decimal places will be kept
|
||||
export const getDecimalSeparator = memoize(
|
||||
() =>
|
||||
getNumberFormat(1)
|
||||
.formatToParts(1.1)
|
||||
.find((part) => part.type === 'decimal')?.value
|
||||
);
|
||||
|
||||
/** formatNumber will format the number with fixed decimals
|
||||
* @param rawValue - should be a number that is not outside the safe range fail as in https://mikemcl.github.io/bignumber.js/#toN
|
||||
* @param formatDecimals - number of decimals to use
|
||||
*/
|
||||
@@ -89,23 +90,7 @@ export const formatNumber = (
|
||||
rawValue: string | number | BigNumber,
|
||||
formatDecimals = 0
|
||||
) => {
|
||||
const decimalPlaces = Math.min(
|
||||
Math.max(0, formatDecimals),
|
||||
MAX_FRACTION_DIGITS
|
||||
);
|
||||
const format = getFormat();
|
||||
const formatted = new BigNumber(rawValue).toFormat(decimalPlaces, format);
|
||||
// if there are no decimal places just return formatted value
|
||||
if (!decimalPlaces) {
|
||||
return formatted;
|
||||
}
|
||||
// minimum number of decimal places to keep when removing trailing zeros
|
||||
const minimumFractionDigits = Math.min(decimalPlaces, MIN_FRACTION_DIGITS);
|
||||
const parts = formatted.split(format.decimalSeparator);
|
||||
parts[1] = (parts[1] || '')
|
||||
.replace(/0+$/, '')
|
||||
.padEnd(minimumFractionDigits, '0');
|
||||
return parts.join(format.decimalSeparator);
|
||||
return getNumberFormat(formatDecimals).format(Number(rawValue));
|
||||
};
|
||||
|
||||
/** formatNumberFixed will format the number with fixed decimals
|
||||
@@ -116,10 +101,7 @@ export const formatNumberFixed = (
|
||||
rawValue: string | number | BigNumber,
|
||||
formatDecimals = 0
|
||||
) => {
|
||||
return new BigNumber(rawValue).toFormat(
|
||||
Math.min(Math.max(0, formatDecimals), MAX_FRACTION_DIGITS),
|
||||
getFormat()
|
||||
);
|
||||
return getFixedNumberFormat(formatDecimals).format(Number(rawValue));
|
||||
};
|
||||
|
||||
export const quantumDecimalPlaces = (
|
||||
@@ -149,14 +131,9 @@ export const addDecimalsFormatNumberQuantum = (
|
||||
if (isNaN(Number(quantum))) {
|
||||
return addDecimalsFormatNumber(rawValue, decimalPlaces);
|
||||
}
|
||||
const numberDP = Math.ceil(
|
||||
Math.abs(Math.log10(toBigNum(quantum, decimalPlaces).toNumber()))
|
||||
);
|
||||
return addDecimalsFormatNumber(
|
||||
rawValue,
|
||||
decimalPlaces,
|
||||
Math.max(MIN_FRACTION_DIGITS, numberDP)
|
||||
);
|
||||
const quantumValue = addDecimal(quantum, decimalPlaces);
|
||||
const numberDP = Math.max(0, Math.log10(100 / Number(quantumValue)));
|
||||
return addDecimalsFormatNumber(rawValue, decimalPlaces, Math.ceil(numberDP));
|
||||
};
|
||||
|
||||
export const addDecimalsFormatNumber = (
|
||||
@@ -164,10 +141,9 @@ export const addDecimalsFormatNumber = (
|
||||
decimalPlaces: number,
|
||||
formatDecimals: number = decimalPlaces
|
||||
) => {
|
||||
return formatNumber(
|
||||
new BigNumber(rawValue || 0).dividedBy(Math.pow(10, decimalPlaces)),
|
||||
formatDecimals
|
||||
);
|
||||
const x = addDecimal(rawValue, decimalPlaces);
|
||||
|
||||
return formatNumber(x, formatDecimals);
|
||||
};
|
||||
|
||||
export const addDecimalsFixedFormatNumber = (
|
||||
|
||||
@@ -10,24 +10,24 @@ describe('formatValue', () => {
|
||||
{
|
||||
v: '123456789123456789',
|
||||
d: 10,
|
||||
o: '12,345,678.9123456789',
|
||||
o: '12,345,678.91234568',
|
||||
},
|
||||
])('formats values correctly', ({ v, d, o }) => {
|
||||
expect(formatValue(v, d)).toStrictEqual(o);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ v: 123000, d: 5, o: '1.23', q: '1' },
|
||||
{ v: 123000, d: 3, o: '123.00', q: '1' },
|
||||
{ v: 123000, d: 1, o: '12,300.00', q: '1' },
|
||||
{ v: 123001000, d: 2, o: '1,230,010.00', q: '1' },
|
||||
{ v: 123000, d: 5, o: '1.23', q: '0.1' },
|
||||
{ v: 123000, d: 3, o: '123.00', q: '0.1' },
|
||||
{ v: 123000, d: 1, o: '12,300.00', q: '0.1' },
|
||||
{ v: 123001000, d: 2, o: '1,230,010.00', q: '0.1' },
|
||||
{ v: 123001, d: 2, o: '1,230.01', q: '100' },
|
||||
{ v: 123001, d: 2, o: '1,230.01', q: '1' },
|
||||
{ v: 123001, d: 2, o: '1,230.01', q: '0.1' },
|
||||
{
|
||||
v: '123456789123456789',
|
||||
d: 10,
|
||||
o: '12,345,678.91235',
|
||||
q: '384600',
|
||||
o: '12,345,678.91234568',
|
||||
q: '0.00003846',
|
||||
},
|
||||
])(
|
||||
'formats with formatValue with quantum given number correctly',
|
||||
@@ -42,15 +42,15 @@ describe('formatRange', () => {
|
||||
min: 123000,
|
||||
max: 12300011111,
|
||||
d: 5,
|
||||
o: '1.23 - 123,000.11',
|
||||
q: '1000',
|
||||
o: '1.23 - 123,000.11111',
|
||||
q: '0.1',
|
||||
},
|
||||
{
|
||||
min: 123000,
|
||||
max: 12300011111,
|
||||
d: 3,
|
||||
o: '123.00 - 12,300,011.11',
|
||||
q: '100',
|
||||
o: '123.00 - 12,300,011.111',
|
||||
q: '0.1',
|
||||
},
|
||||
{
|
||||
min: 123000,
|
||||
|
||||
Reference in New Issue
Block a user