Compare commits

...
48 changed files with 635 additions and 411 deletions
+2 -2
View File
@@ -23,7 +23,7 @@ NX_TENDERMINT_URL=https://tm.n01.stagnet1.vega.rocks
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n01.stagnet1.vega.xyz/websocket
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
#Test configuration variables
CYPRESS_FAIRGROUND=false
@@ -31,4 +31,4 @@ LC_ALL="en_US.UTF-8"
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=true
NX_METAMASK_SNAPS=true
NX_METAMASK_SNAPS=true
+2 -2
View File
@@ -20,7 +20,7 @@ NX_TRANCHES_SERVICE_URL=https://tranches-stagnet1-k8s.ops.vega.xyz
NX_VEGA_REST_URL=http://localhost:3008/api/v2/
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
NX_TENDERMINT_URL=http://localhost:26617
NX_TENDERMINT_WEBSOCKET_URL=wss://localhost:26617/websocket
@@ -30,4 +30,4 @@ CYPRESS_FAIRGROUND=false
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=false
NX_METAMASK_SNAPS=false
NX_METAMASK_SNAPS=false
+2 -2
View File
@@ -15,11 +15,11 @@ NX_VEGA_REST_URL=https://api.n00.devnet1.vega.xyz/api/v2/
NX_SENTRY_DSN=https://4b8c8a8ba07742648aa4dfe1b8d17e40@o286262.ingest.sentry.io/5882996
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
NX_TENDERMINT_URL=https://tm.be.devnet1.vega.xyz/
NX_TENDERMINT_WEBSOCKET_URL=wss://be.devnet1.vega.xyz/websocket
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=true
NX_METAMASK_SNAPS=true
NX_METAMASK_SNAPS=true
+1 -1
View File
@@ -15,7 +15,7 @@ NX_TRANCHES_SERVICE_URL=https://tranches-mainnet-k8s.ops.vega.xyz
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/mainnet/announcements.json
NX_VEGA_REST_URL=https://api.vega.community/api/v2/
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-mainnet
NX_TENDERMINT_URL=https://be.vega.community
NX_TENDERMINT_WEBSOCKET_URL=wss://be.vega.community/websocket
+1 -1
View File
@@ -14,7 +14,7 @@ NX_TRANCHES_SERVICE_URL=https://tranches-mainnet-mirror-k8s.ops.vega.xyz
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/mainnet/announcements.json
NX_VEGA_REST_URL=https://api.mainnet-mirror.vega.rocks/api/v2/
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-mainnet
NX_TENDERMINT_URL=https://be.mainnet-mirror.vega.rocks
NX_TENDERMINT_WEBSOCKET_URL=wss://be.mainnet-mirror.vega.rocks/websocket
+1 -1
View File
@@ -11,7 +11,7 @@ NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/annou
NX_VEGA_REST_URL=https://api.n00.stagnet1.vega.xyz/api/v2/
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
NX_TENDERMINT_URL=https://tm.n01.stagnet1.vega.rocks
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n01.stagnet1.vega.xyz/websocket
+1 -1
View File
@@ -16,7 +16,7 @@ NX_VEGA_REST_URL=https://api.n07.testnet.vega.xyz/api/v2/
NX_SENTRY_DSN=https://4b8c8a8ba07742648aa4dfe1b8d17e40@o286262.ingest.sentry.io/5882996
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
NX_TENDERMINT_URL=https://tm.be.testnet.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.testnet.vega.xyz/websocket
+1 -1
View File
@@ -13,7 +13,7 @@ NX_VEGA_REST_URL=https://api-validators-testnet.vega.rocks/api/v2/
NX_SENTRY_DSN=https://4b8c8a8ba07742648aa4dfe1b8d17e40@o286262.ingest.sentry.io/5882996
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
NX_TENDERMINT_URL=https://tm.be.validators-testnet.vega.rocks
NX_TENDERMINT_WEBSOCKET_URL=wss://be.validators-testnet.vega.
@@ -54,7 +54,7 @@ export const WalletCardRow = ({
}) => {
const ref = React.useRef<HTMLDivElement | null>(null);
useAnimateValue(ref, value);
const [integers, decimalsPlaces] = useNumberParts(value, decimals);
const [integers, decimalsPlaces, separator] = useNumberParts(value, decimals);
return (
<div
@@ -75,7 +75,10 @@ export const WalletCardRow = ({
className="font-mono flex-1 text-right"
data-testid="associated-amount"
>
<span>{integers}.</span>
<span>
{integers}
{separator}
</span>
<span>{decimalsPlaces}</span>
</span>
)}
@@ -110,7 +113,10 @@ export const WalletCardAsset = ({
border,
subheading,
}: WalletCardAssetProps) => {
const [integers, decimalsPlaces] = useNumberParts(balance, decimals);
const [integers, decimalsPlaces, separator] = useNumberParts(
balance,
decimals
);
return (
<div className="flex flex-nowrap mt-2 mb-4">
@@ -132,7 +138,10 @@ export const WalletCardAsset = ({
</div>
</div>
<div className="px-2 basis-full font-mono" data-testid="currency-value">
<span>{integers}.</span>
<span>
{integers}
{separator}
</span>
<span className="text-neutral-400">{decimalsPlaces}</span>
</div>
</div>
@@ -133,11 +133,7 @@ describe('market info is displayed', { tags: '@smoke' }, () => {
validateMarketDataRow(4, 'Decimals', '5');
validateMarketDataRow(5, 'Quantum', '1');
validateMarketDataRow(6, 'Status', 'Enabled');
validateMarketDataRow(
7,
'Contract address',
'0x0158031158Bb4dF2AD02eAA31e8963E84EA978a4'
);
validateMarketDataRow(7, 'Contract address', '0x0158…78a4');
validateMarketDataRow(8, 'Withdrawal threshold', '0.0005');
validateMarketDataRow(9, 'Lifetime limit', '1,230');
validateMarketDataRow(10, 'Infrastructure fee account balance', '0.00001');
@@ -6,7 +6,7 @@ const askVolume = 'ask-vol-9894185';
const bidVolume = 'bid-vol-9889001';
const askCumulative = 'cumulative-vol-9894185';
const bidCumulative = 'cumulative-vol-9889001';
const midPrice = 'middle-mark-price-4612690000';
const midPrice = 'last-traded-4612690000';
const priceResolution = 'resolution';
const dealTicketPrice = 'order-price';
const dealTicketSize = 'order-size';
@@ -43,11 +43,10 @@ describe('ethereum wallet', { tags: '@smoke', testIsolation: true }, () => {
// 0004-EWAL-005
// 0004-EWAL-006
const ethWalletAddress = Cypress.env('ETHEREUM_WALLET_ADDRESS');
cy.getByTestId('Deposits').click();
cy.getByTestId('deposit-button').click();
connectEthereumWallet('MetaMask');
cy.getByTestId('ethereum-address').should('have.text', ethWalletAddress);
cy.getByTestId('ethereum-address').should('have.text', '0xEe7D…d94F');
cy.getByTestId('disconnect-ethereum-wallet')
.should('have.text', 'Disconnect')
.click();
+1 -1
View File
@@ -13,7 +13,7 @@ NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega/releases
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/main/announcements.json
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
# Cosmic elevator flags
+1 -1
View File
@@ -13,7 +13,7 @@ NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega/releases
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/test/announcements.json
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
NX_ETH_LOCAL_PROVIDER_URL=http://localhost:8545/
NX_ETH_WALLET_MNEMONIC="ozone access unlock valid olympic save include omit supply green clown session"
+1 -1
View File
@@ -14,7 +14,7 @@ NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega-dev-releases/releases
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/fairground/announcements.json
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=true
+1 -1
View File
@@ -14,7 +14,7 @@ NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/annou
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_VEGA_CONSOLE_URL=https://console.vega.xyz
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-mainnet/codfcglpplgmmlokgilfkpcjnmkbfiel
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet-mainnet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-mainnet
# TAG name of the current app version - TODO: bump to the latest upon release
NX_APP_VERSION=v0.20.21-core-0.71.6
+1 -1
View File
@@ -14,7 +14,7 @@ NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/annou
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_VEGA_CONSOLE_URL=https://console.mainnet-mirror.vega.rocks
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-mainnet/codfcglpplgmmlokgilfkpcjnmkbfiel
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet-mainnet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-mainnet
# TAG name of the current app version - TODO: bump to the latest upon release
NX_APP_VERSION=v0.20.19-core-0.71.6
+1 -1
View File
@@ -14,7 +14,7 @@ NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega/releases
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/fairground/announcements.json
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=true
+1 -1
View File
@@ -15,7 +15,7 @@ NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/annou
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_VEGA_CONSOLE_URL=https://console.fairground.wtf
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=true
+1 -1
View File
@@ -16,7 +16,7 @@ NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_VEGA_CONSOLE_URL=https://trading.validators-testnet.vega.rocks
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/pl/firefox/addon/vega-wallet
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=false
@@ -69,6 +69,7 @@ describe('MarketSelectorItem', () => {
targetStake: '1000000',
trigger: AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
priceMonitoringBounds: null,
lastTradedPrice: '100',
};
const candles = [
+1 -1
View File
@@ -97,7 +97,7 @@ export const AssetDetailsDialog = ({
}}
>
{content}
<p className="text-sm my-4">
<p className="text-xs my-4">
{t(
'There is 1 unit of the settlement asset (%s) to every 1 quote unit.',
[assetSymbol]
+9 -3
View File
@@ -3,7 +3,11 @@ import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import type * as Schema from '@vegaprotocol/types';
import type { KeyValueTableRowProps } from '@vegaprotocol/ui-toolkit';
import { CopyWithTooltip, Icon } from '@vegaprotocol/ui-toolkit';
import {
CopyWithTooltip,
Icon,
truncateMiddle,
} from '@vegaprotocol/ui-toolkit';
import {
KeyValueTable,
KeyValueTableRow,
@@ -56,7 +60,7 @@ export const rows: Rows = [
key: AssetDetail.ID,
label: t('ID'),
tooltip: '',
value: (asset) => asset.id,
value: (asset) => truncateMiddle(asset.id),
},
{
key: AssetDetail.TYPE,
@@ -109,7 +113,9 @@ export const rows: Rows = [
return (
<>
<EtherscanLink address={asset.source.contractAddress} />{' '}
<EtherscanLink address={asset.source.contractAddress}>
{truncateMiddle(asset.source.contractAddress)}
</EtherscanLink>{' '}
<CopyWithTooltip text={asset.source.contractAddress}>
<button title={t('Copy address to clipboard')}>
<Icon size={3} name="duplicate" />
+2 -2
View File
@@ -1,4 +1,4 @@
import { TradingOption } from '@vegaprotocol/ui-toolkit';
import { TradingOption, truncateMiddle } from '@vegaprotocol/ui-toolkit';
import type { AssetFieldsFragment } from './__generated__/Asset';
import classNames from 'classnames';
import { t } from '@vegaprotocol/i18n';
@@ -45,7 +45,7 @@ export const AssetOption = ({ asset, balance }: AssetOptionProps) => {
{balance}
<div className="text-[12px] font-mono w-full text-left break-all">
<span className="text-vega-light-300 dark:text-vega-dark-300">
{asset.id}
{truncateMiddle(asset.id)}
</span>
</div>
</div>
@@ -432,9 +432,9 @@ describe('StopOrder', () => {
});
it('sets expiry time/date to now if expiry is changed to checked', async () => {
const now = Math.round(Date.now() / 1000) * 1000;
const now = 24 * 60 * 60 * 1000;
render(generateJsx());
jest.spyOn(global.Date, 'now').mockImplementationOnce(() => now);
jest.spyOn(global.Date, 'now').mockImplementation(() => now);
await userEvent.click(screen.getByTestId(expire));
// expiry time/date was empty it should be set to now
@@ -590,9 +590,9 @@ describe('DealTicket', () => {
it('sets expiry time/date to now if expiry is changed to checked', async () => {
const datePicker = 'date-picker-field';
const now = Math.round(Date.now() / 1000) * 1000;
const now = 24 * 60 * 60 * 1000;
render(generateJsx());
jest.spyOn(global.Date, 'now').mockImplementationOnce(() => now);
jest.spyOn(global.Date, 'now').mockImplementation(() => now);
await userEvent.selectOptions(
screen.getByTestId('order-tif'),
Schema.OrderTimeInForce.TIME_IN_FORCE_GTT
@@ -496,11 +496,12 @@ export const DealTicket = ({
onSelect={(value) => {
// If GTT is selected and no expiresAt time is set, or its
// behind current time then reset the value to current time
const now = Date.now();
if (
value === Schema.OrderTimeInForce.TIME_IN_FORCE_GTT &&
(!expiresAt || new Date(expiresAt).getTime() < Date.now())
(!expiresAt || new Date(expiresAt).getTime() < now)
) {
setValue('expiresAt', formatForInput(new Date()), {
setValue('expiresAt', formatForInput(new Date(now)), {
shouldValidate: true,
});
}
+15 -2
View File
@@ -2,7 +2,11 @@ import type { Asset } from '@vegaprotocol/assets';
import { EtherscanLink } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { Intent, Notification } from '@vegaprotocol/ui-toolkit';
import { formatNumber } from '@vegaprotocol/utils';
import {
formatNumber,
getUnlimitedThreshold,
quantumDecimalPlaces,
} from '@vegaprotocol/utils';
import type { EthStoredTxState } from '@vegaprotocol/web3';
import { EthTxStatus, useEthTransactionStore } from '@vegaprotocol/web3';
import BigNumber from 'bignumber.js';
@@ -188,6 +192,15 @@ const ApprovalTxFeedback = ({
}
if (tx.status === EthTxStatus.Confirmed) {
const approvedAllowanceValue = (
allowance || new BigNumber(0)
).isGreaterThan(getUnlimitedThreshold(selectedAsset.decimals))
? '∞'
: formatNumber(
allowance?.toString() || 0,
quantumDecimalPlaces(selectedAsset.quantum, selectedAsset.decimals)
);
return (
<div className="mb-4">
<Notification
@@ -198,7 +211,7 @@ const ApprovalTxFeedback = ({
<p>
{t('You approved deposits of up to %s %s.', [
selectedAsset?.symbol,
formatNumber(allowance?.toString() || 0),
approvedAllowanceValue,
])}
</p>
{txLink && <p>{txLink}</p>}
+3 -2
View File
@@ -15,6 +15,7 @@ import { useWeb3ConnectStore } from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core';
import type { AssetFieldsFragment } from '@vegaprotocol/assets';
import type { DepositBalances } from './use-deposit-balances';
import { truncateMiddle } from '@vegaprotocol/ui-toolkit';
jest.mock('@vegaprotocol/wallet');
jest.mock('@vegaprotocol/web3');
@@ -90,7 +91,7 @@ describe('Deposit form', () => {
// Assert default values (including) from/to provided by useVegaWallet and useWeb3React
expect(screen.getByText('From (Ethereum address)')).toBeInTheDocument();
expect(screen.getByTestId('ethereum-address')).toHaveTextContent(
MOCK_ETH_ADDRESS
truncateMiddle(MOCK_ETH_ADDRESS)
);
expect(screen.getByLabelText('Asset')).toHaveValue('');
expect(screen.getByLabelText('To (Vega key)')).toHaveValue('');
@@ -353,7 +354,7 @@ describe('Deposit form', () => {
).not.toBeInTheDocument();
expect(screen.getByText('From (Ethereum address)')).toBeInTheDocument();
expect(screen.getByTestId('ethereum-address')).toHaveTextContent(
MOCK_ETH_ADDRESS
truncateMiddle(MOCK_ETH_ADDRESS)
);
});
+2 -1
View File
@@ -22,6 +22,7 @@ import {
Intent,
ButtonLink,
TradingSelect,
truncateMiddle,
} from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useWeb3React } from '@web3-react/core';
@@ -173,7 +174,7 @@ export const DepositForm = ({
return (
<div className="text-sm" aria-describedby="ethereum-address">
<p className="mb-1 break-all" data-testid="ethereum-address">
{account}
{truncateMiddle(account)}
</p>
<DisconnectEthereumButton
onDisconnect={() => {
+10 -4
View File
@@ -7,7 +7,7 @@ import {
Tooltip,
} from '@vegaprotocol/ui-toolkit';
import type BigNumber from 'bignumber.js';
import { formatNumber } from '@vegaprotocol/utils';
import { formatNumber, quantumDecimalPlaces } from '@vegaprotocol/utils';
// Note: all of the values here are with correct asset's decimals
// See `libs/deposits/src/lib/use-deposit-balances.ts`
@@ -35,7 +35,10 @@ export const DepositLimits = ({
label: t('Balance available'),
rawValue: balance,
value: balance ? (
<CompactNumber number={balance} decimals={asset.decimals} />
<CompactNumber
number={balance}
decimals={quantumDecimalPlaces(asset.quantum, asset.decimals)}
/>
) : (
'-'
),
@@ -73,7 +76,7 @@ export const DepositLimits = ({
value: !exempt ? (
<CompactNumber
number={max.minus(deposited)}
decimals={asset.decimals}
decimals={quantumDecimalPlaces(asset.quantum, asset.decimals)}
/>
) : (
<div data-testid="exempt">{t('Exempt')}</div>
@@ -97,7 +100,10 @@ export const DepositLimits = ({
),
rawValue: allowance,
value: allowance ? (
<CompactNumber number={allowance} decimals={asset.decimals} />
<CompactNumber
number={allowance}
decimals={quantumDecimalPlaces(asset.quantum, asset.decimals)}
/>
) : (
'-'
),
@@ -0,0 +1,109 @@
import { useState } from 'react';
import {
VegaIcon,
VegaIconNames,
TradingDropdown,
TradingDropdownTrigger,
TradingDropdownContent,
TradingDropdownItem,
} from '@vegaprotocol/ui-toolkit';
import { formatNumberFixed } from '@vegaprotocol/utils';
export const OrderbookControls = ({
lastTradedPrice,
resolution,
decimalPlaces,
setResolution,
}: {
lastTradedPrice: string | undefined;
resolution: number;
decimalPlaces: number;
setResolution: (resolution: number) => void;
}) => {
const [isOpen, setOpen] = useState(false);
const resolutions = new Array(
Math.max(lastTradedPrice?.toString().length ?? 0, decimalPlaces + 1)
)
.fill(null)
.map((v, i) => Math.pow(10, i));
const formatResolution = (r: number) => {
return formatNumberFixed(
Math.log10(r) - decimalPlaces > 0
? Math.pow(10, Math.log10(r) - decimalPlaces)
: 0,
decimalPlaces - Math.log10(r)
);
};
const increaseResolution = () => {
const index = resolutions.indexOf(resolution);
if (index < resolutions.length - 1) {
setResolution(resolutions[index + 1]);
}
};
const decreaseResolution = () => {
const index = resolutions.indexOf(resolution);
if (index > 0) {
setResolution(resolutions[index - 1]);
}
};
return (
<div className="flex h-6">
<button
onClick={increaseResolution}
disabled={resolutions.indexOf(resolution) >= resolutions.length - 1}
className="flex items-center px-2 border-r cursor-pointer border-default"
data-testid="plus-button"
>
<VegaIcon size={12} name={VegaIconNames.PLUS} />
</button>
<TradingDropdown
open={isOpen}
onOpenChange={(open) => setOpen(open)}
trigger={
<TradingDropdownTrigger data-testid="resolution">
<button
className="flex items-center px-2 text-left gap-1"
style={{
minWidth: `${
Math.max.apply(
null,
resolutions.map((item) => formatResolution(item).length)
) + 5
}ch`,
}}
>
<VegaIcon
size={12}
name={
isOpen ? VegaIconNames.CHEVRON_UP : VegaIconNames.CHEVRON_DOWN
}
/>
{formatResolution(resolution)}
</button>
</TradingDropdownTrigger>
}
>
<TradingDropdownContent align="start">
{resolutions.map((r) => (
<TradingDropdownItem key={r} onClick={() => setResolution(r)}>
{formatResolution(r)}
</TradingDropdownItem>
))}
</TradingDropdownContent>
</TradingDropdown>
<button
onClick={decreaseResolution}
disabled={resolutions.indexOf(resolution) <= 0}
className="flex items-center px-2 cursor-pointer border-x border-default"
data-testid="minus-button"
>
<VegaIcon size={12} name={VegaIconNames.MINUS} />
</button>
</div>
);
};
@@ -31,21 +31,12 @@ describe('compactRows', () => {
it('counts cumulative vol', () => {
const asks = compactRows(sell, VolumeType.ask, 10);
const bids = compactRows(buy, VolumeType.bid, 10);
expect(asks[0].cumulativeVol.value).toEqual(4950);
expect(bids[0].cumulativeVol.value).toEqual(579);
expect(asks[10].cumulativeVol.value).toEqual(390);
expect(bids[10].cumulativeVol.value).toEqual(4950);
expect(bids[bids.length - 1].cumulativeVol.value).toEqual(4950);
expect(asks[asks.length - 1].cumulativeVol.value).toEqual(390);
});
it('updates relative data', () => {
const asks = compactRows(sell, VolumeType.ask, 10);
const bids = compactRows(buy, VolumeType.bid, 10);
expect(asks[0].cumulativeVol.relativeValue).toEqual(100);
expect(bids[0].cumulativeVol.relativeValue).toEqual(12);
expect(asks[10].cumulativeVol.relativeValue).toEqual(8);
expect(bids[10].cumulativeVol.relativeValue).toEqual(100);
expect(asks[0].cumulativeVol).toEqual(4950);
expect(bids[0].cumulativeVol).toEqual(579);
expect(asks[10].cumulativeVol).toEqual(390);
expect(bids[10].cumulativeVol).toEqual(4950);
expect(bids[bids.length - 1].cumulativeVol).toEqual(4950);
expect(asks[asks.length - 1].cumulativeVol).toEqual(390);
});
});
+18 -36
View File
@@ -5,15 +5,11 @@ export enum VolumeType {
bid,
ask,
}
export interface CumulativeVol {
value: number;
relativeValue?: number;
}
export interface OrderbookRowData {
price: string;
value: number;
cumulativeVol: CumulativeVol;
volume: number;
cumulativeVol: number;
}
export const getPriceLevel = (price: string | bigint, resolution: number) => {
@@ -26,25 +22,6 @@ export const getPriceLevel = (price: string | bigint, resolution: number) => {
return priceLevel.toString();
};
const getMaxVolumes = (orderbookData: OrderbookRowData[]) => ({
cumulativeVol: Math.max(
orderbookData[0]?.cumulativeVol.value,
orderbookData[orderbookData.length - 1]?.cumulativeVol.value
),
});
// round instead of ceil so we will not show 0 if value if different than 0
const toPercentValue = (value?: number) => Math.ceil((value ?? 0) * 100);
const updateRelativeData = (data: OrderbookRowData[]) => {
const { cumulativeVol } = getMaxVolumes(data);
data.forEach((data, i) => {
data.cumulativeVol.relativeValue = toPercentValue(
data.cumulativeVol.value / cumulativeVol
);
});
};
const updateCumulativeVolumeByType = (
data: OrderbookRowData[],
dataType: VolumeType
@@ -53,14 +30,13 @@ const updateCumulativeVolumeByType = (
const maxIndex = data.length - 1;
if (dataType === VolumeType.bid) {
for (let i = 0; i <= maxIndex; i++) {
data[i].cumulativeVol.value =
data[i].value + (i !== 0 ? data[i - 1].cumulativeVol.value : 0);
data[i].cumulativeVol =
data[i].volume + (i !== 0 ? data[i - 1].cumulativeVol : 0);
}
} else {
for (let i = maxIndex; i >= 0; i--) {
data[i].cumulativeVol.value =
data[i].value +
(i !== maxIndex ? data[i + 1].cumulativeVol.value : 0);
data[i].cumulativeVol =
data[i].volume + (i !== maxIndex ? data[i + 1].cumulativeVol : 0);
}
}
}
@@ -75,6 +51,7 @@ export const compactRows = (
getPriceLevel(row.price, resolution)
);
const orderbookData: OrderbookRowData[] = [];
Object.keys(groupedByLevel).forEach((price) => {
const { volume } = groupedByLevel[price].pop() as PriceLevelFieldsFragment;
let value = Number(volume);
@@ -83,7 +60,11 @@ export const compactRows = (
value += Number(subRow.volume);
subRow = groupedByLevel[price].pop();
}
orderbookData.push({ price, value, cumulativeVol: { value: 0 } });
orderbookData.push({
price,
volume: value,
cumulativeVol: 0,
});
});
orderbookData.sort((a, b) => {
@@ -95,8 +76,9 @@ export const compactRows = (
}
return 1;
});
updateCumulativeVolumeByType(orderbookData, dataType);
updateRelativeData(orderbookData);
return orderbookData;
};
@@ -140,7 +122,7 @@ export interface MockDataGeneratorParams {
numberOfSellRows: number;
numberOfBuyRows: number;
overlap: number;
midPrice?: string;
lastTradedPrice: string;
bestStaticBidPrice: number;
bestStaticOfferPrice: number;
}
@@ -148,14 +130,14 @@ export interface MockDataGeneratorParams {
export const generateMockData = ({
numberOfSellRows,
numberOfBuyRows,
midPrice,
lastTradedPrice,
overlap,
bestStaticBidPrice,
bestStaticOfferPrice,
}: MockDataGeneratorParams) => {
let matrix = new Array(numberOfSellRows).fill(undefined);
let price =
Number(midPrice) + (numberOfSellRows - Math.ceil(overlap / 2) + 1);
Number(lastTradedPrice) + (numberOfSellRows - Math.ceil(overlap / 2) + 1);
const sell: PriceLevelFieldsFragment[] = matrix.map((row, i) => ({
price: (price -= 1).toString(),
volume: (numberOfSellRows - i + 1).toString(),
@@ -171,7 +153,7 @@ export const generateMockData = ({
return {
asks: sell,
bids: buy,
midPrice,
lastTradedPrice,
bestStaticBidPrice: bestStaticBidPrice.toString(),
bestStaticOfferPrice: bestStaticOfferPrice.toString(),
};
+12 -10
View File
@@ -17,7 +17,7 @@ export type OrderbookData = {
interface OrderbookManagerProps {
marketId: string;
onClick?: (args: { price?: string; size?: string }) => void;
onClick: (args: { price?: string; size?: string }) => void;
}
export const OrderbookManager = ({
@@ -61,15 +61,17 @@ export const OrderbookManager = ({
data={data}
reload={reload}
>
<Orderbook
bids={data?.depth.buy ?? []}
asks={data?.depth.sell ?? []}
decimalPlaces={market?.decimalPlaces ?? 0}
positionDecimalPlaces={market?.positionDecimalPlaces ?? 0}
assetSymbol={market?.tradableInstrument.instrument.product.quoteName}
onClick={onClick}
midPrice={marketData?.midPrice}
/>
{market && marketData && (
<Orderbook
bids={data?.depth.buy ?? []}
asks={data?.depth.sell ?? []}
decimalPlaces={market.decimalPlaces}
positionDecimalPlaces={market.positionDecimalPlaces}
assetSymbol={market.tradableInstrument.instrument.product.quoteName}
onClick={onClick}
lastTradedPrice={marketData.lastTradedPrice}
/>
)}
</AsyncRenderer>
);
};
+105 -114
View File
@@ -1,158 +1,149 @@
import React, { memo } from 'react';
import type { ReactNode } from 'react';
import { memo } from 'react';
import { addDecimal, addDecimalsFixedFormatNumber } from '@vegaprotocol/utils';
import { NumericCell, PriceCell } from '@vegaprotocol/datagrid';
import { NumericCell } from '@vegaprotocol/datagrid';
import { VolumeType } from './orderbook-data';
import classNames from 'classnames';
const HIDE_VOL_WIDTH = 190;
const HIDE_CUMULATIVE_VOL_WIDTH = 260;
interface OrderbookRowProps {
value: number;
cumulativeValue?: number;
cumulativeRelativeValue?: number;
volume: number;
cumulativeVolume: number;
decimalPlaces: number;
positionDecimalPlaces: number;
price: string;
onClick?: (args: { price?: string; size?: string }) => void;
onClick: (args: { price?: string; size?: string }) => void;
type: VolumeType;
width: number;
maxVol: number;
}
const HIDE_VOL_WIDTH = 150;
const HIDE_CUMULATIVE_VOL_WIDTH = 220;
const CumulationBar = ({
cumulativeValue = 0,
type,
}: {
cumulativeValue?: number;
type: VolumeType;
}) => {
return (
<div
data-testid={`${VolumeType.bid === type ? 'bid' : 'ask'}-bar`}
className={classNames(
'absolute top-0 left-0 h-full',
type === VolumeType.bid
? 'bg-market-green-300 dark:bg-market-green/50'
: 'bg-market-red-300 dark:bg-market-red/30'
)}
style={{
width: `${cumulativeValue}%`,
}}
/>
);
};
const CumulativeVol = memo(
export const OrderbookRow = memo(
({
testId,
positionDecimalPlaces,
cumulativeValue,
onClick,
}: {
ask?: number;
bid?: number;
cumulativeValue?: number;
testId?: string;
className?: string;
positionDecimalPlaces: number;
onClick?: (size?: string | number) => void;
}) => {
const volume = cumulativeValue ? (
<NumericCell
testId={testId}
value={cumulativeValue}
valueFormatted={addDecimalsFixedFormatNumber(
cumulativeValue,
positionDecimalPlaces ?? 0
)}
/>
) : null;
return onClick && volume ? (
<button
onClick={() => onClick(cumulativeValue)}
className="hover:dark:bg-neutral-800 hover:bg-neutral-200 text-right pr-1"
>
{volume}
</button>
) : (
<div className="pr-1" data-testid={testId}>
{volume}
</div>
);
}
);
CumulativeVol.displayName = 'OrderBookCumulativeVol';
export const OrderbookRow = React.memo(
({
value,
cumulativeValue,
cumulativeRelativeValue,
volume,
cumulativeVolume,
decimalPlaces,
positionDecimalPlaces,
price,
onClick,
type,
width,
maxVol,
}: OrderbookRowProps) => {
const txtId = type === VolumeType.bid ? 'bid' : 'ask';
const cols =
width >= HIDE_CUMULATIVE_VOL_WIDTH ? 3 : width >= HIDE_VOL_WIDTH ? 2 : 1;
return (
<div className="relative pr-1">
<CumulationBar cumulativeValue={cumulativeRelativeValue} type={type} />
<div className="relative px-1">
<CumulationBar
cumulativeVolume={cumulativeVolume}
type={type}
maxVol={maxVol}
/>
<div
data-testid={`${txtId}-rows-container`}
className={classNames('grid gap-1 text-right', `grid-cols-${cols}`)}
>
<PriceCell
testId={`price-${price}`}
value={BigInt(price)}
onClick={() =>
onClick && onClick({ price: addDecimal(price, decimalPlaces) })
}
valueFormatted={addDecimalsFixedFormatNumber(price, decimalPlaces)}
className={
type === VolumeType.ask
? 'text-market-red dark:text-market-red'
: 'text-market-green-600 dark:text-market-green'
}
/>
{width >= HIDE_VOL_WIDTH && (
<PriceCell
testId={`${txtId}-vol-${price}`}
onClick={(value) =>
onClick &&
value &&
onClick({
size: addDecimal(value, positionDecimalPlaces),
})
}
value={value}
<OrderBookRowCell
onClick={() => onClick({ price: addDecimal(price, decimalPlaces) })}
>
<NumericCell
testId={`price-${price}`}
value={BigInt(price)}
valueFormatted={addDecimalsFixedFormatNumber(
value,
positionDecimalPlaces
price,
decimalPlaces
)}
className={classNames({
'text-market-red dark:text-market-red': type === VolumeType.ask,
'text-market-green-600 dark:text-market-green':
type === VolumeType.bid,
})}
/>
</OrderBookRowCell>
{width >= HIDE_VOL_WIDTH && (
<OrderBookRowCell
onClick={() =>
onClick({ size: addDecimal(volume, positionDecimalPlaces) })
}
>
<NumericCell
testId={`${txtId}-vol-${price}`}
value={volume}
valueFormatted={addDecimalsFixedFormatNumber(
volume,
positionDecimalPlaces ?? 0
)}
/>
</OrderBookRowCell>
)}
{width >= HIDE_CUMULATIVE_VOL_WIDTH && (
<CumulativeVol
testId={`cumulative-vol-${price}`}
<OrderBookRowCell
onClick={() =>
onClick &&
cumulativeValue &&
onClick({
size: addDecimal(cumulativeValue, positionDecimalPlaces),
size: addDecimal(cumulativeVolume, positionDecimalPlaces),
})
}
positionDecimalPlaces={positionDecimalPlaces}
cumulativeValue={cumulativeValue}
/>
>
<NumericCell
testId={`cumulative-vol-${price}`}
value={cumulativeVolume}
valueFormatted={addDecimalsFixedFormatNumber(
cumulativeVolume,
positionDecimalPlaces
)}
/>
</OrderBookRowCell>
)}
</div>
</div>
);
}
);
OrderbookRow.displayName = 'OrderbookRow';
const OrderBookRowCell = ({
children,
onClick,
}: {
children: ReactNode;
onClick: () => void;
}) => {
return (
<button
className="overflow-hidden text-right text-ellipsis whitespace-nowrap hover:dark:bg-neutral-800 hover:bg-neutral-200"
onClick={onClick}
>
{children}
</button>
);
};
const CumulationBar = ({
cumulativeVolume = 0,
type,
maxVol,
}: {
cumulativeVolume: number;
type: VolumeType;
maxVol: number;
}) => {
const width = (cumulativeVolume / maxVol) * 100;
return (
<div
data-testid={`${VolumeType.bid === type ? 'bid' : 'ask'}-bar`}
className={classNames(
'absolute top-0 left-0 h-full',
type === VolumeType.bid
? 'bg-market-green/10 dark:bg-market-green/10'
: 'bg-market-red/10 dark:bg-market-red/10'
)}
style={{
width: `${width}%`,
}}
/>
);
};
+53 -7
View File
@@ -1,7 +1,7 @@
import { render, waitFor, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { generateMockData, VolumeType } from './orderbook-data';
import { Orderbook } from './orderbook';
import { Orderbook, OrderbookMid } from './orderbook';
import * as orderbookData from './orderbook-data';
function mockOffsetSize(width: number, height: number) {
@@ -24,7 +24,7 @@ describe('Orderbook', () => {
numberOfSellRows: 100,
numberOfBuyRows: 100,
step: 1,
midPrice: '122900',
lastTradedPrice: '122900',
bestStaticBidPrice: 122905,
bestStaticOfferPrice: 122895,
decimalPlaces: 3,
@@ -44,13 +44,14 @@ describe('Orderbook', () => {
positionDecimalPlaces={0}
{...generateMockData(params)}
assetSymbol="USD"
onClick={jest.fn()}
/>
);
await waitFor(() =>
screen.getByTestId(`middle-mark-price-${params.midPrice}`)
screen.getByTestId(`last-traded-${params.lastTradedPrice}`)
);
expect(
screen.getByTestId(`middle-mark-price-${params.midPrice}`)
screen.getByTestId(`last-traded-${params.lastTradedPrice}`)
).toHaveTextContent('122.90');
});
@@ -68,10 +69,10 @@ describe('Orderbook', () => {
/>
);
expect(
await screen.findByTestId(`middle-mark-price-${params.midPrice}`)
await screen.findByTestId(`last-traded-${params.lastTradedPrice}`)
).toBeInTheDocument();
// Before resolution change the price is 122.934
await userEvent.click(await screen.getByTestId('price-122901'));
await userEvent.click(screen.getByTestId('price-122901'));
expect(onClickSpy).toBeCalledWith({ price: '122.901' });
await userEvent.click(screen.getByTestId('resolution'));
@@ -92,7 +93,7 @@ describe('Orderbook', () => {
VolumeType.ask,
10
);
await userEvent.click(await screen.getByTestId('price-12294'));
await userEvent.click(screen.getByTestId('price-12294'));
expect(onClickSpy).toBeCalledWith({ price: '122.94' });
});
@@ -177,3 +178,48 @@ describe('Orderbook', () => {
});
});
});
describe('OrderbookMid', () => {
const props = {
lastTradedPrice: '100',
decimalPlaces: 0,
assetSymbol: 'BTC',
bestAskPrice: '101',
bestBidPrice: '99',
};
it('renders no change until lastTradedPrice changes', () => {
const { rerender } = render(<OrderbookMid {...props} />);
expect(screen.getByTestId(/last-traded/)).toHaveTextContent(
props.lastTradedPrice
);
expect(screen.getByText(props.assetSymbol)).toBeInTheDocument();
expect(screen.queryByTestId(/icon-/)).not.toBeInTheDocument();
expect(screen.getByTestId('spread')).toHaveTextContent('(2)');
// rerender with no change should not show the icon
rerender(<OrderbookMid {...props} />);
expect(screen.queryByTestId(/icon-/)).not.toBeInTheDocument();
rerender(
<OrderbookMid {...props} lastTradedPrice="101" bestAskPrice="102" />
);
expect(screen.getByTestId('icon-arrow-up')).toBeInTheDocument();
expect(screen.getByTestId('spread')).toHaveTextContent('(3)');
// rerender again with the same price, should still be set to 'up'
rerender(
<OrderbookMid
{...props}
lastTradedPrice="101"
bestAskPrice="102"
bestBidPrice="98"
/>
);
expect(screen.getByTestId('icon-arrow-up')).toBeInTheDocument();
expect(screen.getByTestId('spread')).toHaveTextContent('(4)');
rerender(<OrderbookMid {...props} lastTradedPrice="100" />);
expect(screen.getByTestId('icon-arrow-down')).toBeInTheDocument();
});
});
@@ -9,9 +9,9 @@ type Props = Omit<MockDataGeneratorParams, 'resolution'> & {
const OrderbookMockDataProvider = ({ decimalPlaces, ...props }: Props) => {
return (
<div className="absolute inset-0 dark:bg-black dark:text-neutral-200 bg-white text-neutral-800">
<div className="absolute inset-0 bg-white dark:bg-black dark:text-neutral-200 text-neutral-800">
<div
className="absolute left-0 top-0 bottom-0"
className="absolute top-0 bottom-0 left-0"
style={{ width: '400px' }}
>
<Orderbook
@@ -19,6 +19,7 @@ const OrderbookMockDataProvider = ({ decimalPlaces, ...props }: Props) => {
decimalPlaces={decimalPlaces}
{...generateMockData({ ...props })}
assetSymbol="USD"
onClick={() => undefined}
/>
</div>
</div>
+112 -151
View File
@@ -1,25 +1,15 @@
import { useMemo, useRef, useState } from 'react';
import ReactVirtualizedAutoSizer from 'react-virtualized-auto-sizer';
import {
addDecimalsFormatNumber,
formatNumberFixed,
} from '@vegaprotocol/utils';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { usePrevious } from '@vegaprotocol/react-helpers';
import { OrderbookRow } from './orderbook-row';
import type { OrderbookRowData } from './orderbook-data';
import { compactRows, VolumeType } from './orderbook-data';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
Splash,
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { Splash, VegaIcon, VegaIconNames } from '@vegaprotocol/ui-toolkit';
import classNames from 'classnames';
import type { PriceLevelFieldsFragment } from './__generated__/MarketDepth';
import { OrderbookControls } from './orderbook-controls';
// Sets row height, will be used to calculate number of rows that can be
// displayed each side of the book without overflow
@@ -27,20 +17,7 @@ export const rowHeight = 17;
const rowGap = 1;
const midHeight = 30;
type PriceChange = 'up' | 'down' | 'none';
const PRICE_CHANGE_ICON_MAP: Readonly<Record<PriceChange, VegaIconNames>> = {
up: VegaIconNames.ARROW_UP,
down: VegaIconNames.ARROW_DOWN,
none: VegaIconNames.BULLET,
};
const PRICE_CHANGE_CLASS_MAP: Readonly<Record<PriceChange, string>> = {
up: 'text-market-green-600 dark:text-market-green',
down: 'text-market-red dark:text-market-red',
none: 'text-vega-blue-500',
};
const OrderbookTable = ({
const OrderbookSide = ({
rows,
resolution,
type,
@@ -48,14 +25,16 @@ const OrderbookTable = ({
positionDecimalPlaces,
onClick,
width,
maxVol,
}: {
rows: OrderbookRowData[];
resolution: number;
decimalPlaces: number;
positionDecimalPlaces: number;
type: VolumeType;
onClick?: (args: { price?: string; size?: string }) => void;
onClick: (args: { price?: string; size?: string }) => void;
width: number;
maxVol: number;
}) => {
return (
<div
@@ -78,11 +57,11 @@ const OrderbookTable = ({
onClick={onClick}
decimalPlaces={decimalPlaces - Math.log10(resolution)}
positionDecimalPlaces={positionDecimalPlaces}
value={data.value}
cumulativeValue={data.cumulativeVol.value}
cumulativeRelativeValue={data.cumulativeVol.relativeValue}
volume={data.volume}
cumulativeVolume={data.cumulativeVol}
type={type}
width={width}
maxVol={maxVol}
/>
))}
</div>
@@ -90,31 +69,88 @@ const OrderbookTable = ({
);
};
export const OrderbookMid = ({
lastTradedPrice,
decimalPlaces,
assetSymbol,
bestAskPrice,
bestBidPrice,
}: {
lastTradedPrice: string;
decimalPlaces: number;
assetSymbol: string;
bestAskPrice: string;
bestBidPrice: string;
}) => {
const previousLastTradedPrice = usePrevious(lastTradedPrice);
const priceChangeRef = useRef<'up' | 'down' | 'none'>('none');
const spread = (BigInt(bestAskPrice) - BigInt(bestBidPrice)).toString();
if (previousLastTradedPrice !== lastTradedPrice) {
priceChangeRef.current =
Number(previousLastTradedPrice) > Number(lastTradedPrice) ? 'down' : 'up';
}
return (
<div className="flex items-center justify-center text-base gap-2">
{priceChangeRef.current !== 'none' && (
<span
className={classNames('flex flex-col justify-center', {
'text-market-green-600 dark:text-market-green':
priceChangeRef.current === 'up',
'text-market-red dark:text-market-red':
priceChangeRef.current === 'down',
})}
>
<VegaIcon
name={
priceChangeRef.current === 'up'
? VegaIconNames.ARROW_UP
: VegaIconNames.ARROW_DOWN
}
/>
</span>
)}
<span
// monospace sizing doesn't quite align with alpha
className="font-mono text-[15px]"
data-testid={`last-traded-${lastTradedPrice}`}
title={t('Last traded price')}
>
{addDecimalsFormatNumber(lastTradedPrice, decimalPlaces)}
</span>
<span>{assetSymbol}</span>
<span
title={t('Spread')}
className="font-mono text-xs text-muted"
data-testid="spread"
>
({addDecimalsFormatNumber(spread, decimalPlaces)})
</span>
</div>
);
};
interface OrderbookProps {
decimalPlaces: number;
positionDecimalPlaces: number;
onClick?: (args: { price?: string; size?: string }) => void;
midPrice?: string;
onClick: (args: { price?: string; size?: string }) => void;
lastTradedPrice: string;
bids: PriceLevelFieldsFragment[];
asks: PriceLevelFieldsFragment[];
assetSymbol: string | undefined;
assetSymbol: string;
}
export const Orderbook = ({
decimalPlaces,
positionDecimalPlaces,
onClick,
midPrice,
lastTradedPrice,
asks,
bids,
assetSymbol,
}: OrderbookProps) => {
const [resolution, setResolution] = useState(1);
const resolutions = new Array(
Math.max(midPrice?.toString().length ?? 0, decimalPlaces + 1)
)
.fill(null)
.map((v, i) => Math.pow(10, i));
const groupedAsks = useMemo(() => {
return compactRows(asks, VolumeType.ask, resolution);
@@ -123,44 +159,11 @@ export const Orderbook = ({
const groupedBids = useMemo(() => {
return compactRows(bids, VolumeType.bid, resolution);
}, [bids, resolution]);
const [isOpen, setOpen] = useState(false);
const previousMidPrice = usePrevious(midPrice);
const priceChangeRef = useRef<'up' | 'down' | 'none'>('none');
if (midPrice && previousMidPrice !== midPrice) {
priceChangeRef.current =
(previousMidPrice || '') > midPrice ? 'down' : 'up';
}
const priceChangeIcon = (
<span
className={classNames(PRICE_CHANGE_CLASS_MAP[priceChangeRef.current])}
>
<VegaIcon name={PRICE_CHANGE_ICON_MAP[priceChangeRef.current]} />
</span>
);
const formatResolution = (r: number) => {
return formatNumberFixed(
Math.log10(r) - decimalPlaces > 0
? Math.pow(10, Math.log10(r) - decimalPlaces)
: 0,
decimalPlaces - Math.log10(r)
);
};
const increaseResolution = () => {
const index = resolutions.indexOf(resolution);
if (index < resolutions.length - 1) {
setResolution(resolutions[index + 1]);
}
};
const decreaseResolution = () => {
const index = resolutions.indexOf(resolution);
if (index > 0) {
setResolution(resolutions[index - 1]);
}
};
// get the best bid/ask, note that we are using the pre aggregated
// values so we can render the most accurate spread in the mid section
const bestAskPrice = asks[0] ? asks[0].price : '0';
const bestBidPrice = bids[0] ? bids[0].price : '0';
return (
<div className="h-full text-xs grid grid-rows-[1fr_min-content]">
@@ -171,21 +174,30 @@ export const Orderbook = ({
1,
Math.floor((height - midHeight) / 2 / (rowHeight + rowGap))
);
const askRows = groupedAsks?.slice(limit * -1) ?? [];
const bidRows = groupedBids?.slice(0, limit) ?? [];
const askRows = groupedAsks.slice(limit * -1);
const bidRows = groupedBids.slice(0, limit);
// this is used for providing a scale to render the volume
// bars based on the visible book
const deepestVisibleAsk = askRows[0];
const deepestVisibleBid = bidRows[bidRows.length - 1];
const maxVol = Math.max(
deepestVisibleAsk?.cumulativeVol || 0,
deepestVisibleBid?.cumulativeVol || 0
);
return (
<div
className="overflow-hidden grid"
data-testid="orderbook-grid-element"
style={{
width: width + 'px',
height: height + 'px',
width,
height,
gridTemplateRows: `1fr ${midHeight}px 1fr`, // cannot use tailwind here as tailwind will not parse a class string with interpolation
}}
>
{askRows.length || bidRows.length ? (
<>
<OrderbookTable
<OrderbookSide
rows={askRows}
type={VolumeType.ask}
resolution={resolution}
@@ -193,22 +205,16 @@ export const Orderbook = ({
positionDecimalPlaces={positionDecimalPlaces}
onClick={onClick}
width={width}
maxVol={maxVol}
/>
<div className="flex items-center justify-center gap-2">
{midPrice && (
<>
<span
className="font-mono text-lg"
data-testid={`middle-mark-price-${midPrice}`}
>
{addDecimalsFormatNumber(midPrice, decimalPlaces)}
</span>
<span className="text-base">{assetSymbol}</span>
{priceChangeIcon}
</>
)}
</div>
<OrderbookTable
<OrderbookMid
lastTradedPrice={lastTradedPrice}
decimalPlaces={decimalPlaces}
assetSymbol={assetSymbol}
bestAskPrice={bestAskPrice}
bestBidPrice={bestBidPrice}
/>
<OrderbookSide
rows={bidRows}
type={VolumeType.bid}
resolution={resolution}
@@ -216,10 +222,11 @@ export const Orderbook = ({
positionDecimalPlaces={positionDecimalPlaces}
onClick={onClick}
width={width}
maxVol={maxVol}
/>
</>
) : (
<div className="inset-0 absolute">
<div className="absolute inset-0">
<Splash>{t('No data')}</Splash>
</div>
)}
@@ -228,59 +235,13 @@ export const Orderbook = ({
}}
</ReactVirtualizedAutoSizer>
</div>
<div className="border-t border-default flex">
<button
onClick={increaseResolution}
disabled={resolutions.indexOf(resolution) >= resolutions.length - 1}
className="flex items-center border-r border-default px-2 cursor-pointer"
data-testid="plus-button"
>
<VegaIcon size={12} name={VegaIconNames.PLUS} />
</button>
<DropdownMenu
open={isOpen}
onOpenChange={(open) => setOpen(open)}
trigger={
<DropdownMenuTrigger
data-testid="resolution"
className="flex justify-between px-1 items-center"
style={{
width: `${
Math.max.apply(
null,
resolutions.map((item) => formatResolution(item).length)
) + 3
}ch`,
}}
>
<VegaIcon
size={12}
name={
isOpen ? VegaIconNames.CHEVRON_UP : VegaIconNames.CHEVRON_DOWN
}
/>
<div className="text-xs text-left">
{formatResolution(resolution)}
</div>
</DropdownMenuTrigger>
}
>
<DropdownMenuContent align="start">
{resolutions.map((r) => (
<DropdownMenuItem key={r} onClick={() => setResolution(r)}>
{formatResolution(r)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<button
onClick={decreaseResolution}
disabled={resolutions.indexOf(resolution) <= 0}
className="flex items-center border-x border-default px-2 cursor-pointer"
data-testid="minus-button"
>
<VegaIcon size={12} name={VegaIconNames.MINUS} />
</button>
<div className="border-t border-default">
<OrderbookControls
lastTradedPrice={lastTradedPrice}
resolution={resolution}
decimalPlaces={decimalPlaces}
setResolution={setResolution}
/>
</div>
</div>
);
+6 -4
View File
@@ -3,23 +3,23 @@ import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type MarketDataUpdateFieldsFragment = { __typename?: 'ObservableMarketData', marketId: string, auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null };
export type MarketDataUpdateFieldsFragment = { __typename?: 'ObservableMarketData', marketId: string, auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, lastTradedPrice: string, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null };
export type MarketDataUpdateSubscriptionVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type MarketDataUpdateSubscription = { __typename?: 'Subscription', marketsData: Array<{ __typename?: 'ObservableMarketData', marketId: string, auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null }> };
export type MarketDataUpdateSubscription = { __typename?: 'Subscription', marketsData: Array<{ __typename?: 'ObservableMarketData', marketId: string, auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, lastTradedPrice: string, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null }> };
export type MarketDataFieldsFragment = { __typename?: 'MarketData', auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, market: { __typename?: 'Market', id: string }, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null };
export type MarketDataFieldsFragment = { __typename?: 'MarketData', auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, lastTradedPrice: string, market: { __typename?: 'Market', id: string }, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null };
export type MarketDataQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type MarketDataQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', data?: { __typename?: 'MarketData', auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, market: { __typename?: 'Market', id: string }, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null } | null } }> } | null };
export type MarketDataQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', data?: { __typename?: 'MarketData', auctionEnd?: string | null, auctionStart?: string | null, bestBidPrice: string, bestBidVolume: string, bestOfferPrice: string, bestOfferVolume: string, bestStaticBidPrice: string, bestStaticBidVolume: string, bestStaticOfferPrice: string, bestStaticOfferVolume: string, indicativePrice: string, indicativeVolume: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, marketValueProxy: string, markPrice: string, midPrice: string, openInterest: string, staticMidPrice: string, suppliedStake?: string | null, targetStake?: string | null, trigger: Types.AuctionTrigger, lastTradedPrice: string, market: { __typename?: 'Market', id: string }, priceMonitoringBounds?: Array<{ __typename?: 'PriceMonitoringBounds', minValidPrice: string, maxValidPrice: string, referencePrice: string, trigger: { __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number } }> | null } | null } }> } | null };
export const MarketDataUpdateFieldsFragmentDoc = gql`
fragment MarketDataUpdateFields on ObservableMarketData {
@@ -56,6 +56,7 @@ export const MarketDataUpdateFieldsFragmentDoc = gql`
suppliedStake
targetStake
trigger
lastTradedPrice
}
`;
export const MarketDataFieldsFragmentDoc = gql`
@@ -95,6 +96,7 @@ export const MarketDataFieldsFragmentDoc = gql`
suppliedStake
targetStake
trigger
lastTradedPrice
}
`;
export const MarketDataUpdateDocument = gql`
+2
View File
@@ -32,6 +32,7 @@ fragment MarketDataUpdateFields on ObservableMarketData {
suppliedStake
targetStake
trigger
lastTradedPrice
}
subscription MarketDataUpdate($marketId: ID!) {
@@ -76,6 +77,7 @@ fragment MarketDataFields on MarketData {
suppliedStake
targetStake
trigger
lastTradedPrice
}
query MarketData($marketId: ID!) {
+2
View File
@@ -62,6 +62,7 @@ const marketDataFields: MarketDataFieldsFragment = {
markPrice: '4612690058',
midPrice: '4612690000',
openInterest: '0',
lastTradedPrice: '4612690000',
priceMonitoringBounds: [
{
minValidPrice: '654701',
@@ -99,6 +100,7 @@ const marketDataUpdateFields: MarketDataUpdateFieldsFragment = {
marketValueProxy: '',
markPrice: '4612690058',
midPrice: '0',
lastTradedPrice: '0',
openInterest: '0',
staticMidPrice: '0',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
@@ -5,6 +5,6 @@ import { toNumberParts } from '@vegaprotocol/utils';
export const useNumberParts = (
value: BigNumber | null | undefined,
decimals: number
): [integers: string, decimalPlaces: string] => {
): [integers: string, decimalPlaces: string, separator: string | undefined] => {
return useMemo(() => toNumberParts(value, decimals), [decimals, value]);
};
+10 -1
View File
@@ -1,9 +1,14 @@
import { BigNumber } from 'bignumber.js';
import { getUserLocale, formatNumber } from '@vegaprotocol/utils';
import {
getUserLocale,
formatNumber,
getUnlimitedThreshold,
} from '@vegaprotocol/utils';
const INFINITY = '∞';
const DEFAULT_COMPACT_ABOVE = 1_000_000;
const DEFAULT_COMPACT_CAP = new BigNumber(1e24);
/**
* Compacts given number to human readable format.
* @param number
@@ -35,6 +40,10 @@ export const CompactNumber = ({
const decimalPlaces =
(decimals === 'infer' ? number.decimalPlaces() : decimals) || 0;
if (number.isGreaterThan(getUnlimitedThreshold(decimalPlaces))) {
return <span data-testid={testId}>{INFINITY}</span>;
}
if (number.isLessThan(DEFAULT_COMPACT_ABOVE)) {
return (
<span data-testid={testId}>{formatNumber(number, decimalPlaces)}</span>
+70 -8
View File
@@ -5,7 +5,9 @@ import {
addDecimalsFormatNumberQuantum,
formatNumber,
formatNumberPercentage,
getUnlimitedThreshold,
isNumeric,
quantumDecimalPlaces,
toDecimal,
toNumberParts,
} from './number';
@@ -82,17 +84,17 @@ describe('number utils', () => {
describe('toNumberParts', () => {
it.each([
{ v: null, d: 3, o: ['0', '000'] },
{ v: undefined, d: 3, o: ['0', '000'] },
{ v: new BigNumber(123), d: 3, o: ['123', '00'] },
{ v: new BigNumber(123.123), d: 3, o: ['123', '123'] },
{ v: new BigNumber(123.123), d: 6, o: ['123', '123'] },
{ v: new BigNumber(123.123), d: 0, o: ['123', ''] },
{ v: new BigNumber(123), d: undefined, o: ['123', '00'] },
{ v: null, d: 3, o: ['0', '000', '.'] },
{ v: undefined, d: 3, o: ['0', '000', '.'] },
{ v: new BigNumber(123), d: 3, o: ['123', '00', '.'] },
{ v: new BigNumber(123.123), d: 3, o: ['123', '123', '.'] },
{ v: new BigNumber(123.123), d: 6, o: ['123', '123', '.'] },
{ v: new BigNumber(123.123), d: 0, o: ['123', '', '.'] },
{ v: new BigNumber(123), d: undefined, o: ['123', '00', '.'] },
{
v: new BigNumber(30000),
d: undefined,
o: ['30,000', '00'],
o: ['30,000', '00', '.'],
},
])('returns correct tuple given the different arguments', ({ v, d, o }) => {
expect(toNumberParts(v, d)).toStrictEqual(o);
@@ -156,3 +158,63 @@ describe('number utils', () => {
});
});
});
describe('quantumDecimalPlaces', () => {
it.each([
['1', 1, 3],
['10', 1, 2],
['100', 1, 1],
['1000', 1, 0],
['1', 2, 4],
['10', 2, 3],
['100', 2, 2],
['1000', 2, 1],
['1', 3, 5],
['10', 3, 4],
['100', 3, 3],
['1000', 3, 2],
['1', 18, 20],
['1000000000', 18, 11],
['5000000000', 18, 11],
['1000000000000000000', 18, 2],
])(
'converts quantum %s of %d decimal places to %d quant. decimal places',
(quantum, decimals, output) => {
expect(quantumDecimalPlaces(quantum, decimals)).toEqual(output);
}
);
});
describe('getUnlimitedThreshold', () => {
it.each([
[
0,
'9.26336713898529563388567880069503262826159877325124512315660672063305037119488e+76',
],
[
1,
'9.26336713898529563388567880069503262826159877325124512315660672063305037119488e+75',
],
[
2,
'9.26336713898529563388567880069503262826159877325124512315660672063305037119488e+74',
],
[
3,
'9.26336713898529563388567880069503262826159877325124512315660672063305037119488e+73',
],
[
10,
'9.26336713898529563388567880069503262826159877325124512315660672063305037119488e+66',
],
[
18,
'9.26336713898529563388567880069503262826159877325124512315660672063305037119488e+58',
],
])(
'given %d decimal places it returns unlimited threshold %s',
(decimals, output) => {
expect(getUnlimitedThreshold(decimals).toString()).toEqual(output);
}
);
});
+34 -3
View File
@@ -4,6 +4,18 @@ import memoize from 'lodash/memoize';
import { getUserLocale } from '../get-user-locale';
/**
* A raw unformatted value greater than this is considered and displayed
* as UNLIMITED.
*/
export const UNLIMITED_THRESHOLD = new BigNumber(2).pow(256).times(0.8);
/**
* Gets the unlimited threshold value for given decimal places.
* @param decimalPlaces the asset's decimal places
*/
export const getUnlimitedThreshold = (decimalPlaces: number) =>
UNLIMITED_THRESHOLD.dividedBy(Math.pow(10, decimalPlaces));
const MIN_FRACTION_DIGITS = 2;
const MAX_FRACTION_DIGITS = 20;
@@ -90,6 +102,25 @@ export const formatNumberFixed = (
return getFixedNumberFormat(formatDecimals).format(Number(rawValue));
};
export const quantumDecimalPlaces = (
/** Raw asset's quantum value */
rawQuantum: number | string,
/** Asset's decimal places */
decimalPlaces: number
) => {
// if raw quantum value is an empty string then it'll evaluate to 0
// this check ignores NaNs and zeroes
const formatDecimals =
isNaN(Number(rawQuantum)) || Number(rawQuantum) === 0
? decimalPlaces
: Math.max(
0,
Math.log10(100 / Number(addDecimal(rawQuantum, decimalPlaces)))
);
return Math.ceil(formatDecimals);
};
export const addDecimalsFormatNumberQuantum = (
rawValue: string | number,
decimalPlaces: number,
@@ -132,15 +163,15 @@ export const formatNumberPercentage = (value: BigNumber, decimals?: number) => {
export const toNumberParts = (
value: BigNumber | null | undefined,
decimals = 18
): [integers: string, decimalPlaces: string] => {
): [integers: string, decimalPlaces: string, separator: string] => {
if (!value) {
return ['0', '0'.repeat(decimals)];
return ['0', '0'.repeat(decimals), '.'];
}
const separator = getDecimalSeparator() || '.';
const [integers, decimalsPlaces] = formatNumber(value, decimals)
.toString()
.split(separator);
return [integers, decimalsPlaces || ''];
return [integers, decimalsPlaces || '', separator];
};
export const isNumeric = (
+4 -1
View File
@@ -11,4 +11,7 @@ As a market user I want to see information about orders existing in the market.
- I **Must** see prices sorted descending (<a name="6003-ORDB-007" href="#6003-ORDB-007">6003-ORDB-007</a>)
- I **Must** be able to set a resolution of data (<a name="6003-ORDB-008" href="#6003-ORDB-008">6003-ORDB-008</a>)
- When I click specific price, it **Must** be copied to deal ticket form (<a name="6003-ORDB-009" href="#6003-ORDB-009">6003-ORDB-009</a>)
- Order is removed from orderbook if traded away(<a name="6003-ORDB-010" href="#6003-ORDB-010">6003-ORDB-010</a>)
- Order is removed from orderbook if traded away (<a name="6003-ORDB-010" href="#6003-ORDB-010">6003-ORDB-010</a>)
- Spread (bestAsk - bestOffer) is show in the mid secion (<a name="6003-ORDB-011" href="#6003-ORDB-011">6003-ORDB-011</a>)
- Cumulative volume is displayed visually (volume bars) as a proportion of the entire book volume (<a name="6003-ORDB-012" href="#6003-ORDB-012">6003-ORDB-012</a>)
- Mid section shows the last traded price movement using an arrow (<a name="6003-ORDB-013" href="#6003-ORDB-013">6003-ORDB-013</a>)
+3 -6
View File
@@ -37,14 +37,11 @@ EOT
auth_soft_fail = true
}
docker_service "postgres-1" {
image = "vegaprotocol/timescaledb:2.8.0-pg14"
# Read me for more details: https://github.com/vegaprotocol/docker/tree/main/timescaledb#timescaledb
image = "vegaprotocol/vegacapsule-timescaledb:2.8.0-pg14-v0.0.1"
cmd = "postgres"
args = []
env = {
POSTGRES_USER="vega"
POSTGRES_PASSWORD="vega"
POSTGRES_DBS="vega0,vega1,vega2,vega3,vega4,vega5,vega6,vega7,vega8,vega9,vega10,vega11,vega12,vega13,vega14,vega15,vega16,vega17,vega18,vega19,vega20,vega21,vega22,vega23,vega24,vega25"
}
env = {}
static_port {
value = 5232