Compare commits

..
50 changed files with 528 additions and 269 deletions
@@ -8,7 +8,7 @@ import {
doesValueEquateToParam,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { validateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/utils';
import {
NetworkParams,
useNetworkParams,
@@ -41,6 +41,7 @@ export interface NewAssetProposalFormFields {
const DOCS_LINK = '/new-asset-proposal';
export const ProposeNewAsset = () => {
const validateJson = useValidateJson();
const {
params,
loading: networkParamsLoading,
@@ -7,7 +7,7 @@ import {
doesValueEquateToParam,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { validateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/utils';
import {
NetworkParams,
useNetworkParams,
@@ -39,6 +39,7 @@ export interface NewMarketProposalFormFields {
const DOCS_LINK = '/new-market-proposal';
export const ProposeNewMarket = () => {
const validateJson = useValidateJson();
const {
params,
loading: networkParamsLoading,
@@ -14,7 +14,7 @@ import {
RoundedWrapper,
TextArea,
} from '@vegaprotocol/ui-toolkit';
import { validateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/utils';
import {
NetworkParams,
useNetworkParams,
@@ -31,6 +31,7 @@ export interface RawProposalFormFields {
}
export const ProposeRaw = () => {
const validateJson = useValidateJson();
const {
params,
loading: networkParamsLoading,
@@ -7,7 +7,7 @@ import {
doesValueEquateToParam,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { validateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/utils';
import {
NetworkParams,
useNetworkParams,
@@ -39,6 +39,7 @@ export interface UpdateAssetProposalFormFields {
const DOCS_LINK = '/update-asset-proposal';
export const ProposeUpdateAsset = () => {
const validateJson = useValidateJson();
const {
params,
loading: networkParamsLoading,
@@ -8,7 +8,7 @@ import {
useProposalSubmit,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { validateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/utils';
import {
NetworkParams,
useNetworkParams,
@@ -53,6 +53,7 @@ export interface UpdateMarketProposalFormFields {
const DOCS_LINK = '/update-market-proposal';
export const ProposeUpdateMarket = () => {
const validateJson = useValidateJson();
const {
params,
loading: networkParamsLoading,
@@ -260,7 +261,7 @@ export const ProposeUpdateMarket = () => {
</FormGroup>
{selectedMarket && (
<div className="mt-[-20px] mb-6">
<div className="mb-6 mt-[-20px]">
<KeyValueTable data-testid="update-market-details">
<KeyValueTableRow>
{t('MarketName')}
+9 -6
View File
@@ -1,8 +1,8 @@
import sortBy from 'lodash/sortBy';
import {
maxSafe,
required,
vegaPublicKey,
useMaxSafe,
useRequired,
useVegaPublicKey,
addDecimal,
formatNumber,
addDecimalsFormatNumber,
@@ -67,6 +67,9 @@ export const TransferForm = ({
minQuantumMultiple,
}: TransferFormProps) => {
const t = useT();
const maxSafe = useMaxSafe();
const required = useRequired();
const vegaPublicKey = useVegaPublicKey();
const {
control,
register,
@@ -415,7 +418,7 @@ export const TransferForm = ({
{accountBalance && (
<button
type="button"
className="absolute top-0 right-0 ml-auto text-xs underline"
className="absolute right-0 top-0 ml-auto text-xs underline"
onClick={() =>
setValue('amount', parseFloat(accountBalance).toString(), {
shouldValidate: true,
@@ -491,7 +494,7 @@ export const TransferFee = ({
const totalValue = new BigNumber(transferAmount).plus(fee).toString();
return (
<div className="flex flex-col mb-4 text-xs gap-2">
<div className="mb-4 flex flex-col gap-2 text-xs">
<div className="flex flex-wrap items-center justify-between gap-1">
<Tooltip
description={t(
@@ -560,7 +563,7 @@ export const AddressField = ({
<button
type="button"
onClick={onChange}
className="absolute top-0 right-0 ml-auto text-xs underline"
className="absolute right-0 top-0 ml-auto text-xs underline"
>
{isInput ? t('Select from wallet') : t('Enter manually')}
</button>
@@ -1,7 +1,7 @@
import { Controller, type Control } from 'react-hook-form';
import type { Market } from '@vegaprotocol/markets';
import type { OrderFormValues } from '../../hooks/use-form-values';
import { toDecimal, validateAmount } from '@vegaprotocol/utils';
import { toDecimal, useValidateAmount } from '@vegaprotocol/utils';
import {
TradingFormGroup,
TradingInput,
@@ -28,6 +28,7 @@ export const DealTicketSizeIceberg = ({
peakSize,
}: DealTicketSizeIcebergProps) => {
const t = useT();
const validateAmount = useValidateAmount();
const sizeStep = toDecimal(market?.positionDecimalPlaces);
const renderPeakSizeError = () => {
@@ -9,7 +9,7 @@ import {
formatValue,
removeDecimal,
toDecimal,
validateAmount,
useValidateAmount,
} from '@vegaprotocol/utils';
import { type Control, type UseFormWatch } from 'react-hook-form';
import { useForm, Controller, useController } from 'react-hook-form';
@@ -36,7 +36,6 @@ import {
} from '@vegaprotocol/markets';
import { ExpirySelector } from './expiry-selector';
import { SideSelector } from './side-selector';
import { timeInForceLabel } from '@vegaprotocol/orders';
import {
NoWalletWarning,
REDUCE_ONLY_TOOLTIP,
@@ -110,6 +109,7 @@ const Trigger = ({
decimalPlaces: number;
}) => {
const t = useT();
const validateAmount = useValidateAmount();
const triggerType = watch(oco ? 'ocoTriggerType' : 'triggerType');
const triggerDirection = watch('triggerDirection');
const isPriceTrigger = triggerType === 'price';
@@ -342,6 +342,7 @@ const Size = ({
assetUnit?: string;
}) => {
const t = useT();
const validateAmount = useValidateAmount();
return (
<Controller
name={oco ? 'ocoSize' : 'size'}
@@ -402,6 +403,7 @@ const Price = ({
oco?: boolean;
}) => {
const t = useT();
const validateAmount = useValidateAmount();
if (watch(oco ? 'ocoType' : 'type') === Schema.OrderType.TYPE_MARKET) {
return null;
}
@@ -479,13 +481,13 @@ const TimeInForce = ({
key={Schema.OrderTimeInForce.TIME_IN_FORCE_IOC}
value={Schema.OrderTimeInForce.TIME_IN_FORCE_IOC}
>
{timeInForceLabel(Schema.OrderTimeInForce.TIME_IN_FORCE_IOC)}
{t(Schema.OrderTimeInForce.TIME_IN_FORCE_IOC)}
</option>
<option
key={Schema.OrderTimeInForce.TIME_IN_FORCE_FOK}
value={Schema.OrderTimeInForce.TIME_IN_FORCE_FOK}
>
{timeInForceLabel(Schema.OrderTimeInForce.TIME_IN_FORCE_FOK)}
{t(Schema.OrderTimeInForce.TIME_IN_FORCE_FOK)}
</option>
</Select>
</FormGroup>
@@ -1181,7 +1183,9 @@ export const StopOrder = ({ market, marketPrice, submit }: StopOrderProps) => {
testId={'stop-order-warning-limit'}
message={t(
'There is a limit of {{maxNumberOfOrders}} active stop orders per market. Orders submitted above the limit will be immediately rejected.',
{ maxNumberOfOrders: MAX_NUMBER_OF_ACTIVE_STOP_ORDERS.toString() }
{
maxNumberOfOrders: MAX_NUMBER_OF_ACTIVE_STOP_ORDERS.toString(),
}
)}
/>
</div>
@@ -495,12 +495,15 @@ describe('DealTicket', () => {
Array.from(screen.getByTestId('order-tif').children).map(
(o) => o.textContent
)
).toEqual(['Fill or Kill (FOK)', 'Immediate or Cancel (IOC)']);
).toEqual([
Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC,
]);
// IOC should be default
// 7002-SORD-030
expect(screen.getByTestId('order-tif')).toHaveDisplayValue(
'Immediate or Cancel (IOC)'
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
// Select FOK - FOK should be selected
@@ -509,7 +512,7 @@ describe('DealTicket', () => {
Schema.OrderTimeInForce.TIME_IN_FORCE_FOK
);
expect(screen.getByTestId('order-tif')).toHaveDisplayValue(
'Fill or Kill (FOK)'
Schema.OrderTimeInForce.TIME_IN_FORCE_FOK
);
// Switch to type limit order -> all TIF options should be shown
@@ -28,7 +28,7 @@ import { useOpenVolume } from '@vegaprotocol/positions';
import {
toBigNum,
removeDecimal,
validateAmount,
useValidateAmount,
toDecimal,
formatForInput,
formatValue,
@@ -140,6 +140,7 @@ export const DealTicket = ({
onDeposit,
}: DealTicketProps) => {
const t = useT();
const validateAmount = useValidateAmount();
const { pubKey, isReadOnly } = useVegaWallet();
const setType = useDealTicketFormValues((state) => state.setType);
const storedFormValues = useDealTicketFormValues(
@@ -6,7 +6,6 @@ import {
SimpleGrid,
} from '@vegaprotocol/ui-toolkit';
import * as Schema from '@vegaprotocol/types';
import { timeInForceLabel } from '@vegaprotocol/orders';
import { compileGridData } from '../trading-mode-tooltip';
import { MarketModeValidationType } from '../../constants';
import type { Market, StaticMarketData } from '@vegaprotocol/markets';
@@ -119,9 +118,7 @@ export const TimeInForceSelector = ({
hasError={!!errorMessage}
>
{options.map(([key, value]) => (
<option key={key} value={value}>
{timeInForceLabel(value)}
</option>
<TimeInForceOption key={key} value={value} />
))}
</TradingSelect>
{errorMessage && (
@@ -133,3 +130,8 @@ export const TimeInForceSelector = ({
</div>
);
};
const TimeInForceOption = ({ value }: { value: Schema.OrderTimeInForce }) => {
const t = useT();
return <option value={value}>{t(value)}</option>;
};
+12 -7
View File
@@ -1,11 +1,11 @@
import type { Asset, AssetFieldsFragment } from '@vegaprotocol/assets';
import { AssetOption } from '@vegaprotocol/assets';
import {
ethereumAddress,
required,
vegaPublicKey,
minSafe,
maxSafe,
useEthereumAddress,
useRequired,
useVegaPublicKey,
useMinSafe,
useMaxSafe,
addDecimal,
isAssetTypeERC20,
formatNumber,
@@ -85,6 +85,11 @@ export const DepositForm = ({
isFaucetable,
}: DepositFormProps) => {
const t = useT();
const ethereumAddress = useEthereumAddress();
const required = useRequired();
const vegaPublicKey = useVegaPublicKey();
const minSafe = useMinSafe();
const maxSafe = useMaxSafe();
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
const openDialog = useWeb3ConnectStore((store) => store.open);
const { isActive, account } = useWeb3React();
@@ -459,7 +464,7 @@ const UseButton = (props: UseButtonProps) => {
<button
{...props}
type="button"
className="absolute top-0 right-0 ml-auto text-sm underline"
className="absolute right-0 top-0 ml-auto text-sm underline"
/>
);
};
@@ -519,7 +524,7 @@ export const AddressField = ({
setIsInput((curr) => !curr);
onChange();
}}
className="absolute top-0 right-0 ml-auto text-sm underline"
className="absolute right-0 top-0 ml-auto text-sm underline"
data-testid="enter-pubkey-manually"
>
{isInput ? t('Select from wallet') : t('Enter manually')}
+2
View File
@@ -13,6 +13,7 @@ import en_trading from './locales/en/trading.json';
import en_markets from './locales/en/markets.json';
import en_web3 from './locales/en/web3.json';
import en_positions from './locales/en/positions.json';
export const locales = {
en: {
accounts: en_accounts,
@@ -28,5 +29,6 @@ export const locales = {
trading: en_trading,
markets: en_markets,
web3: en_web3,
positions: en_positions,
},
};
+7 -1
View File
@@ -128,5 +128,11 @@
"You need to connect your own wallet to start trading on this market": "You need to connect your own wallet to start trading on this market",
"You need to provide a minimum visible size": "You need to provide a minimum visible size",
"You need to provide a peak size": "You need to provide a peak size",
"You need to provide a size": "You need to provide a size"
"You need to provide a size": "You need to provide a size",
"TIME_IN_FORCE_FOK": "Fill or Kill (FOK)",
"TIME_IN_FORCE_GFA": "Good for Auction (GFA)",
"TIME_IN_FORCE_GFN": "Good for Normal (GFN)",
"TIME_IN_FORCE_GTC": "Good 'til Cancelled (GTC)",
"TIME_IN_FORCE_GTT": "Good 'til Time (GTT)",
"TIME_IN_FORCE_IOC": "Immediate or Cancel (IOC)"
}
@@ -0,0 +1,5 @@
{
"Last traded price": "Last traded price",
"No open orders": "No open orders",
"Spread": "Spread"
}
+49
View File
@@ -0,0 +1,49 @@
{
"{{tifLabel}}. Post Only": "{{tifLabel}}. Post Only",
"{{tifLabel}}. Reduce only": "{{tifLabel}}. Reduce only",
"Cancel": "Cancel",
"Cancel all": "Cancel all",
"Cancel order": "Cancel order",
"Cancels": "Cancels",
"Copy": "Copy",
"Copy order ID": "Copy order ID",
"Created": "Created",
"Edit order": "Edit order",
"Expires": "Expires",
"Expires at": "Expires at",
"Filled": "Filled",
"Iceberg order": "Iceberg order",
"Liquidity provision": "Liquidity provision",
"Market": "Market",
"MAX": "MAX",
"Minimum size": "Minimum size",
"No orders": "No orders",
"No stop orders": "No stop orders",
"One Cancels the Other": "One Cancels the Other",
"Order details": "Order details",
"Order ID": "Order ID",
"Peak size": "Peak size",
"Pegged": "Pegged",
"Post only": "Post only",
"Price": "Price",
"Reduce only": "Reduce only",
"Remaining": "Remaining",
"Reserved remaining": "Reserved remaining",
"Side": "Side",
"Size": "Size",
"Something went wrong: {{errorMessage}}": "Something went wrong: {{errorMessage}}",
"Status": "Status",
"Submit": "Submit",
"The maximum volume that can be traded at once. Must be less than the total size of the order.": "The maximum volume that can be traded at once. Must be less than the total size of the order.",
"The price cannot be negative": "The price cannot be negative",
"The size cannot be negative": "The size cannot be negative",
"Trigger": "Trigger",
"Type": "Type",
"Update": "Update",
"Updated": "Updated",
"View order details": "View order details",
"When the order trades and its size falls below this threshold, it will be reset to the peak size and moved to the back of the priority order. Must be less than or equal to peak size, and greater than 0.": "When the order trades and its size falls below this threshold, it will be reset to the peak size and moved to the back of the priority order. Must be less than or equal to peak size, and greater than 0.",
"Yes": "Yes",
"You need to provide a price": "You need to provide a price",
"You need to provide a size": "You need to provide a size"
}
+30
View File
@@ -0,0 +1,30 @@
{
"Best case": "Best case",
"Close position": "Close position",
"Entry / Mark": "Entry / Mark",
"Lifetime loss socialisation deductions: {{losses}}": "Lifetime loss socialisation deductions: {{losses}}",
"Maintained by network": "Maintained by network",
"Margin / Leverage": "Margin / Leverage",
"Market": "Market",
"No positions": "No positions",
"Profit or loss is realised whenever your position is reduced to zero and the margin is released back to your collateral balance. P&L excludes any fees paid.": "Profit or loss is realised whenever your position is reduced to zero and the margin is released back to your collateral balance. P&L excludes any fees paid.",
"Read more about loss socialisation": "Read more about loss socialisation",
"Read more about position resolution": "Read more about position resolution",
"Realised PNL": "Realised PNL",
"Realised PNL: {{value}}": "Realised PNL: {{value}}",
"Size / Notional": "Size / Notional",
"Status: {{status}}": "Status: {{status}}",
"The position was distressed, but could not be closed out - orders were removed from the book, and the open volume will be closed out once there is sufficient volume on the book.": "The position was distressed, but could not be closed out - orders were removed from the book, and the open volume will be closed out once there is sufficient volume on the book.",
"The position was distressed, but removing open orders from the book brought the margin level back to a point where the open position could be maintained.": "The position was distressed, but removing open orders from the book brought the margin level back to a point where the open position could be maintained.",
"Unrealised PNL": "Unrealised PNL",
"Unrealised profit is the current profit on your open position. Margin is still allocated to your position.": "Unrealised profit is the current profit on your open position. Margin is still allocated to your position.",
"Vega key": "Vega key",
"View settlement asset details": "View settlement asset details",
"Worst case": "Worst case",
"Worst case liquidation price": "Worst case liquidation price",
"You did not have enough {{assetSymbol}} collateral to meet the maintenance margin requirements for your position, so it was closed by the network.": "You did not have enough {{assetSymbol}} collateral to meet the maintenance margin requirements for your position, so it was closed by the network.",
"You received less {{assetSymbol}} in gains that you should have when the market moved in your favour. This occurred because one or more other trader(s) were closed out and did not have enough funds to cover their losses, and the market's insurance pool was empty.": "You received less {{assetSymbol}} in gains that you should have when the market moved in your favour. This occurred because one or more other trader(s) were closed out and did not have enough funds to cover their losses, and the market's insurance pool was empty.",
"Your open orders were cancelled.": "Your open orders were cancelled.",
"Your position is distressed.": "Your position is distressed.",
"Your position was closed.": "Your position was closed."
}
+15
View File
@@ -0,0 +1,15 @@
{
"Expired on {{date}}": "Expired on {{date}}",
"Not time-based": "Not time-based",
"Expired": "Expired",
"Mark": "Mark",
"Required": "Required",
"Invalid Ethereum address": "Invalid Ethereum address",
"Invalid Vega key": "Invalid Vega key",
"Value is below minimum": "Value is below minimum",
"Value is above maximum": "Value is above maximum",
"Must be valid JSON": "Must be valid JSON",
"{{field}} must be a multiple of {{step}} for this market": "{{field}} must be a multiple of {{step}} for this market",
"{{field}} must be whole numbers for this market": "{{field}} must be whole numbers for this market",
"{{field}} accepts up to {{decimals}} decimal places": "{{field}} accepts up to {{decimals}} decimal places"
}
@@ -0,0 +1,15 @@
export const useTranslation = () => ({
t: (label: string, replacements?: Record<string, string>) => {
const replace =
replacements?.replace && typeof replacements === 'object'
? replacements?.replace
: replacements;
let translatedLabel = replacements?.defaultValue || label;
if (typeof replace === 'object' && replace !== null) {
Object.keys(replace).forEach((key) => {
translatedLabel = translatedLabel.replace(`{{${key}}}`, replace[key]);
});
}
return translatedLabel;
},
});
+2 -1
View File
@@ -2,7 +2,6 @@ import { DepthChart } from 'pennant';
import throttle from 'lodash/throttle';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import { addDecimal, getNumberFormat } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { marketDepthProvider } from './market-depth-provider';
@@ -16,6 +15,7 @@ import {
} from './__generated__/MarketDepth';
import { type DepthChartProps } from 'pennant';
import { parseLevel, updateLevels } from './depth-chart-utils';
import { useT } from './use-t';
interface DepthChartManagerProps {
marketId: string;
@@ -39,6 +39,7 @@ const getMidPrice = (
type DepthData = Pick<DepthChartProps, 'data' | 'midPrice'>;
export const DepthChartContainer = ({ marketId }: DepthChartManagerProps) => {
const t = useT();
const { theme } = useThemeSwitcher();
const variables = useMemo(() => ({ marketId }), [marketId]);
const [depthData, setDepthData] = useState<DepthData | null>(null);
+3 -1
View File
@@ -1,7 +1,6 @@
import { useMemo, useRef, useState } from 'react';
import ReactVirtualizedAutoSizer from 'react-virtualized-auto-sizer';
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';
@@ -10,6 +9,7 @@ import { Splash, VegaIcon, VegaIconNames } from '@vegaprotocol/ui-toolkit';
import classNames from 'classnames';
import type { PriceLevelFieldsFragment } from './__generated__/MarketDepth';
import { OrderbookControls } from './orderbook-controls';
import { useT } from './use-t';
// Sets row height, will be used to calculate number of rows that can be
// displayed each side of the book without overflow
@@ -85,6 +85,7 @@ export const OrderbookMid = ({
bestAskPrice: string;
bestBidPrice: string;
}) => {
const t = useT();
const previousLastTradedPrice = usePrevious(lastTradedPrice);
const priceChangeRef = useRef<'up' | 'down' | 'none'>('none');
const spread = (BigInt(bestAskPrice) - BigInt(bestBidPrice)).toString();
@@ -153,6 +154,7 @@ export const Orderbook = ({
bids,
assetSymbol,
}: OrderbookProps) => {
const t = useT();
const [resolution, setResolution] = useState(1);
const groupedAsks = useMemo(() => {
+3
View File
@@ -0,0 +1,3 @@
import { useTranslation } from 'react-i18next';
export const useT = () => useTranslation('market-depth').t;
@@ -1,8 +1,8 @@
import { t } from '@vegaprotocol/i18n';
import { TradingButton } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import { useHasAmendableOrder } from '../../order-hooks';
import { useT } from '../../use-t';
export const OpenOrdersMenu = () => {
const { isReadOnly } = useVegaWallet();
@@ -28,8 +28,11 @@ export const OpenOrdersMenu = () => {
);
};
const CancelAllOrdersButton = ({ onClick }: { onClick: () => void }) => (
<TradingButton size="extra-small" onClick={onClick} data-testid="cancelAll">
{t('Cancel all')}
</TradingButton>
);
const CancelAllOrdersButton = ({ onClick }: { onClick: () => void }) => {
const t = useT();
return (
<TradingButton size="extra-small" onClick={onClick} data-testid="cancelAll">
{t('Cancel all')}
</TradingButton>
);
};
@@ -1,4 +1,3 @@
import { t } from '@vegaprotocol/i18n';
import { useCallback, useRef, useState, useEffect } from 'react';
import { type AgGridReact } from 'ag-grid-react';
import { Pagination, type useDataGridEvents } from '@vegaprotocol/datagrid';
@@ -12,6 +11,7 @@ import { type Order } from '../order-data-provider';
import { OrderViewDialog } from '../order-list/order-view-dialog';
import { OrderListTable } from '../order-list';
import { ordersWithMarketProvider } from '../order-data-provider/order-data-provider';
import { useT } from '../../use-t';
export enum Filter {
'Open' = 'Open',
@@ -38,6 +38,7 @@ export const OrderListManager = ({
gridProps,
noRowsMessage,
}: OrderListManagerProps) => {
const t = useT();
const gridRef = useRef<AgGridReact | null>(null);
const [editOrder, setEditOrder] = useState<Order | null>(null);
const [viewOrder, setViewOrder] = useState<Order | null>(null);
@@ -85,7 +86,13 @@ export const OrderListManager = ({
);
if (error) {
return <Splash>{t(`Something went wrong: ${error.message}`)}</Splash>;
return (
<Splash>
{t(`Something went wrong: {{errorMessage}}`, {
errorMessage: error.message,
})}
</Splash>
);
}
return (
@@ -1,4 +1,4 @@
import { act, render, screen, within } from '@testing-library/react';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { OrderEditDialog } from './order-edit-dialog';
@@ -7,16 +7,14 @@ import { limitOrder } from '../mocks';
describe('OrderEditDialog', () => {
it('must be warned (pre-submit) if the input price has too many digits after the decimal place for the market', async () => {
// 7003-MORD-013
await act(async () => {
render(
<OrderEditDialog
order={limitOrder}
onChange={jest.fn()}
isOpen={true}
onSubmit={jest.fn()}
/>
);
});
render(
<OrderEditDialog
order={limitOrder}
onChange={jest.fn()}
isOpen={true}
onSubmit={jest.fn()}
/>
);
const editOrder = await screen.findByTestId('edit-order');
const limitPrice = within(editOrder).getByLabelText('Price');
await userEvent.type(limitPrice, '0.111111');
@@ -3,9 +3,8 @@ import {
getDateTimeFormat,
addDecimal,
addDecimalsFormatNumber,
validateAmount,
useValidateAmount,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { Size } from '@vegaprotocol/datagrid';
import * as Schema from '@vegaprotocol/types';
import {
@@ -19,6 +18,7 @@ import {
} from '@vegaprotocol/ui-toolkit';
import { useForm } from 'react-hook-form';
import type { Order } from '../order-data-provider';
import { useT } from '../../use-t';
interface OrderEditDialogProps {
isOpen: boolean;
@@ -38,6 +38,8 @@ export const OrderEditDialog = ({
order,
onSubmit,
}: OrderEditDialogProps) => {
const t = useT();
const validateAmount = useValidateAmount();
const headerClassName = 'text-xs font-bold text-black dark:text-white';
const {
register,
@@ -60,7 +62,7 @@ export const OrderEditDialog = ({
title={t('Edit order')}
icon={<VegaIcon name={VegaIconNames.EDIT} />}
>
<div className="grid grid-cols-1 md:grid-cols-4 gap-8">
<div className="grid grid-cols-1 gap-8 md:grid-cols-4">
{order.market && (
<div className="md:col-span-2">
<p className={headerClassName}>{t(`Market`)}</p>
@@ -99,10 +101,10 @@ export const OrderEditDialog = ({
<form
onSubmit={handleSubmit(onSubmit)}
data-testid="edit-order"
className="w-full mt-4"
className="mt-4 w-full"
noValidate
>
<div className="flex flex-col md:flex-row gap-4">
<div className="flex flex-col gap-4 md:flex-row">
<TradingFormGroup
label={t('Price')}
labelFor="limitPrice"
@@ -6,7 +6,6 @@ import {
isNumeric,
toBigNum,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import * as Schema from '@vegaprotocol/types';
import {
ActionsDropdown,
@@ -30,10 +29,11 @@ import {
type VegaValueFormatterParams,
type VegaValueGetterParams,
} from '@vegaprotocol/datagrid';
import { AgGridReact } from 'ag-grid-react';
import { type AgGridReact } from 'ag-grid-react';
import { type Order } from '../order-data-provider';
import { Filter } from '../order-list-manager/order-list-manager';
import { type ColDef } from 'ag-grid-community';
import { useT } from '../../use-t';
const defaultColDef = {
resizable: true,
@@ -68,6 +68,7 @@ export const OrderListTable = memo<
},
ref
) => {
const t = useT();
const showAllActions = props.isReadOnly
? false
: filter === undefined || filter === Filter.Open
@@ -252,11 +253,14 @@ export const OrderListTable = memo<
}
const tifLabel = value ? Schema.OrderTimeInForceCode[value] : '';
const label = `${tifLabel}${
data?.postOnly ? t('. Post Only') : ''
}${data?.reduceOnly ? t('. Reduce only') : ''}`;
if (data?.postOnly) {
return t('{{tifLabel}}. Post Only', { tifLabel });
}
if (data?.reduceOnly) {
return t('{{tifLabel}}. Reduce only', { tifLabel });
}
return label;
return tifLabel;
},
},
{
@@ -336,6 +340,7 @@ export const OrderListTable = memo<
onOrderTypeClick,
props.isReadOnly,
showAllActions,
t,
]
);
@@ -2,7 +2,6 @@ import {
addDecimalsFormatNumber,
getDateTimeFormat,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { Size } from '@vegaprotocol/datagrid';
import * as Schema from '@vegaprotocol/types';
import {
@@ -19,6 +18,7 @@ import type { Order } from '../order-data-provider';
import CopyToClipboard from 'react-copy-to-clipboard';
import { useCopyTimeout } from '@vegaprotocol/react-helpers';
import classNames from 'classnames';
import { useT } from '../../use-t';
interface OrderViewDialogProps {
isOpen: boolean;
@@ -33,6 +33,7 @@ export const OrderViewDialog = ({
onChange,
onMarketClick,
}: OrderViewDialogProps) => {
const t = useT();
const [, setCopied] = useCopyTimeout();
return (
<Dialog open={isOpen} title={t('Order details')} onChange={onChange}>
@@ -184,21 +185,21 @@ export const OrderViewDialog = ({
<KeyValueTableRow key={'order-post-only'}>
<div data-testid={'order-post-only-label'}>{t('Post only')}</div>
<div data-testid={`order-post-only-value`}>
{order.postOnly ? t('Yes') : t('-')}
{order.postOnly ? t('Yes') : '-'}
</div>
</KeyValueTableRow>
<KeyValueTableRow key={'order-reduce-only'}>
<div data-testid={'order-reduce-only-label'}>{t('Reduce only')}</div>
<div data-testid={`order-reduce-only-value`}>
{order.reduceOnly ? t('Yes') : t('-')}
{order.reduceOnly ? t('Yes') : '-'}
</div>
</KeyValueTableRow>
<KeyValueTableRow key={'order-pegged'}>
<div data-testid={'order-pegged-label'}>{t('Pegged')}</div>
<div data-testid={`order-pegged-value`}>
{order.peggedOrder ? t('Yes') : t('-')}
{order.peggedOrder ? t('Yes') : '-'}
</div>
</KeyValueTableRow>
@@ -207,7 +208,7 @@ export const OrderViewDialog = ({
{t('Liquidity provision')}
</div>
<div data-testid={`order-liquidity-provision-value`}>
{order.liquidityProvision ? t('Yes') : t('-')}
{order.liquidityProvision ? t('Yes') : '-'}
</div>
</KeyValueTableRow>
</KeyValueTable>
@@ -217,7 +218,7 @@ export const OrderViewDialog = ({
{t('Iceberg order')}
</div>
<div data-testid={`order-iceberg-order-value`}>
{order.icebergOrder ? t('Yes') : t('-')}
{order.icebergOrder ? t('Yes') : '-'}
</div>
</KeyValueTableRow>
{order.icebergOrder && (
@@ -1,4 +1,3 @@
import { t } from '@vegaprotocol/i18n';
import { useCallback, useEffect, useState } from 'react';
import { StopOrdersTable } from '../stop-orders-table/stop-orders-table';
import { type useDataGridEvents } from '@vegaprotocol/datagrid';
@@ -11,6 +10,7 @@ import {
type StopOrdersQueryVariables,
} from '../order-data-provider';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import { useT } from '../../use-t';
export interface StopOrdersManagerProps {
partyId: string;
@@ -27,6 +27,7 @@ export const StopOrdersManager = ({
isReadOnly,
gridProps,
}: StopOrdersManagerProps) => {
const t = useT();
const create = useVegaTransactionStore((state) => state.create);
const [viewOrder, setViewOrder] = useState<Order | null>(null);
const variables: StopOrdersQueryVariables = {
@@ -191,6 +191,7 @@ describe('StopOrdersTable', () => {
expect(cells[i]).toHaveTextContent(expectedValue)
);
});
it('formats status column', async () => {
await act(async () => {
render(generateJsx({ rowData }));
@@ -260,14 +261,13 @@ describe('StopOrdersTable', () => {
await act(async () => {
render(generateJsx({ rowData, onView }));
});
const dropdownMenuButtons = screen.getByTestId('dropdown-menu');
dropdownMenuButtons.click();
await user.click(dropdownMenuButtons as HTMLButtonElement);
const menuItems = screen.getAllByRole('menuitem');
const button = screen.getByTestId('icon-kebab');
await user.click(button);
const menuItems = await screen.findAllByRole('menuitem');
expect(menuItems).toHaveLength(2);
expect(menuItems[0]).toHaveTextContent('Copy order ID');
expect(menuItems[1]).toHaveTextContent('View order details');
menuItems[1].click();
await user.click(menuItems[1]);
expect(onView).toBeCalled();
});
});
@@ -3,9 +3,8 @@ import {
getDateTimeFormat,
isNumeric,
toBigNum,
formatTrigger,
useFormatTrigger,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import * as Schema from '@vegaprotocol/types';
import {
ActionsDropdown,
@@ -35,6 +34,7 @@ import type {
import type { StopOrder } from '../order-data-provider/stop-orders-data-provider';
import type { ColDef } from 'ag-grid-community';
import type { Order } from '../order-data-provider';
import { useT } from '../../use-t';
const defaultColDef = {
resizable: true,
@@ -51,6 +51,8 @@ export type StopOrdersTableProps = TypedDataAgGrid<StopOrder> & {
export const StopOrdersTable = memo(
({ onCancel, onMarketClick, onView, ...props }: StopOrdersTableProps) => {
const t = useT();
const formatTrigger = useFormatTrigger();
const showAllActions = !props.isReadOnly;
const columnDefs: ColDef[] = useMemo(
() => [
@@ -176,7 +178,7 @@ export const StopOrdersTable = memo(
{data.ocoLinkId && (
<Pill
size="xxs"
className="uppercase ml-0.5"
className="ml-0.5 uppercase"
title={t('One Cancels the Other')}
>
OCO
@@ -281,7 +283,15 @@ export const StopOrdersTable = memo(
},
},
],
[onCancel, onMarketClick, onView, props.isReadOnly, showAllActions]
[
onCancel,
onMarketClick,
onView,
props.isReadOnly,
showAllActions,
t,
formatTrigger,
]
);
return (
-1
View File
@@ -1,3 +1,2 @@
export * from './components';
export * from './order-hooks';
export * from './utils';
+2
View File
@@ -0,0 +1,2 @@
import { useTranslation } from 'react-i18next';
export const useT = () => useTranslation('orders').t;
-28
View File
@@ -1,28 +0,0 @@
import { timeInForceLabel } from './utils';
import * as Types from '@vegaprotocol/types';
describe('utils', () => {
describe('timeInForceLabel', () => {
it('should return the correct label for time in force', () => {
expect(timeInForceLabel(Types.OrderTimeInForce.TIME_IN_FORCE_FOK)).toBe(
`Fill or Kill (FOK)`
);
expect(timeInForceLabel(Types.OrderTimeInForce.TIME_IN_FORCE_GTC)).toBe(
`Good 'til Cancelled (GTC)`
);
expect(timeInForceLabel(Types.OrderTimeInForce.TIME_IN_FORCE_IOC)).toBe(
`Immediate or Cancel (IOC)`
);
expect(timeInForceLabel(Types.OrderTimeInForce.TIME_IN_FORCE_GTT)).toBe(
`Good 'til Time (GTT)`
);
expect(timeInForceLabel(Types.OrderTimeInForce.TIME_IN_FORCE_GFA)).toBe(
`Good for Auction (GFA)`
);
expect(timeInForceLabel(Types.OrderTimeInForce.TIME_IN_FORCE_GFN)).toBe(
`Good for Normal (GFN)`
);
expect(timeInForceLabel('')).toBe('');
});
});
});
-22
View File
@@ -1,22 +0,0 @@
import { t } from '@vegaprotocol/i18n';
import * as Schema from '@vegaprotocol/types';
// More detail in https://docs.vega.xyz/mainnet/graphql/enums/order-time-in-force
export const timeInForceLabel = (tif: string) => {
switch (tif) {
case Schema.OrderTimeInForce.TIME_IN_FORCE_GTC:
return t(`Good 'til Cancelled (GTC)`);
case Schema.OrderTimeInForce.TIME_IN_FORCE_IOC:
return t('Immediate or Cancel (IOC)');
case Schema.OrderTimeInForce.TIME_IN_FORCE_FOK:
return t('Fill or Kill (FOK)');
case Schema.OrderTimeInForce.TIME_IN_FORCE_GTT:
return t(`Good 'til Time (GTT)`);
case Schema.OrderTimeInForce.TIME_IN_FORCE_GFN:
return t('Good for Normal (GFN)');
case Schema.OrderTimeInForce.TIME_IN_FORCE_GFA:
return t('Good for Auction (GFA)');
default:
return t(tif);
}
};
+4 -3
View File
@@ -1,7 +1,7 @@
import { Tooltip } from '@vegaprotocol/ui-toolkit';
import { useEstimatePositionQuery } from './__generated__/Positions';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useT } from '../use-t';
export const LiquidationPrice = ({
marketId,
@@ -14,6 +14,7 @@ export const LiquidationPrice = ({
collateralAvailable: string;
decimalPlaces: number;
}) => {
const t = useT();
const { data: currentData, previousData } = useEstimatePositionQuery({
variables: {
marketId,
@@ -43,11 +44,11 @@ export const LiquidationPrice = ({
<tbody>
<tr>
<th>{t('Worst case')}</th>
<td className="pl-2 font-mono text-right">{worstCase}</td>
<td className="pl-2 text-right font-mono">{worstCase}</td>
</tr>
<tr>
<th>{t('Best case')}</th>
<td className="pl-2 font-mono text-right">{bestCase}</td>
<td className="pl-2 text-right font-mono">{bestCase}</td>
</tr>
</tbody>
</table>
@@ -1,4 +1,3 @@
import { t } from '@vegaprotocol/i18n';
import {
ActionsDropdown,
TradingDropdownItem,
@@ -6,8 +5,10 @@ import {
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
import { useT } from '../use-t';
export const PositionActionsDropdown = ({ assetId }: { assetId: string }) => {
const t = useT();
const open = useAssetDetailsDialogStore((store) => store.open);
return (
+2 -1
View File
@@ -3,7 +3,6 @@ import { PositionsTable } from './positions-table';
import * as Schema from '@vegaprotocol/types';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import {
positionsMetricsProvider,
@@ -11,6 +10,7 @@ import {
} from './positions-data-providers';
import type { useDataGridEvents } from '@vegaprotocol/datagrid';
import { MAXGOINT64 } from '@vegaprotocol/utils';
import { useT } from '../use-t';
interface PositionsManagerProps {
partyIds: string[];
@@ -27,6 +27,7 @@ export const PositionsManager = ({
gridProps,
showClosed = false,
}: PositionsManagerProps) => {
const t = useT();
const { pubKeys, pubKey } = useVegaWallet();
const create = useVegaTransactionStore((store) => store.create);
const onClose = useCallback(
+32 -13
View File
@@ -28,7 +28,6 @@ import {
addDecimalsFormatNumber,
addDecimalsFormatNumberQuantum,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { type Position } from './positions-data-providers';
import {
MarketTradingMode,
@@ -38,6 +37,7 @@ import {
import { DocsLinks } from '@vegaprotocol/environment';
import { PositionActionsDropdown } from './position-actions-dropdown';
import { LiquidationPrice } from './liquidation-price';
import { useT } from '../use-t';
interface Props extends TypedDataAgGrid<Position> {
onClose?: (data: Position) => void;
@@ -81,6 +81,7 @@ export const PositionsTable = ({
pubKey,
...props
}: Props) => {
const t = useT();
return (
<AgGrid
overlayNoRowsTemplate={t('No positions')}
@@ -193,8 +194,8 @@ export const PositionsTable = ({
switch (args.data.status) {
case PositionStatus.POSITION_STATUS_CLOSED_OUT:
secondaryTooltip = t(
`You did not have enough %s collateral to meet the maintenance margin requirements for your position, so it was closed by the network.`,
args.data.assetSymbol
`You did not have enough {{assetSymbol}} collateral to meet the maintenance margin requirements for your position, so it was closed by the network.`,
{ assetSymbol: args.data.assetSymbol }
);
break;
case PositionStatus.POSITION_STATUS_ORDERS_CLOSED:
@@ -218,10 +219,12 @@ export const PositionsTable = ({
<p className="mb-2">{primaryTooltip}</p>
<p className="mb-2">{secondaryTooltip}</p>
<p className="mb-2">
{t(
'Status: %s',
PositionStatusMapping[args.data.status]
)}
{t('Status: {{status}}', {
nsSeparator: '*',
replace: {
status: PositionStatusMapping[args.data.status],
},
})}
</p>
{POSITION_RESOLUTION_LINK && (
<ExternalLink href={POSITION_RESOLUTION_LINK}>
@@ -386,18 +389,26 @@ export const PositionsTable = ({
value={
<>
<p className="mb-2">
{t('Realised PNL: %s', args.value)}
{t('Realised PNL: {{value}}', {
nsSeparator: '*',
replace: { value: args.value },
})}
</p>
<p className="mb-2">
{t(
'Lifetime loss socialisation deductions: %s',
lossesFormatted
'Lifetime loss socialisation deductions: {{losses}}',
{
nsSeparator: '*',
replace: {
losses: lossesFormatted,
},
}
)}
</p>
<p className="mb-2">
{t(
`You received less %s in gains that you should have when the market moved in your favour. This occurred because one or more other trader(s) were closed out and did not have enough funds to cover their losses, and the market's insurance pool was empty.`,
args.data.assetSymbol
`You received less {{assetSymbol}} in gains that you should have when the market moved in your favour. This occurred because one or more other trader(s) were closed out and did not have enough funds to cover their losses, and the market's insurance pool was empty.`,
{ assetSymbol: args.data.assetSymbol }
)}
</p>
{LOSS_SOCIALIZATION_LINK && (
@@ -481,7 +492,15 @@ export const PositionsTable = ({
return columnDefs.filter<ColDef>(
(colDef: ColDef | null): colDef is ColDef => colDef !== null
);
}, [isReadOnly, multipleKeys, onClose, onMarketClick, pubKey, pubKeys])}
}, [
isReadOnly,
multipleKeys,
onClose,
onMarketClick,
pubKey,
pubKeys,
t,
])}
{...props}
/>
);
+13
View File
@@ -1,4 +1,17 @@
import '@testing-library/jest-dom';
import ResizeObserver from 'resize-observer-polyfill';
import { locales } from '@vegaprotocol/i18n';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// Set up i18n instance so that components have the correct default
// en translations
i18n.use(initReactI18next).init({
// we init with resources
resources: locales,
fallbackLng: 'en',
ns: ['positions'],
defaultNS: 'positions',
});
global.ResizeObserver = ResizeObserver;
+3
View File
@@ -0,0 +1,3 @@
import { useTranslation } from 'react-i18next';
export const ns = 'positions';
export const useT = () => useTranslation(ns).t;
+14
View File
@@ -0,0 +1,14 @@
export const useTranslation = () => ({
t: (label: string, replacements?: Record<string, string>) => {
let translatedLabel = label;
if (typeof replacements === 'object' && replacements !== null) {
Object.keys(replacements).forEach((key) => {
translatedLabel = translatedLabel.replace(
`{{${key}}}`,
replacements[key]
);
});
}
return translatedLabel;
},
});
+33 -23
View File
@@ -1,27 +1,37 @@
import * as Schema from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
import { addDecimalsFormatNumber } from './number';
import { useCallback } from 'react';
import { useT } from '../use-t';
export const formatTrigger = (
data: Pick<Schema.StopOrder, 'trigger' | 'triggerDirection'> | undefined,
marketDecimalPlaces: number,
defaultValue = '-'
) => {
if (data && data?.trigger?.__typename === 'StopOrderPrice') {
return `${t('Mark')} ${
data?.triggerDirection ===
Schema.StopOrderTriggerDirection.TRIGGER_DIRECTION_FALLS_BELOW
? '<'
: '>'
} ${addDecimalsFormatNumber(data.trigger.price, marketDecimalPlaces)}`;
}
if (data && data?.trigger?.__typename === 'StopOrderTrailingPercentOffset') {
return `${t('Mark')} ${
data?.triggerDirection ===
Schema.StopOrderTriggerDirection.TRIGGER_DIRECTION_FALLS_BELOW
? '+'
: '-'
}${(Number(data?.trigger.trailingPercentOffset) * 100).toFixed(1)}%`;
}
return defaultValue;
export const useFormatTrigger = () => {
const t = useT();
return useCallback(
(
data: Pick<Schema.StopOrder, 'trigger' | 'triggerDirection'> | undefined,
marketDecimalPlaces: number,
defaultValue = '-'
) => {
if (data && data?.trigger?.__typename === 'StopOrderPrice') {
return `${t('Mark')} ${
data?.triggerDirection ===
Schema.StopOrderTriggerDirection.TRIGGER_DIRECTION_FALLS_BELOW
? '<'
: '>'
} ${addDecimalsFormatNumber(data.trigger.price, marketDecimalPlaces)}`;
}
if (
data &&
data?.trigger?.__typename === 'StopOrderTrailingPercentOffset'
) {
return `${t('Mark')} ${
data?.triggerDirection ===
Schema.StopOrderTriggerDirection.TRIGGER_DIRECTION_FALLS_BELOW
? '+'
: '-'
}${(Number(data?.trigger.trailingPercentOffset) * 100).toFixed(1)}%`;
}
return defaultValue;
},
[t]
);
};
+8 -3
View File
@@ -1,7 +1,7 @@
import { MarketState } from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
import { isValid, parseISO } from 'date-fns';
import { getDateTimeFormat } from './format';
import { useT } from './use-t';
export const getMarketExpiryDate = (
tags?: ReadonlyArray<string> | null
@@ -40,12 +40,15 @@ export const getExpiryDate = (
close: string | null,
state: MarketState
): string => {
const t = useT();
const metadataExpiryDate = getMarketExpiryDate(tags);
const marketTimestampCloseDate = close && new Date(close);
let content = null;
if (!metadataExpiryDate) {
content = marketTimestampCloseDate
? `Expired on ${getDateTimeFormat().format(marketTimestampCloseDate)}`
? t('Expired on {{date}}', {
date: getDateTimeFormat().format(marketTimestampCloseDate),
})
: t('Not time-based');
} else {
const isExpired =
@@ -54,7 +57,9 @@ export const getExpiryDate = (
state === MarketState.STATE_SETTLED);
if (isExpired) {
content = marketTimestampCloseDate
? `Expired on ${getDateTimeFormat().format(marketTimestampCloseDate)}`
? t('Expired on {{date}}', {
date: getDateTimeFormat().format(marketTimestampCloseDate),
})
: t('Expired');
} else {
content = getDateTimeFormat().format(metadataExpiryDate);
+3
View File
@@ -0,0 +1,3 @@
import { useTranslation } from 'react-i18next';
export const ns = 'utils';
export const useT = () => useTranslation(ns).t;
+8 -1
View File
@@ -1,6 +1,10 @@
import { ethereumAddress, vegaPublicKey } from './common';
import { renderHook } from '@testing-library/react';
import { useEthereumAddress, useVegaPublicKey } from './common';
it('ethereumAddress', () => {
const result = renderHook(useEthereumAddress);
const ethereumAddress = result.result.current;
const errorMessage = 'Invalid Ethereum address';
const validAddress = '0x72c22822A19D20DE7e426fB84aa047399Ddd8853';
@@ -17,6 +21,9 @@ it('ethereumAddress', () => {
});
it('vegaPublicKey', () => {
const result = renderHook(useVegaPublicKey);
const vegaPublicKey = result.result.current;
const errorMessage = 'Invalid Vega key';
const validKey =
+70 -33
View File
@@ -1,40 +1,71 @@
import BigNumber from 'bignumber.js';
import { t } from '@vegaprotocol/i18n';
import { useT } from '../use-t';
import { useCallback } from 'react';
export const required = (value: string) => {
if (value === null || value === undefined || value === '') {
return t('Required');
}
return true;
export const useRequired = () => {
const t = useT();
return useCallback(
(value: string) => {
if (value === null || value === undefined || value === '') {
return t('Required');
}
return true;
},
[t]
);
};
export const ethereumAddress = (value: string) => {
if (!/^0x[0-9a-fA-F]{40}$/i.test(value)) {
return t('Invalid Ethereum address');
}
return true;
export const useEthereumAddress = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!/^0x[0-9a-fA-F]{40}$/i.test(value)) {
return t('Invalid Ethereum address');
}
return true;
},
[t]
);
};
export const VEGA_ID_REGEX = /^[A-Fa-f0-9]{64}$/i;
export const vegaPublicKey = (value: string) => {
if (!VEGA_ID_REGEX.test(value)) {
return t('Invalid Vega key');
}
return true;
export const useVegaPublicKey = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!VEGA_ID_REGEX.test(value)) {
return t('Invalid Vega key');
}
return true;
},
[t]
);
};
export const minSafe = (min: BigNumber) => (value: string) => {
if (new BigNumber(value).isLessThan(min)) {
return t('Value is below minimum');
}
return true;
export const useMinSafe = () => {
const t = useT();
return useCallback(
(min: BigNumber) => (value: string) => {
if (new BigNumber(value).isLessThan(min)) {
return t('Value is below minimum');
}
return true;
},
[t]
);
};
export const maxSafe = (max: BigNumber) => (value: string) => {
if (new BigNumber(value).isGreaterThan(max)) {
return t('Value is above maximum');
}
return true;
export const useMaxSafe = () => {
const t = useT();
return useCallback(
(max: BigNumber) => (value: string) => {
if (new BigNumber(value).isGreaterThan(max)) {
return t('Value is above maximum');
}
return true;
},
[t]
);
};
export const suitableForSyntaxHighlighter = (str: string) => {
@@ -46,11 +77,17 @@ export const suitableForSyntaxHighlighter = (str: string) => {
}
};
export const validateJson = (value: string) => {
try {
JSON.parse(value);
return true;
} catch (e) {
return t('Must be valid JSON');
}
export const useValidateJson = () => {
const t = useT();
return useCallback(
(value: string) => {
try {
JSON.parse(value);
return true;
} catch (e) {
return t('Must be valid JSON');
}
},
[t]
);
};
+37 -19
View File
@@ -1,22 +1,40 @@
import { t } from '@vegaprotocol/i18n';
import { useCallback } from 'react';
import { useT } from '../use-t';
export const validateAmount = (step: number | string, field: string) => {
const [, stepDecimals = ''] = String(step).split('.');
export const useValidateAmount = () => {
const t = useT();
return useCallback(
(step: number | string, field: string) => {
const [, stepDecimals = ''] = String(step).split('.');
return (value?: string) => {
if (Number(step) > 1) {
if (Number(value) % Number(step) > 0) {
return t(`${field} must be a multiple of ${step} for this market`);
}
return true;
}
const [, valueDecimals = ''] = (value || '').split('.');
if (stepDecimals.length < valueDecimals.length) {
if (stepDecimals === '') {
return t(`${field} must be whole numbers for this market`);
}
return t(`${field} accepts up to ${stepDecimals.length} decimal places`);
}
return true;
};
return (value?: string) => {
if (Number(step) > 1) {
if (Number(value) % Number(step) > 0) {
return t(
'{{field}} must be a multiple of {{step}} for this market',
{
field,
step,
}
);
}
return true;
}
const [, valueDecimals = ''] = (value || '').split('.');
if (stepDecimals.length < valueDecimals.length) {
if (stepDecimals === '') {
return t('{{field}} must be whole numbers for this market', {
field,
});
}
return t('{{field}} accepts up to {{decimals}} decimal places', {
field,
decimals: stepDecimals.length,
});
}
return true;
};
},
[t]
);
};
@@ -40,7 +40,7 @@ import {
formatNumber,
toBigNum,
truncateByChars,
formatTrigger,
useFormatTrigger,
MAXGOINT64,
} from '@vegaprotocol/utils';
import { useAssetsMapProvider } from '@vegaprotocol/assets';
@@ -260,6 +260,7 @@ const SubmitStopOrderSetup = ({
triggerDirection: Schema.StopOrderTriggerDirection;
market: Market;
}) => {
const formatTrigger = useFormatTrigger();
if (!market || !stopOrderSetup) return null;
const { price, size, side } = stopOrderSetup.orderSubmission;
@@ -446,6 +447,7 @@ const CancelOrderDetails = ({
const CancelStopOrderDetails = ({ stopOrderId }: { stopOrderId: string }) => {
const t = useT();
const formatTrigger = useFormatTrigger();
const { data: orderById } = useStopOrderByIdQuery({
variables: { stopOrderId },
});
@@ -732,7 +734,7 @@ const VegaTxCompleteToastsContent = ({ tx }: VegaTxToastContentProps) => {
<p>{t('Your funds have been unlocked for withdrawal.')}</p>
{tx.txHash && (
<ExternalLink
className="block mb-[5px] break-all"
className="mb-[5px] block break-all"
href={explorerLink(EXPLORER_TX.replace(':hash', tx.txHash))}
rel="noreferrer"
>
+32 -37
View File
@@ -1,10 +1,10 @@
import type { Asset } from '@vegaprotocol/assets';
import { AssetOption } from '@vegaprotocol/assets';
import {
ethereumAddress,
minSafe,
useEthereumAddress,
useRequired,
useMinSafe,
removeDecimal,
required,
isAssetTypeERC20,
formatNumber,
} from '@vegaprotocol/utils';
@@ -23,7 +23,6 @@ import {
import { useWeb3React } from '@web3-react/core';
import BigNumber from 'bignumber.js';
import { useEffect, type ButtonHTMLAttributes } from 'react';
import type { ControllerRenderProps } from 'react-hook-form';
import { formatDistanceToNow } from 'date-fns';
import { useForm, Controller, useWatch } from 'react-hook-form';
import { WithdrawLimits } from './withdraw-limits';
@@ -112,6 +111,10 @@ export const WithdrawForm = ({
onSelectAsset,
submitWithdraw,
}: WithdrawFormProps) => {
const ethereumAddress = useEthereumAddress();
const required = useRequired();
const minSafe = useMinSafe();
const { account: address } = useWeb3React();
const {
register,
@@ -150,36 +153,6 @@ export const WithdrawForm = ({
trigger('to');
}, [address, setValue, trigger]);
const renderAssetsSelector = ({
field,
}: {
field: ControllerRenderProps<FormFields, 'asset'>;
}) => {
return (
<TradingRichSelect
data-testid="select-asset"
id="asset"
name="asset"
required
onValueChange={(value) => {
onSelectAsset(value);
field.onChange(value);
}}
placeholder={t('Please select an asset')}
value={selectedAsset?.id}
hasError={Boolean(errors.asset?.message)}
>
{assets.filter(isAssetTypeERC20).map((a) => (
<AssetOption
key={a.id}
asset={a}
balance={<AssetBalance asset={a} />}
/>
))}
</TradingRichSelect>
);
};
const showWithdrawDelayNotification =
Boolean(delay) &&
Boolean(selectedAsset) &&
@@ -189,7 +162,7 @@ export const WithdrawForm = ({
<>
<div className="mb-4 text-sm">
<p>{t('There are two steps required to make a withdrawal')}</p>
<ol className="pl-4 list-disc">
<ol className="list-disc pl-4">
<li>{t('Step 1 - Release funds from Vega')}</li>
<li>{t('Step 2 - Transfer funds to your Ethereum wallet')}</li>
</ol>
@@ -208,7 +181,29 @@ export const WithdrawForm = ({
required: (value) => !!selectedAsset || required(value),
},
}}
render={renderAssetsSelector}
render={({ field }) => (
<TradingRichSelect
data-testid="select-asset"
id="asset"
name="asset"
required
onValueChange={(value) => {
onSelectAsset(value);
field.onChange(value);
}}
placeholder={t('Please select an asset')}
value={selectedAsset?.id}
hasError={Boolean(errors.asset?.message)}
>
{assets.filter(isAssetTypeERC20).map((a) => (
<AssetOption
key={a.id}
asset={a}
balance={<AssetBalance asset={a} />}
/>
))}
</TradingRichSelect>
)}
/>
{errors.asset?.message && (
<TradingInputError intent="danger">
@@ -314,7 +309,7 @@ const UseButton = (props: UseButtonProps) => {
<button
{...props}
type="button"
className="absolute top-0 right-0 ml-auto text-sm underline"
className="absolute right-0 top-0 ml-auto text-sm underline"
/>
);
};