Compare commits

...
61 changed files with 514 additions and 381 deletions

No files matched your search

@@ -10,7 +10,7 @@ import {
addDecimalsFormatNumber,
formatNumber,
removePaginationWrapper,
suitableForSyntaxHighlighter,
validForSyntaxHighlighter,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { RouteTitle } from '../../components/route-title';
@@ -134,7 +134,7 @@ export const NetworkParameterRow = ({
}: {
row: { key: string; value: string };
}) => {
const isSyntaxRow = suitableForSyntaxHighlighter(value);
const isSyntaxRow = validForSyntaxHighlighter(value);
useDocumentTitle(['Network Parameters']);
return (
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useForm } from 'react-hook-form';
import { suitableForSyntaxHighlighter } from '@vegaprotocol/utils';
import { validForSyntaxHighlighter } from '@vegaprotocol/utils';
import { useNetworkParams } from '@vegaprotocol/network-parameters';
import {
getClosingTimestamp,
@@ -46,7 +46,7 @@ const SelectedNetworkParamCurrentValue = ({
<div className="mb-4">
<p className="text-sm text-white">{t('CurrentValue')}</p>
{suitableForSyntaxHighlighter(value) ? (
{validForSyntaxHighlighter(value) ? (
<SyntaxHighlighter data={JSON.parse(value)} />
) : (
<Input
@@ -8,7 +8,7 @@ import {
doesValueEquateToParam,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { useValidateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/react-helpers';
import {
NetworkParams,
useNetworkParams,
@@ -7,7 +7,7 @@ import {
doesValueEquateToParam,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { useValidateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/react-helpers';
import {
NetworkParams,
useNetworkParams,
@@ -14,7 +14,7 @@ import {
RoundedWrapper,
TextArea,
} from '@vegaprotocol/ui-toolkit';
import { useValidateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/react-helpers';
import {
NetworkParams,
useNetworkParams,
@@ -7,7 +7,7 @@ import {
doesValueEquateToParam,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { useValidateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/react-helpers';
import {
NetworkParams,
useNetworkParams,
@@ -8,7 +8,7 @@ import {
useProposalSubmit,
} from '@vegaprotocol/proposals';
import { useEnvironment, DocsLinks } from '@vegaprotocol/environment';
import { useValidateJson } from '@vegaprotocol/utils';
import { useValidateJson } from '@vegaprotocol/react-helpers';
import {
NetworkParams,
useNetworkParams,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 547 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

-22
View File
@@ -1,22 +0,0 @@
{
"name": "Vega Protocol - Trading",
"short_name": "Console",
"description": "Vega Protocol - Trading dApp",
"start_url": "/",
"display": "standalone",
"orientation": "portrait",
"theme_color": "#000000",
"background_color": "#ffffff",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
}
]
}
@@ -9,7 +9,7 @@ import {
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { URL_REGEX, isValidVegaPublicKey } from '@vegaprotocol/utils';
import { URL_REGEX, validVegaPublicKey } from '@vegaprotocol/utils';
import { type useReferralSetTransaction } from '../../lib/hooks/use-referral-set-transaction';
import { useT } from '../../lib/use-t';
@@ -217,9 +217,7 @@ export const TeamForm = ({
validate: {
allowList: (value) => {
const publicKeys = parseAllowListText(value);
if (
publicKeys.every((pk) => isValidVegaPublicKey(pk))
) {
if (publicKeys.every((pk) => validVegaPublicKey(pk))) {
return true;
}
return t('Invalid public key found in allow list');
@@ -2,12 +2,11 @@ import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
import { DocsLinks, useEnvironment } from '@vegaprotocol/environment';
import { ButtonLink, ExternalLink, Link } from '@vegaprotocol/ui-toolkit';
import type { Market } from '@vegaprotocol/markets';
import { addDecimalsFormatNumber, fromNanoSeconds } from '@vegaprotocol/utils';
import {
addDecimalsFormatNumber,
fromNanoSeconds,
getExpiryDate,
useMarketExpiryDate,
getMarketExpiryDate,
} from '@vegaprotocol/utils';
} from '@vegaprotocol/react-helpers';
import {
Last24hPriceChange,
Last24hVolume,
@@ -264,12 +263,13 @@ export const FundingCountdown = ({ marketId }: { marketId: string }) => {
};
const ExpiryLabel = ({ market }: ExpiryLabelProps) => {
const expiryDate = useMarketExpiryDate(
market.tradableInstrument.instrument.metadata.tags,
market.marketTimestamps.close,
market.state
);
const content = market.tradableInstrument.instrument.metadata.tags
? getExpiryDate(
market.tradableInstrument.instrument.metadata.tags,
market.marketTimestamps.close,
market.state
)
? expiryDate
: '-';
return <div data-testid="trading-expiry">{content}</div>;
};
+2 -4
View File
@@ -11,10 +11,8 @@ import { useMemo } from 'react';
import type { Asset } from '@vegaprotocol/types';
import type { ProductType } from '@vegaprotocol/types';
import { MarketState, MarketStateMapping } from '@vegaprotocol/types';
import {
addDecimalsFormatNumber,
getMarketExpiryDate,
} from '@vegaprotocol/utils';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { getMarketExpiryDate } from '@vegaprotocol/react-helpers';
import { closedMarketsWithDataProvider, getAsset } from '@vegaprotocol/markets';
import type { DataSourceFilterFragment } from '@vegaprotocol/markets';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
@@ -170,6 +170,9 @@ const cacheConfig: InMemoryCacheConfig = {
Fees: {
keyFields: false,
},
PartyProfile: {
keyFields: ['partyId'],
},
// The folling types are cached by the data provider and not by apollo
PositionUpdate: {
keyFields: false,
@@ -7,11 +7,8 @@ import {
useSuccessorMarket,
type Market,
} from '@vegaprotocol/markets';
import {
addDecimalsFormatNumber,
getMarketExpiryDate,
isNumeric,
} from '@vegaprotocol/utils';
import { addDecimalsFormatNumber, isNumeric } from '@vegaprotocol/utils';
import { getMarketExpiryDate } from '@vegaprotocol/react-helpers';
import { useT, ns } from '../../lib/use-t';
import { Links } from '../../lib/links';
+40 -3
View File
@@ -8,6 +8,12 @@ import {
mockConfig,
MockedWalletProvider,
} from '@vegaprotocol/wallet-react/testing';
import { MockedProvider, type MockedResponse } from '@apollo/react-testing';
import {
PartyProfilesDocument,
type PartyProfilesQuery,
type PartyProfilesQueryVariables,
} from '../vega-wallet-connect-button/__generated__/PartyProfiles';
jest.mock('@vegaprotocol/proposals', () => ({
ProtocolUpgradeCountdown: () => null,
@@ -24,15 +30,45 @@ describe('Navbar', () => {
publicKey: '2'.repeat(64),
},
];
const key1Alias = 'key 1 alias';
const marketId = 'abc';
const navbarContent = 'navbar-menu-content';
const partyProfilesMock: MockedResponse<
PartyProfilesQuery,
PartyProfilesQueryVariables
> = {
request: {
query: PartyProfilesDocument,
variables: {
partyIds: mockKeys.map((k) => k.publicKey),
},
},
result: {
data: {
partiesProfilesConnection: {
edges: [
{
node: {
partyId: mockKeys[0].publicKey,
alias: key1Alias,
metadata: [],
},
},
],
},
},
},
};
const renderComponent = (initialEntries?: string[]) => {
return render(
<MemoryRouter initialEntries={initialEntries}>
<MockedWalletProvider>
<Navbar />
</MockedWalletProvider>
<MockedProvider mocks={[partyProfilesMock]}>
<MockedWalletProvider>
<Navbar />
</MockedWalletProvider>
</MockedProvider>
</MemoryRouter>
);
};
@@ -140,6 +176,7 @@ describe('Navbar', () => {
const activeKey = within(menu.getByTestId(/key-1+-mobile/));
expect(activeKey.getByText(mockKeys[0].name)).toBeInTheDocument();
expect(activeKey.getByTestId('icon-tick')).toBeInTheDocument();
expect(screen.getByText(key1Alias)).toBeInTheDocument();
const inactiveKey = within(menu.getByTestId(/key-2+-mobile/));
await userEvent.click(inactiveKey.getByText(mockKeys[1].name));
@@ -9,7 +9,7 @@ import {
import { useProfileDialogStore } from '../../stores/profile-dialog-store';
import { useForm } from 'react-hook-form';
import { useT } from '../../lib/use-t';
import { useRequired } from '@vegaprotocol/utils';
import { useRequired } from '@vegaprotocol/react-helpers';
import {
useSimpleTransaction,
type Status,
@@ -31,39 +31,27 @@ export const ProfileDialog = () => {
const pubKey = useProfileDialogStore((store) => store.pubKey);
const setOpen = useProfileDialogStore((store) => store.setOpen);
const { send, status, error, reset } = useSimpleTransaction({
onSuccess: () => {
refetch();
},
});
const profileEdge = data?.partiesProfilesConnection?.edges.find(
(e) => e.node.partyId === pubKey
);
const sendTx = (field: FormFields) => {
send({
updatePartyProfile: {
alias: field.alias,
metadata: [],
},
});
};
return (
<Dialog
open={open}
onChange={() => {
setOpen(undefined);
reset();
}}
title={t('Edit profile')}
>
<ProfileForm
<ProfileFormContainer
profile={profileEdge?.node}
status={status}
error={error}
onSubmit={sendTx}
onSuccess={() => {
refetch();
setTimeout(() => {
setOpen(undefined);
}, 1000);
}}
/>
</Dialog>
);
@@ -77,6 +65,32 @@ type Profile = NonNullable<
PartyProfilesQuery['partiesProfilesConnection']
>['edges'][number]['node'];
const ProfileFormContainer = ({
profile,
onSuccess,
}: {
profile: Profile | undefined;
onSuccess: () => void;
}) => {
const { send, status, error } = useSimpleTransaction({ onSuccess });
const sendTx = (field: FormFields) => {
send({
updatePartyProfile: {
alias: field.alias,
metadata: [],
},
});
};
return (
<ProfileForm
profile={profile}
status={status}
error={error}
onSubmit={sendTx}
/>
);
};
const ProfileForm = ({
profile,
onSubmit,
@@ -114,6 +128,14 @@ const ProfileForm = ({
const errorMessage = errors.alias?.message || error;
if (status === 'confirmed') {
return (
<p className="mt-2 mb-4 text-sm text-vega-green-600 dark:text-vega-green">
{t('Profile updated')}
</p>
);
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="mt-3">
<FormGroup label="Alias" labelFor="alias">
@@ -131,12 +153,6 @@ const ProfileForm = ({
</p>
</InputError>
)}
{status === 'confirmed' && (
<p className="mt-2 mb-4 text-sm text-success">
{t('Profile updated')}
</p>
)}
</FormGroup>
<TradingButton
type="submit"
@@ -94,6 +94,7 @@ export const VegaWalletConnectButton = ({
<KeypairRadioGroup
pubKey={pubKey}
pubKeys={pubKeys}
activeKey={activeKey?.publicKey}
onSelect={selectPubKey}
/>
<TradingDropdownSeparator />
@@ -138,15 +139,18 @@ export const VegaWalletConnectButton = ({
const KeypairRadioGroup = ({
pubKey,
pubKeys,
activeKey,
onSelect,
}: {
pubKey: string | undefined;
pubKeys: Key[];
activeKey: string | undefined;
onSelect: (pubKey: string) => void;
}) => {
const { data } = usePartyProfilesQuery({
variables: { partyIds: pubKeys.map((pk) => pk.publicKey) },
skip: pubKeys.length <= 0,
fetchPolicy: 'cache-and-network',
});
return (
@@ -156,14 +160,27 @@ const KeypairRadioGroup = ({
(e) => e.node.partyId === pk.publicKey
);
return (
<KeypairItem key={pk.publicKey} pk={pk} alias={profile?.node.alias} />
<KeypairItem
key={pk.publicKey}
pk={pk}
isActive={activeKey === pk.publicKey}
alias={profile?.node.alias}
/>
);
})}
</TradingDropdownRadioGroup>
);
};
const KeypairItem = ({ pk, alias }: { pk: Key; alias: string | undefined }) => {
const KeypairItem = ({
pk,
isActive,
alias,
}: {
pk: Key;
alias: string | undefined;
isActive: boolean;
}) => {
const t = useT();
const [copied, setCopied] = useCopyTimeout();
const setOpen = useProfileDialogStore((store) => store.setOpen);
@@ -194,8 +211,13 @@ const KeypairItem = ({ pk, alias }: { pk: Key; alias: string | undefined }) => {
data-testid={`key-${pk.publicKey}`}
>
<Tooltip description={t('Public facing key alias. Click to edit')}>
<button data-testid="alias" onClick={() => setOpen(pk.publicKey)}>
<button
data-testid="alias"
onClick={() => setOpen(pk.publicKey)}
className="flex items-center gap-1"
>
{alias ? alias : t('No alias')}
{isActive && <VegaIcon name={VegaIconNames.EDIT} />}
</button>
</Tooltip>
</div>
@@ -12,6 +12,8 @@ import CopyToClipboard from 'react-copy-to-clipboard';
import { ViewType, useSidebar } from '../sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
import { usePartyProfilesQuery } from '../vega-wallet-connect-button/__generated__/PartyProfiles';
import { useProfileDialogStore } from '../../stores/profile-dialog-store';
export const VegaWalletMenu = ({
setMenu,
@@ -23,6 +25,12 @@ export const VegaWalletMenu = ({
const currentRouteId = useGetCurrentRouteId();
const setViews = useSidebar((store) => store.setViews);
const { data } = usePartyProfilesQuery({
variables: { partyIds: pubKeys.map((pk) => pk.publicKey) },
skip: pubKeys.length <= 0,
fetchPolicy: 'cache-and-network',
});
const activeKey = useMemo(() => {
return pubKeys?.find((pk) => pk.publicKey === pubKey);
}, [pubKey, pubKeys]);
@@ -37,14 +45,21 @@ export const VegaWalletMenu = ({
return (
<div>
<div className="grow my-4" role="list">
{(pubKeys || []).map((pk) => (
<KeypairListItem
key={pk.publicKey}
pk={pk}
isActive={activeKey?.publicKey === pk.publicKey}
onSelectItem={onSelectItem}
/>
))}
{(pubKeys || []).map((pk) => {
const profile = data?.partiesProfilesConnection?.edges.find(
(e) => e.node.partyId === pk.publicKey
);
return (
<KeypairListItem
key={pk.publicKey}
pk={pk}
isActive={activeKey?.publicKey === pk.publicKey}
onSelectItem={onSelectItem}
alias={profile?.node.alias}
setMenu={setMenu}
/>
);
})}
</div>
<div className="flex flex-col gap-2 m-4">
@@ -72,18 +87,23 @@ export const VegaWalletMenu = ({
const KeypairListItem = ({
pk,
isActive,
alias,
onSelectItem,
setMenu,
}: {
pk: Key;
isActive: boolean;
alias: string | undefined;
onSelectItem: (pk: string) => void;
setMenu: (open: 'nav' | 'wallet' | null) => void;
}) => {
const t = useT();
const [copied, setCopied] = useCopyTimeout();
const setOpen = useProfileDialogStore((store) => store.setOpen);
return (
<div
className="flex flex-col w-full ml-4 mr-2 mb-4"
className="flex flex-col w-full px-4 mb-4"
data-testid={`key-${pk.publicKey}-mobile`}
>
<span className="flex gap-2 items-center mr-2">
@@ -106,6 +126,24 @@ const KeypairListItem = ({
</CopyToClipboard>
{copied && <span className="text-xs">{t('Copied')}</span>}
</span>
<span
className="flex gap-2 items-center"
data-testid={`key-${pk.publicKey}`}
>
<span className="truncate">{alias ? alias : t('No alias')}</span>
{isActive && (
<button
data-testid="alias"
onClick={() => {
setOpen(pk.publicKey);
setMenu(null);
}}
className="flex items-center gap-1"
>
<VegaIcon name={VegaIconNames.EDIT} />
</button>
)}
</span>
</div>
);
};
@@ -186,7 +186,7 @@ def test_reward_history(
def test_staking_reward(
setup_environment: Tuple[Page, str, str],
) -> None:
):
page, tDAI_market, tDAI_asset_id = setup_environment
expect(page.get_by_test_id("active-rewards-card")).to_have_count(2)
staking_reward_card = page.get_by_test_id("active-rewards-card").nth(1)
+29 -7
View File
@@ -4,11 +4,10 @@ export default function Document() {
return (
<>
<Head>
{/*
meta tags
- next advised against using _document for this, so they exist in our
- single page index.page.tsx
*/}
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no"
/>
{/* preload fonts */}
<link
@@ -18,15 +17,38 @@ export default function Document() {
type="font/woff"
/>
<link
rel="preload"
href="/AlphaLyrae.woff2"
as="font"
type="font/woff2"
/>
{/* icons */}
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="apple-touch-icon" content="/favicon.ico" />
<link
rel="apple-touch-icon"
sizes="180x180"
href="/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="/favicon-16x16.png"
/>
{/* scripts */}
<script src="/theme-setter.js" type="text/javascript" async />
{/* manifest */}
<link rel="manifest" href="/apps/trading/public/manifest.json" />
<link rel="manifest" href="/manifest.json" />
</Head>
<Html>
<body
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 281 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 15 KiB

+6 -6
View File
@@ -9,14 +9,14 @@
"background_color": "#ffffff",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "cover.png",
"type": "image/png",
"sizes": "192x192"
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
File renamed without changes.
+5 -3
View File
@@ -1,13 +1,15 @@
import sortBy from 'lodash/sortBy';
import {
useMaxSafe,
useRequired,
useVegaPublicKey,
addDecimal,
toBigNum,
removeDecimal,
addDecimalsFormatNumber,
} from '@vegaprotocol/utils';
import {
useMaxSafe,
useRequired,
useVegaPublicKey,
} from '@vegaprotocol/react-helpers';
import { useT } from './use-t';
import {
TradingFormGroup,
@@ -1,7 +1,8 @@
import { Controller, type Control } from 'react-hook-form';
import type { Market } from '@vegaprotocol/markets';
import type { OrderFormValues } from '../../hooks/use-form-values';
import { determinePriceStep, useValidateAmount } from '@vegaprotocol/utils';
import { determinePriceStep } from '@vegaprotocol/utils';
import { useValidateAmount } from '@vegaprotocol/react-helpers';
import {
TradingFormGroup,
Tooltip,
@@ -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 { useValidateAmount } from '@vegaprotocol/utils';
import { useValidateAmount } from '@vegaprotocol/react-helpers';
import {
TradingFormGroup,
TradingInput,
@@ -8,8 +8,8 @@ import {
formatForInput,
formatValue,
removeDecimal,
useValidateAmount,
} from '@vegaprotocol/utils';
import { useValidateAmount } from '@vegaprotocol/react-helpers';
import { type Control, type UseFormWatch } from 'react-hook-form';
import { useForm, Controller, useController } from 'react-hook-form';
import * as Schema from '@vegaprotocol/types';
@@ -31,10 +31,10 @@ import { useOpenVolume } from '@vegaprotocol/positions';
import {
toBigNum,
removeDecimal,
useValidateAmount,
formatForInput,
formatValue,
} from '@vegaprotocol/utils';
import { useValidateAmount } from '@vegaprotocol/react-helpers';
import { activeOrdersProvider } from '@vegaprotocol/orders';
import {
getAsset,
+7 -5
View File
@@ -1,16 +1,18 @@
import type { Asset, AssetFieldsFragment } from '@vegaprotocol/assets';
import { AssetOption } from '@vegaprotocol/assets';
import {
addDecimal,
isAssetTypeERC20,
formatNumber,
} from '@vegaprotocol/utils';
import {
useLocalStorage,
useEthereumAddress,
useRequired,
useVegaPublicKey,
useMinSafe,
useMaxSafe,
addDecimal,
isAssetTypeERC20,
formatNumber,
} from '@vegaprotocol/utils';
import { useLocalStorage } from '@vegaprotocol/react-helpers';
} from '@vegaprotocol/react-helpers';
import {
TradingFormGroup,
TradingInput,
+2
View File
@@ -16,6 +16,7 @@ import en_markets from './locales/en/markets.json';
import en_web3 from './locales/en/web3.json';
import en_proposals from './locales/en/proposals.json';
import en_positions from './locales/en/positions.json';
import en_react_helpers from './locales/en/react-helpers.json';
import en_trades from './locales/en/trading.json';
import en_ui_toolkit from './locales/en/ui-toolkit.json';
import en_wallet from './locales/en/wallet.json';
@@ -39,6 +40,7 @@ export const locales = {
web3: en_web3,
positions: en_positions,
proposals: en_proposals,
react_helpers: en_react_helpers,
trades: en_trades,
'ui-toolkit': en_ui_toolkit,
wallet: en_wallet,
@@ -27,8 +27,8 @@ import {
formatNumber,
formatNumberPercentage,
getDateTimeFormat,
getMarketExpiryDateFormatted,
} from '@vegaprotocol/utils';
import { getMarketExpiryDateFormatted } from '@vegaprotocol/react-helpers';
import type { Get } from 'type-fest';
import { MarketInfoTable } from './info-key-value-table';
import type {
@@ -3,10 +3,10 @@ import {
getDateTimeFormat,
addDecimal,
addDecimalsFormatNumber,
useValidateAmount,
determinePriceStep,
determineSizeStep,
} from '@vegaprotocol/utils';
import { useValidateAmount } from '@vegaprotocol/react-helpers';
import { Size } from '@vegaprotocol/datagrid';
import * as Schema from '@vegaprotocol/types';
import {
@@ -3,8 +3,8 @@ import {
getDateTimeFormat,
isNumeric,
toBigNum,
useFormatTrigger,
} from '@vegaprotocol/utils';
import { useFormatTrigger } from '@vegaprotocol/react-helpers';
import * as Schema from '@vegaprotocol/types';
import {
ActionsDropdown,
+3
View File
@@ -12,5 +12,8 @@ export * from './use-theme-switcher';
export * from './use-storybook-theme-observer';
export * from './use-yesterday';
export * from './use-previous';
export * from './use-validate';
export * from './use-market-expiry-date';
export { useScript } from './use-script';
export { useUserAgent } from './use-user-agent';
export { useFormatTrigger } from './use-format-trigger';
@@ -1,7 +1,7 @@
import { type StopOrder, StopOrderTriggerDirection } from '@vegaprotocol/types';
import { addDecimalsFormatNumber } from './number';
import { useCallback } from 'react';
import { useT } from '../use-t';
import { type StopOrder, StopOrderTriggerDirection } from '@vegaprotocol/types';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { useT } from './use-t';
export const useFormatTrigger = () => {
const t = useT();
@@ -1,42 +1,10 @@
import { MarketState } from '@vegaprotocol/types';
import { getDateTimeFormat } from '@vegaprotocol/utils';
import { isValid, parseISO } from 'date-fns';
import { getDateTimeFormat } from './format';
import { useT } from './use-t';
export const getMarketExpiryDate = (
tags?: ReadonlyArray<string> | null
): Date | null => {
if (tags) {
const dateFound = tags.reduce<Date | null>((agg, tag) => {
const parsed = parseISO(
(tag.match(/^settlement.*:/) &&
tag
.split(':')
.filter((item, i) => i)
.join(':')) as string
);
if (isValid(parsed)) {
agg = parsed;
}
return agg;
}, null);
return dateFound;
}
return null;
};
export const getMarketExpiryDateFormatted = (
tags?: ReadonlyArray<string> | null
): string | null => {
if (tags) {
const dateFound = getMarketExpiryDate(tags);
return dateFound ? getDateTimeFormat().format(dateFound) : null;
}
return null;
};
export const getExpiryDate = (
tags: ReadonlyArray<string> | null,
export const useMarketExpiryDate = (
tags: ReadonlyArray<string> | null | undefined,
close: string | null,
state: MarketState
): string => {
@@ -67,3 +35,35 @@ export const getExpiryDate = (
}
return content;
};
export const getMarketExpiryDateFormatted = (
tags?: ReadonlyArray<string> | null
): string | null => {
if (tags) {
const dateFound = getMarketExpiryDate(tags);
return dateFound ? getDateTimeFormat().format(dateFound) : null;
}
return null;
};
export const getMarketExpiryDate = (
tags?: ReadonlyArray<string> | null
): Date | null => {
if (tags) {
const dateFound = tags.reduce<Date | null>((agg, tag) => {
const parsed = parseISO(
(tag.match(/^settlement.*:/) &&
tag
.split(':')
.filter((item, i) => i)
.join(':')) as string
);
if (isValid(parsed)) {
agg = parsed;
}
return agg;
}, null);
return dateFound;
}
return null;
};
@@ -1,3 +1,3 @@
import { useTranslation } from 'react-i18next';
export const ns = 'utils';
export const ns = 'react-helpers';
export const useT = () => useTranslation(ns).t;
@@ -0,0 +1,121 @@
import { useCallback } from 'react';
import BigNumber from 'bignumber.js';
import * as utils from '@vegaprotocol/utils';
import { useT } from './use-t';
export const useRequired = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!utils.validRequired(value)) {
return t('Required');
}
return true;
},
[t]
);
};
export const useEthereumAddress = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!utils.validEthAddress(value)) {
return t('Invalid Ethereum address');
}
return true;
},
[t]
);
};
export const useVegaPublicKey = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!utils.validVegaPublicKey(value)) {
return t('Invalid Vega key');
}
return true;
},
[t]
);
};
export const useMinSafe = () => {
const t = useT();
return useCallback(
(min: BigNumber) => (value: string) => {
if (utils.validMinSafe(value, min)) {
return t('Value is below minimum');
}
return true;
},
[t]
);
};
export const useMaxSafe = () => {
const t = useT();
return useCallback(
(max: BigNumber) => (value: string) => {
if (utils.validMaxSafe(value, max)) {
return t('Value is above maximum');
}
return true;
},
[t]
);
};
export const useValidateJson = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!utils.validJSON(value)) {
return t('Must be valid JSON');
}
return true;
},
[t]
);
};
export const useValidateUrl = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!utils.validUrl(value)) {
return t('Invalid URL');
}
return true;
},
[t]
);
};
/** Used in deal ticket price/size amounts */
export const useValidateAmount = () => {
const t = useT();
return useCallback(
(step: number | string, field: string) => {
return (value?: string) => {
if (!utils.validStep(step, value)) {
if (new BigNumber(step).isEqualTo(1)) {
return t('{{field}} must be whole numbers for this market', {
field,
step,
});
}
return t('{{field}} must be a multiple of {{step}} for this market', {
field,
step,
});
}
return true;
};
},
[t]
);
};
+2 -1
View File
@@ -17,7 +17,8 @@ import {
type SymbolQuery,
type SymbolQueryVariables,
} from './__generated__/Symbol';
import { getMarketExpiryDate, toBigNum } from '@vegaprotocol/utils';
import { toBigNum } from '@vegaprotocol/utils';
import { getMarketExpiryDate } from '@vegaprotocol/react-helpers';
import {
type IBasicDataFeed,
type DatafeedConfiguration,
+6 -4
View File
@@ -1,6 +1,6 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*", "__generated__"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
@@ -9,16 +9,18 @@
"error",
{
"paths": [
"error",
"@apollo/client",
"@ethersproject",
"@vegaprotocol/data-provider",
"ag-grid-react",
"ag-grid-community",
"ethers",
"graphql",
"graphql-tag",
"graphql-ws",
"ethers",
"@ethersproject"
"react",
"react-dom",
"react-i18next"
],
"patterns": ["@sentry/*"]
}
-4
View File
@@ -7,10 +7,6 @@
"date-fns": "^2.28.0",
"lodash": "^4.17.21"
},
"peerDependencies": {
"react": "18.2.0",
"react-i18next": "13.5.0"
},
"type": "module",
"module": "./index.js"
}
-1
View File
@@ -7,7 +7,6 @@ export * from './lib/helpers';
export * from './lib/is-asset-erc20';
export * from './lib/is-valid-url';
export * from './lib/local-storage';
export * from './lib/markets';
export * from './lib/price-change';
export * from './lib/remove-0x';
export * from './lib/remove-pagination-wrapper';
-1
View File
@@ -3,5 +3,4 @@ export * from './number';
export * from './range';
export * from './size';
export * from './strings';
export * from './trigger';
export * from './ether';
+47 -21
View File
@@ -1,40 +1,66 @@
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';
import { validEthAddress, validVegaPublicKey, validStep } from './common';
it('validEthAddress', () => {
const validAddress = '0x72c22822A19D20DE7e426fB84aa047399Ddd8853';
expect(ethereumAddress(validAddress)).toEqual(true);
expect(validEthAddress(validAddress)).toEqual(true);
const invalidChars = '0xzzc22822A19D20DE7e426fB84aa047399Ddd8853';
expect(ethereumAddress(invalidChars)).toEqual(errorMessage);
expect(validEthAddress(invalidChars)).toEqual(false);
const tooManyChars = '0x72c22822A19D20DE7e426fB84aa047399Ddd88531111111';
expect(ethereumAddress(tooManyChars)).toEqual(errorMessage);
expect(validEthAddress(tooManyChars)).toEqual(false);
const no0x = '1x72c22822A19D20DE7e426fB84aa047399Ddd8853';
expect(ethereumAddress(no0x)).toEqual(errorMessage);
expect(validEthAddress(no0x)).toEqual(false);
});
it('vegaPublicKey', () => {
const result = renderHook(useVegaPublicKey);
const vegaPublicKey = result.result.current;
const errorMessage = 'Invalid Vega key';
it('validVegaPublicKey', () => {
const validKey =
'70d14a321e02e71992fd115563df765000ccc4775cbe71a0e2f9ff5a3b9dc680';
expect(vegaPublicKey(validKey)).toEqual(true);
expect(validVegaPublicKey(validKey)).toEqual(true);
const invalidChars =
'zzz14a321e02e71992fd115563df765000ccc4775cbe71a0e2f9ff5a3b9dc680';
expect(vegaPublicKey(invalidChars)).toEqual(errorMessage);
expect(validVegaPublicKey(invalidChars)).toEqual(false);
const tooManyChars =
'70d14a321e02e71992fd115563df765000ccc4775cbe71a0e2f9ff5a3b9dc680111111';
expect(vegaPublicKey(tooManyChars)).toEqual(errorMessage);
expect(validVegaPublicKey(tooManyChars)).toEqual(false);
});
describe('validateAgainstStep', () => {
it('fails when step is an empty string', () => {
expect(validStep('', '1234')).toEqual(false);
});
it.each([
[0, 0],
[1234567890, 0],
[0.03, 0.03],
[0.09, 0.03],
[0.27, 0.03],
[1, 1],
[123, 1],
[4, 2],
[8, 2],
])(
'checks whether given value (%s) IS a multiple of given step (%s)',
(value, step) => {
expect(validStep(step, value)).toEqual(true);
}
);
it.each([
[1, 2],
[0.1, 0.003],
[1.11, 0.1],
[123.1, 1],
[222, 221],
[NaN, 1],
])(
'checks whether given value (%s) IS NOT a multiple of given step (%s)',
(value, step) => {
expect(validStep(step, value)).toEqual(false);
}
);
});
+48 -91
View File
@@ -1,77 +1,52 @@
import BigNumber from 'bignumber.js';
import { useT } from '../use-t';
import { useCallback } from 'react';
export const useRequired = () => {
const t = useT();
return useCallback(
(value: string) => {
if (value === null || value === undefined || value === '') {
return t('Required');
}
return true;
},
[t]
);
};
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 validRequired = (value: string | number | undefined | null) => {
if (value === null || value === undefined || value === '') {
return false;
}
return true;
};
export const VEGA_ID_REGEX = /^[A-Fa-f0-9]{64}$/i;
export const isValidVegaPublicKey = (value: string) => {
export const validVegaPublicKey = (value: string) => {
return VEGA_ID_REGEX.test(value);
};
export const useVegaPublicKey = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!isValidVegaPublicKey(value)) {
return t('Invalid Vega key');
}
return true;
},
[t]
);
export const URL_REGEX =
/^(https?:\/\/)?([a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})+)(:[0-9]{1,5})?(\/[^\s]*)?$/;
export const validUrl = (value: string) => {
return URL_REGEX.test(value);
};
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 ETH_ADDRESS = /^0x[0-9a-fA-F]{40}$/i;
export const validEthAddress = (value: string) => {
return ETH_ADDRESS.test(value);
};
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 validMinSafe = (
value: string | number | BigNumber,
min: string | number | BigNumber
) => {
return new BigNumber(value).isLessThan(min);
};
export const suitableForSyntaxHighlighter = (str: string) => {
export const validMaxSafe = (
value: string | number | BigNumber,
max: string | number | BigNumber
) => {
return new BigNumber(value).isGreaterThan(max);
};
export const validJSON = (value: string) => {
try {
JSON.parse(value);
return true;
} catch (e) {
return false;
}
};
export const validForSyntaxHighlighter = (str: string) => {
try {
const test = JSON.parse(str);
return test && Object.keys(test).length > 0;
@@ -80,35 +55,17 @@ export const suitableForSyntaxHighlighter = (str: string) => {
}
};
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]
);
};
export const validStep = (step: string | number, input?: string | number) => {
const stepValue = new BigNumber(step);
if (stepValue.isNaN()) {
// unable to check if step is not a number
return false;
}
if (stepValue.isZero()) {
// every number is valid when step is zero
return true;
}
export const URL_REGEX =
/^(https?:\/\/)?([a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})+)(:[0-9]{1,5})?(\/[^\s]*)?$/;
const isValidUrl = (value: string) => {
return URL_REGEX.test(value);
};
export const useValidateUrl = () => {
const t = useT();
return useCallback(
(value: string) => {
if (!isValidUrl(value)) {
return t('Invalid URL');
}
return true;
},
[t]
);
const value = new BigNumber(input || '');
return value.modulo(stepValue).isZero();
};
-1
View File
@@ -1,2 +1 @@
export * from './common';
export * from './validate-amount';
@@ -1,38 +0,0 @@
import { validateAgainstStep } from './validate-amount';
describe('validateAgainstStep', () => {
it('fails when step is an empty string', () => {
expect(validateAgainstStep('', '1234')).toEqual(false);
});
it.each([
[0, 0],
[1234567890, 0],
[0.03, 0.03],
[0.09, 0.03],
[0.27, 0.03],
[1, 1],
[123, 1],
[4, 2],
[8, 2],
])(
'checks whether given value (%s) IS a multiple of given step (%s)',
(value, step) => {
expect(validateAgainstStep(step, value)).toEqual(true);
}
);
it.each([
[1, 2],
[0.1, 0.003],
[1.11, 0.1],
[123.1, 1],
[222, 221],
[NaN, 1],
])(
'checks whether given value (%s) IS NOT a multiple of given step (%s)',
(value, step) => {
expect(validateAgainstStep(step, value)).toEqual(false);
}
);
});
@@ -1,50 +0,0 @@
import { useCallback } from 'react';
import { useT } from '../use-t';
import BigNumber from 'bignumber.js';
export const useValidateAmount = () => {
const t = useT();
return useCallback(
(step: number | string, field: string) => {
return (value?: string) => {
const isValid = validateAgainstStep(step, value);
if (!isValid) {
if (new BigNumber(step).isEqualTo(1)) {
return t('{{field}} must be whole numbers for this market', {
field,
step,
});
}
return t('{{field}} must be a multiple of {{step}} for this market', {
field,
step,
});
}
return true;
};
},
[t]
);
};
const isMultipleOf = (value: BigNumber, multipleOf: BigNumber) =>
value.modulo(multipleOf).isZero();
export const validateAgainstStep = (
step: string | number,
input?: string | number
) => {
const stepValue = new BigNumber(step);
if (stepValue.isNaN()) {
// unable to check if step is not a number
return false;
}
if (stepValue.isZero()) {
// every number is valid when step is zero
return true;
}
const value = new BigNumber(input || '');
return isMultipleOf(value, stepValue);
};
@@ -1,6 +1,6 @@
import { type StoreApi } from 'zustand';
import { type Store, type Connector } from '../types';
import { isValidVegaPublicKey } from '@vegaprotocol/utils';
import { validVegaPublicKey } from '@vegaprotocol/utils';
import {
ConnectorError,
chainIdError,
@@ -40,7 +40,7 @@ export class ViewPartyConnector implements Connector {
throw userRejectedError();
}
if (!isValidVegaPublicKey(value)) {
if (!validVegaPublicKey(value)) {
throw connectError('invalid public key');
}
@@ -40,9 +40,9 @@ import {
formatNumber,
toBigNum,
truncateByChars,
useFormatTrigger,
HALFMAXGOINT64,
} from '@vegaprotocol/utils';
import { useFormatTrigger } from '@vegaprotocol/react-helpers';
import { useAssetsMapProvider } from '@vegaprotocol/assets';
import { useEthWithdrawApprovalsStore } from './use-ethereum-withdraw-approvals-store';
import { DApp, EXPLORER_TX, useLinks } from '@vegaprotocol/environment';
+5 -3
View File
@@ -1,13 +1,15 @@
import type { Asset } from '@vegaprotocol/assets';
import { AssetOption } from '@vegaprotocol/assets';
import {
useEthereumAddress,
useRequired,
useMinSafe,
removeDecimal,
isAssetTypeERC20,
formatNumber,
} from '@vegaprotocol/utils';
import {
useEthereumAddress,
useRequired,
useMinSafe,
} from '@vegaprotocol/react-helpers';
import { useLocalStorage } from '@vegaprotocol/react-helpers';
import {
TradingFormGroup,