Compare commits

..
Author SHA1 Message Date
Ben 5ce2c117be chore(trading): black formatting and removed double fixtures (#5506) 2023-12-19 14:49:41 +00:00
Art 3beeb0140c feat(wallet): disconnect if wallet unreachable (#5501) 2023-12-18 10:39:18 +00:00
m.ray 4b208e90bf fix(trading): internal timestamp date unix formatting (#5505) 2023-12-14 15:10:17 +00:00
Bartłomiej Głownia ec837854cf chore(trading): avoid portfolio and market page re-rendering on sidebar view change (#5499) 2023-12-14 14:12:19 +00:00
Bartłomiej Głownia 8b94a75ba4 feat(positions): improve tooltips (#5481) 2023-12-13 14:36:57 +00:00
Ben 08c57b6759 chore(trading): run against local console (#5500) 2023-12-13 12:46:16 +00:00
Ben bb2184498f chore(trading): update vega version (#5498) 2023-12-13 11:16:52 +00:00
Bartłomiej Głownia 8b07ce3024 fix(trading): fix tabs covered by orderbook splash (#5497) 2023-12-13 09:10:54 +00:00
Bartłomiej Głownia 8a110584dd feat(trading): improve desposit and withraw asset selection (#5493) 2023-12-13 08:47:22 +00:00
Bartłomiej Głownia b82615a3d8 fix(trading): do not add candles if they are older than requested date range (#5484) 2023-12-13 08:06:02 +00:00
Matthew Russell f178b85846 feat(trading): trading view (#5348) 2023-12-12 17:33:41 -08:00
Bartłomiej Głownia 0796f2b31f feat(environment): users controlled feature flags (#5425) 2023-12-12 13:53:20 +01:00
dalebennett1992 67be224138 Merge pull request #5492 from vegaprotocol/test/referrals2
test: add referrals tests
2023-12-12 10:33:57 +00:00
dalebennett1992 51c426ef4b test: test ids 2023-12-12 10:16:47 +00:00
dalebennett1992 fa28d31ef3 test: add referrals tests 2023-12-12 10:15:20 +00:00
m.ray 201a586b05 chore(trading): enable close position (#5490) 2023-12-11 15:51:22 +00:00
m.ray 7d96d9bcd1 chore(trading): update env trading (#5478) 2023-12-08 15:44:55 +00:00
Art 345be81142 fix(trading): rewordings in referrals, qusd tooltip, onboarding (#5477) 2023-12-08 14:48:12 +00:00
141 changed files with 2988 additions and 800 deletions
+3
View File
@@ -1,5 +1,8 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Auto-format all files
yarn nx format:write
# Lint all staged files
yarn lint-staged
+3 -3
View File
@@ -1,8 +1,8 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Lint all staged files
yarn nx format:check
# Lint all staged files - this brings more value as pre-commit
# yarn nx format:check
# Test all projects with changes
yarn nx affected -t test --exclude trading
# yarn nx affected -t test --exclude trading
@@ -105,8 +105,6 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
yesLPPercentage,
yesTokens,
noTokens,
yesEquityLikeShareWeight,
noEquityLikeShareWeight,
totalEquityLikeShareWeight,
requiredMajorityPercentage,
requiredMajorityLPPercentage,
@@ -202,42 +200,17 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
<div className="flex items-center gap-1">
<span>{t('liquidityProviderVotesFor')}:</span>
<Tooltip
description={formatNumber(
yesEquityLikeShareWeight,
defaultDP
)}
description={
<span>{yesLPPercentage.toFixed(defaultDP)}%</span>
}
>
<button>
<CompactVotes number={yesEquityLikeShareWeight} />
</button>
<button>{yesLPPercentage.toFixed(0)}%</button>
</Tooltip>
<span>
(
<Tooltip
description={
<span>{yesLPPercentage.toFixed(defaultDP)}%</span>
}
>
<button>{yesLPPercentage.toFixed(0)}%</button>
</Tooltip>
)
</span>
</div>
<div className="flex items-center gap-1">
<span>{t('liquidityProviderVotesAgainst')}:</span>
<Tooltip
description={formatNumber(
noEquityLikeShareWeight,
defaultDP
)}
>
<button>
<CompactVotes number={noEquityLikeShareWeight} />
</button>
</Tooltip>
<span>
(
<Tooltip
description={
<span>{noLPPercentage.toFixed(defaultDP)}%</span>
@@ -245,7 +218,6 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
>
<button>{noLPPercentage.toFixed(0)}%</button>
</Tooltip>
)
</span>
</div>
</div>
@@ -282,13 +254,10 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
defaultDP
)}
>
<button>
<CompactVotes number={totalEquityLikeShareWeight} />
</button>
<span>
{totalEquityLikeShareWeight.times(100).toString()}%
</span>
</Tooltip>
<span>
({totalEquityLikeShareWeight.toFixed(defaultDP)}%)
</span>
</div>
</div>
</section>
@@ -81,12 +81,7 @@ export const useVoteInformation = ({
const yesPercentage = totalTokensVoted.isZero()
? new BigNumber(0)
: yesTokens.multipliedBy(100).dividedBy(totalTokensVoted);
const yesLPPercentage = totalEquityLikeShareWeight.isZero()
? new BigNumber(0)
: yesEquityLikeShareWeight
.multipliedBy(100)
.dividedBy(totalEquityLikeShareWeight);
const yesLPPercentage = yesEquityLikeShareWeight.multipliedBy(100);
const noPercentage = totalTokensVoted.isZero()
? new BigNumber(0)
+2 -3
View File
@@ -22,10 +22,9 @@ NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
NX_SUCCESSOR_MARKETS=true
NX_STOP_ORDERS=true
NX_ICEBERG_ORDERS=true
# NX_PRODUCT_PERPETUALS
NX_METAMASK_SNAPS=true
NX_REFERRALS=false
NX_REFERRALS=true
# NX_DISABLE_CLOSE_POSITION=false
NX_TENDERMINT_URL=https://be.vega.community
NX_TENDERMINT_WEBSOCKET_URL=wss://be.vega.community/websocket
NX_DISABLE_CLOSE_POSITION=true
+4 -1
View File
@@ -24,4 +24,7 @@ NX_STOP_ORDERS=true
NX_ICEBERG_ORDERS=true
# NX_PRODUCT_PERPETUALS
NX_METAMASK_SNAPS=true
NX_REFERRALS=true
NX_REFERRALS=true
NX_CHARTING_LIBRARY_PATH=https://assets.vega.community/trading-view-bundle/v0.0.1/
NX_CHARTING_LIBRARY_HASH=PDjWaqPFndDp+LCvqbKvntWriaqNzNpZ5i9R/BULzCg=
+3 -1
View File
@@ -23,9 +23,11 @@ NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
NX_SUCCESSOR_MARKETS=true
NX_STOP_ORDERS=true
NX_ICEBERG_ORDERS=true
# NX_PRODUCT_PERPETUALS
NX_METAMASK_SNAPS=true
NX_REFERRALS=true
NX_TENDERMINT_URL=https://tm.be.testnet.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.testnet.vega.xyz/websocket
NX_CHARTING_LIBRARY_PATH=https://assets.vega.community/trading-view-bundle/v0.0.1/
NX_CHARTING_LIBRARY_HASH=PDjWaqPFndDp+LCvqbKvntWriaqNzNpZ5i9R/BULzCg=
+1 -15
View File
@@ -9,8 +9,6 @@ import { TradeGrid } from './trade-grid';
import { TradePanels } from './trade-panels';
import { useNavigate, useParams } from 'react-router-dom';
import { Links } from '../../lib/links';
import { ViewType, useSidebar } from '../../components/sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT, ns } from '../../lib/use-t';
import { Trans } from 'react-i18next';
@@ -61,9 +59,6 @@ export const MarketPage = () => {
const t = useT();
const { marketId } = useParams();
const navigate = useNavigate();
const currentRouteId = useGetCurrentRouteId();
const { setViews, getView } = useSidebar();
const view = getView(currentRouteId);
const { screenSize } = useScreenDimensions();
const largeScreen = ['lg', 'xl', 'xxl', 'xxxl'].includes(screenSize);
const update = useGlobalStore((store) => store.update);
@@ -72,20 +67,11 @@ export const MarketPage = () => {
const { data, loading } = useMarket(marketId);
useEffect(() => {
if (data?.id && data.id !== lastMarketId && !closed) {
if (data?.id && data.id !== lastMarketId) {
update({ marketId: data.id });
}
}, [update, lastMarketId, data?.id]);
useEffect(() => {
if (largeScreen && view === undefined) {
setViews(
{ type: closed ? ViewType.Info : ViewType.Order },
currentRouteId
);
}
}, [setViews, view, currentRouteId, largeScreen]);
const pinnedAsset = data && getAsset(data);
const tradeView = useMemo(() => {
@@ -62,10 +62,10 @@ const MainGrid = memo(
id="chart"
overflowHidden
name={t('Chart')}
menu={<TradingViews.candles.menu />}
menu={<TradingViews.chart.menu />}
>
<ErrorBoundary feature="chart">
<TradingViews.candles.component marketId={marketId} />
<TradingViews.chart.component marketId={marketId} />
</ErrorBoundary>
</Tab>
<Tab id="depth" name={t('Depth')}>
@@ -23,7 +23,7 @@ interface TradePanelsProps {
export const TradePanels = ({ market, pinnedAsset }: TradePanelsProps) => {
const featureFlags = useFeatureFlags((state) => state.flags);
const [view, setView] = useState<TradingView>('candles');
const [view, setView] = useState<TradingView>('chart');
const renderView = () => {
const Component = TradingViews[view].component;
@@ -50,7 +50,7 @@ export const TradePanels = ({ market, pinnedAsset }: TradePanelsProps) => {
const Menu = viewCfg.menu;
return (
<div className="flex gap-1 p-1 bg-vega-clight-800 dark:bg-vega-cdark-800 border-b border-default">
<div className="flex items-center justify-end gap-1 p-1 bg-vega-clight-800 dark:bg-vega-cdark-800 border-b border-default">
<Menu />
</div>
);
@@ -149,7 +149,7 @@ const useViewLabel = (view: TradingView) => {
const t = useT();
const labels = {
candles: t('Candles'),
chart: t('Chart'),
depth: t('Depth'),
liquidity: t('Liquidity'),
funding: t('Funding'),
@@ -1,8 +1,4 @@
import { DepthChartContainer } from '@vegaprotocol/market-depth';
import {
CandlesChartContainer,
CandlesMenu,
} from '@vegaprotocol/candles-chart';
import { Filter, OpenOrdersMenu } from '@vegaprotocol/orders';
import { TradesContainer } from '../../components/trades-container';
import { OrderbookContainer } from '../../components/orderbook-container';
@@ -16,13 +12,14 @@ import { OrdersContainer } from '../../components/orders-container';
import { StopOrdersContainer } from '../../components/stop-orders-container';
import { AccountsMenu } from '../../components/accounts-menu';
import { PositionsMenu } from '../../components/positions-menu';
import { ChartContainer, ChartMenu } from '../../components/chart-container';
export type TradingView = keyof typeof TradingViews;
export const TradingViews = {
candles: {
component: CandlesChartContainer,
menu: CandlesMenu,
chart: {
component: ChartContainer,
menu: ChartMenu,
},
depth: {
component: DepthChartContainer,
@@ -4,9 +4,26 @@ import {
SidebarButton,
SidebarDivider,
ViewType,
useSidebar,
} from '../../components/sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
import { useScreenDimensions } from '@vegaprotocol/react-helpers';
import { useEffect } from 'react';
const ViewInitializer = () => {
const currentRouteId = useGetCurrentRouteId();
const { setViews, getView } = useSidebar();
const view = getView(currentRouteId);
const { screenSize } = useScreenDimensions();
const largeScreen = ['lg', 'xl', 'xxl', 'xxxl'].includes(screenSize);
useEffect(() => {
if (largeScreen && view === undefined) {
setViews({ type: ViewType.Order }, currentRouteId);
}
}, [setViews, view, currentRouteId, largeScreen]);
return null;
};
export const MarketsSidebar = () => {
const t = useT();
@@ -37,6 +54,7 @@ export const MarketsSidebar = () => {
path=":marketId"
element={
<>
<ViewInitializer />
<SidebarDivider />
<SidebarButton
view={ViewType.Order}
@@ -39,11 +39,21 @@ const WithdrawalsIndicator = () => {
);
};
export const Portfolio = () => {
const t = useT();
const SidebarViewInitializer = () => {
const currentRouteId = useGetCurrentRouteId();
const { getView, setViews } = useSidebar();
const view = getView(currentRouteId);
// Make transfer sidebar open by default
useEffect(() => {
if (view === undefined) {
setViews({ type: ViewType.Transfer }, currentRouteId);
}
}, [view, setViews, currentRouteId]);
return null;
};
export const Portfolio = () => {
const t = useT();
const { updateTitle } = usePageTitleStore((store) => ({
updateTitle: store.updateTitle,
@@ -53,17 +63,11 @@ export const Portfolio = () => {
updateTitle(titlefy([t('Portfolio')]));
}, [updateTitle, t]);
// Make transfer sidebar open by default
useEffect(() => {
if (view === undefined) {
setViews({ type: ViewType.Transfer }, currentRouteId);
}
}, [view, setViews, currentRouteId]);
const [sizes, handleOnLayoutChange] = usePaneLayout({ id: 'portfolio' });
const wrapperClasses = 'p-0.5 h-full max-h-full flex flex-col';
return (
<div className={wrapperClasses}>
<SidebarViewInitializer />
<ResizableGrid vertical onChange={handleOnLayoutChange}>
<ResizableGridPanel minSize={75}>
<PortfolioGridChild>
@@ -18,13 +18,35 @@ import { Routes } from '../../lib/links';
import { useTransactionEventSubscription } from '@vegaprotocol/web3';
import { Statistics, useStats } from './referral-statistics';
import { useReferralProgram } from './hooks/use-referral-program';
import { useT } from '../../lib/use-t';
import { ns, useT } from '../../lib/use-t';
import { useFundsAvailable } from './hooks/use-funds-available';
import { ViewType, useSidebar } from '../../components/sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { QUSDTooltip } from './qusd-tooltip';
import { Trans } from 'react-i18next';
const RELOAD_DELAY = 3000;
const SPAM_PROTECTION_ERR = 'SPAM_PROTECTION_ERR';
const SpamProtectionErr = ({
requiredFunds,
}: {
requiredFunds?: string | number | bigint;
}) => {
if (!requiredFunds) return null;
// eslint-disable-next-line react/jsx-no-undef
return (
<Trans
defaults="To protect the network from spam, you must have at least {{requiredFunds}} <0>qUSD</0> of any asset on the network to proceed."
values={{
requiredFunds,
}}
components={[<QUSDTooltip key="qusd" />]}
ns={ns}
/>
);
};
const validateCode = (value: string, t: ReturnType<typeof useT>) => {
const number = +`0x${value}`;
if (!value || value.length !== 64) {
@@ -76,7 +98,6 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
setValue,
setError,
watch,
clearErrors,
} = useForm();
const [params] = useSearchParams();
@@ -90,32 +111,11 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
*/
const validateFundsAvailable = useCallback(() => {
if (requiredFunds && !isEligible) {
const err = t(
'To protect the network from spam, you must have at least {{requiredFunds}} qUSD of any asset on the network to proceed.',
{
requiredFunds,
}
);
const err = SPAM_PROTECTION_ERR;
return err;
}
return true;
}, [isEligible, requiredFunds, t]);
useEffect(() => {
if (codeField) {
const err = validateFundsAvailable();
if (err !== true) {
setStatus('no-funds');
setError('code', {
type: 'required',
message: err,
});
} else {
setStatus(null);
clearErrors('code');
}
}
}, [clearErrors, codeField, isEligible, setError, validateFundsAvailable]);
}, [isEligible, requiredFunds]);
/**
* Validates the set a user tries to apply to.
@@ -140,6 +140,15 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
if (code) setValue('code', code);
}, [params, setValue]);
useEffect(() => {
const err = validateFundsAvailable();
if (err !== true) {
setStatus('no-funds');
} else {
setStatus(null);
}
}, [isEligible, validateFundsAvailable]);
const onSubmit = ({ code }: FieldValues) => {
if (isReadOnly || !pubKey || !code || code.length === 0) {
return;
@@ -323,10 +332,26 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
</label>
<RainbowButton variant="border" {...getButtonProps()} />
</form>
{errors.code && (
<InputError className="overflow-auto break-words">
{errors.code.message?.toString()}
{status === 'no-funds' ? (
<InputError intent="warning" className="overflow-auto break-words">
<span>
<SpamProtectionErr requiredFunds={requiredFunds?.toString()} />
</span>
</InputError>
) : (
errors.code && (
<InputError intent="warning" className="overflow-auto break-words">
{errors.code.message === SPAM_PROTECTION_ERR ? (
<span>
<SpamProtectionErr
requiredFunds={requiredFunds?.toString()}
/>
</span>
) : (
errors.code.message?.toString()
)}
</InputError>
)
)}
</div>
{validateCode(codeField, t) === true && previewLoading && !previewData ? (
@@ -1,7 +1,7 @@
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useFundsAvailableQuery } from './__generated__/FundsAvailable';
import compact from 'lodash/compact';
import sum from 'lodash/sum';
import BigNumber from 'bignumber.js';
/**
* Gets the funds for given public key and required min for
@@ -24,14 +24,16 @@ export const useFundsAvailable = (pubKey?: string) => {
? compact(data.party?.accountsConnection?.edges?.map((e) => e?.node))
: undefined;
const requiredFunds = data
? BigInt(data.networkParameter?.value || '0')
? BigNumber(data.networkParameter?.value || '0')
: undefined;
const sumOfFunds = sum(
fundsAvailable?.filter((fa) => fa.balance).map((fa) => BigInt(fa.balance))
);
const sumOfFunds =
fundsAvailable
?.filter((fa) => fa.balance)
.reduce((sum, fa) => sum.plus(BigNumber(fa.balance)), BigNumber(0)) ||
BigNumber(0);
if (requiredFunds && sumOfFunds >= requiredFunds) {
if (requiredFunds && sumOfFunds.isGreaterThanOrEqualTo(requiredFunds)) {
stopPolling();
}
@@ -41,6 +43,6 @@ export const useFundsAvailable = (pubKey?: string) => {
isEligible:
fundsAvailable != null &&
requiredFunds != null &&
sumOfFunds >= requiredFunds,
sumOfFunds.isGreaterThanOrEqualTo(requiredFunds),
};
};
@@ -15,7 +15,7 @@ export const LandingBanner = () => {
</div>
<div className="pt-20 sm:w-[50%]">
<h1 className="text-6xl font-alpha calt mb-10">
{t('Vega community referral program')}
{t('Vega community referrals')}
</h1>
<p className="text-lg mb-1">
{t(
@@ -0,0 +1,28 @@
import { DocsLinks } from '@vegaprotocol/environment';
import { ExternalLink, Tooltip } from '@vegaprotocol/ui-toolkit';
import { useT } from '../../lib/use-t';
export const QUSDTooltip = () => {
const t = useT();
return (
<Tooltip
description={
<>
<p className="mb-1">
{t(
'qUSD provides a rough USD equivalent of balances across all assets using the value of "Quantum" for that asset'
)}
</p>
{DocsLinks && (
<ExternalLink href={DocsLinks.QUANTUM}>
{t('Find out more')}
</ExternalLink>
)}
</>
}
underline={true}
>
<span>{t('qUSD')}</span>
</Tooltip>
);
};
@@ -4,8 +4,6 @@ import {
VegaIcon,
VegaIconNames,
truncateMiddle,
ExternalLink,
Tooltip,
} from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
@@ -28,10 +26,10 @@ import sortBy from 'lodash/sortBy';
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useCurrentEpochInfoQuery } from './hooks/__generated__/Epoch';
import BigNumber from 'bignumber.js';
import { DocsLinks } from '@vegaprotocol/environment';
import { useT, ns } from '../../lib/use-t';
import { Trans } from 'react-i18next';
import { ApplyCodeForm, ApplyCodeFormContainer } from './apply-code-form';
import { QUSDTooltip } from './qusd-tooltip';
export const ReferralStatistics = () => {
const { pubKey } = useVegaWallet();
@@ -214,6 +212,7 @@ export const Statistics = ({
).toString(),
}
)}
testId="base-commission-rate"
overrideWithNoProgram={!details}
>
{baseCommissionValue * 100}%
@@ -223,6 +222,7 @@ export const Statistics = ({
const stakingMultiplierTile = (
<StatTile
title={t('Staking multiplier')}
testId="staking-multiplier"
description={
<span
className={classNames({
@@ -256,6 +256,7 @@ export const Statistics = ({
? `(${baseCommissionFormatted}% ⨉ ${multiplier} = ${finalCommissionFormatted}%)`
: undefined
}
testId="final-commission-rate"
overrideWithNoProgram={!details}
>
{finalCommissionFormatted}%
@@ -263,7 +264,9 @@ export const Statistics = ({
);
const numberOfTradersValue = data.referees.length;
const numberOfTradersTile = (
<StatTile title={t('Number of traders')}>{numberOfTradersValue}</StatTile>
<StatTile title={t('Number of traders')} testId="number-of-traders">
{numberOfTradersValue}
</StatTile>
);
const codeTile = (
@@ -278,6 +281,7 @@ export const Statistics = ({
title={t('myVolume', 'My volume (last {{count}} epochs)', {
count: details?.windowLength || DEFAULT_AGGREGATION_DAYS,
})}
testId="my-volume"
overrideWithNoProgram={!details}
>
{compactNumFormat.format(referrerVolumeValue)}
@@ -293,6 +297,7 @@ export const Statistics = ({
count: details?.windowLength || DEFAULT_AGGREGATION_DAYS,
})}
description={<QUSDTooltip />}
testId="total-commission"
>
{getNumberFormat(0).format(Number(totalCommissionValue))}
</StatTile>
@@ -318,6 +323,7 @@ export const Statistics = ({
const currentBenefitTierTile = (
<StatTile
title={t('Current tier')}
testId="current-tier"
description={
nextBenefitTierValue?.tier
? t('(Next tier: {{nextTier}})', {
@@ -333,7 +339,11 @@ export const Statistics = ({
</StatTile>
);
const discountFactorTile = (
<StatTile title={t('Discount')} overrideWithNoProgram={!details}>
<StatTile
title={t('Discount')}
testId="discount"
overrideWithNoProgram={!details}
>
{isApplyCodePreview && benefitTiers.length >= 1
? benefitTiers[0].discountFactor * 100
: discountFactorValue * 100}
@@ -349,23 +359,34 @@ export const Statistics = ({
count: details?.windowLength,
}
)}
testId="combined-volume"
overrideWithNoProgram={!details}
>
{compactNumFormat.format(runningVolumeValue)}
</StatTile>
);
const epochsTile = (
<StatTile title={t('Epochs in set')}>{epochsValue}</StatTile>
<StatTile title={t('Epochs in set')} testId="epochs-in-set">
{epochsValue}
</StatTile>
);
const nextTierVolumeTile = (
<StatTile title={t('Volume to next tier')} overrideWithNoProgram={!details}>
<StatTile
title={t('Volume to next tier')}
testId="vol-to-next-tier"
overrideWithNoProgram={!details}
>
{nextBenefitTierVolumeValue <= 0
? '0'
: compactNumFormat.format(nextBenefitTierVolumeValue)}
</StatTile>
);
const nextTierEpochsTile = (
<StatTile title={t('Epochs to next tier')} overrideWithNoProgram={!details}>
<StatTile
title={t('Epochs to next tier')}
testId="epochs-to-next-tier"
overrideWithNoProgram={!details}
>
{nextBenefitTierEpochsValue <= 0 ? '0' : nextBenefitTierEpochsValue}
</StatTile>
);
@@ -519,28 +540,3 @@ export const RefereesTable = ({
</>
);
};
export const QUSDTooltip = () => {
const t = useT();
return (
<Tooltip
description={
<>
<p className="mb-1">
{t(
'qUSD provides a rough USD equivalent of balances across all assets using the value of "Quantum" for that asset'
)}
</p>
{DocsLinks && (
<ExternalLink href={DocsLinks.QUANTUM}>
{t('Find out more')}
</ExternalLink>
)}
</>
}
underline={true}
>
<span>{t('qUSD')}</span>
</Tooltip>
);
};
@@ -159,11 +159,11 @@ export const TiersContainer = () => {
return (
<>
<h2 className="text-3xl mt-10">{t('Current Program Details')}</h2>
<h2 className="text-3xl mt-10">{t('Current program details')}</h2>
{details?.id && (
<p>
<Trans
defaults="As a result of <0>{{proposal}}</0> the program below is currently active on the Vega network."
defaults="As a result of governance proposal <0>{{proposal}}</0> the program below is currently active on the Vega network."
values={{ proposal: truncateMiddle(details.id) }}
components={[
<ExternalLink
+9 -2
View File
@@ -32,6 +32,7 @@ export const Tile = ({
type StatTileProps = {
title: string;
testId?: string;
description?: ReactNode;
children?: ReactNode;
overrideWithNoProgram?: boolean;
@@ -40,6 +41,7 @@ export const StatTile = ({
title,
description,
children,
testId,
overrideWithNoProgram = false,
}: StatTileProps) => {
if (overrideWithNoProgram) {
@@ -47,10 +49,15 @@ export const StatTile = ({
}
return (
<Tile>
<h3 className="mb-1 text-sm text-vega-clight-100 dark:text-vega-cdark-100 calt">
<h3
data-testid={testId}
className="mb-1 text-sm text-vega-clight-100 dark:text-vega-cdark-100 calt"
>
{title}
</h3>
<div className="text-5xl text-left">{children}</div>
<div data-testid={`${testId}-value`} className="text-5xl text-left">
{children}
</div>
{description && (
<div className="text-sm text-left text-vega-clight-100 dark:text-vega-cdark-100">
{description}
@@ -13,6 +13,7 @@ import { ViewType, useSidebar } from '../sidebar';
import { useMarketClickHandler } from '../../lib/hooks/use-market-click-handler';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
import { usePersistentDepositStore } from '@vegaprotocol/deposits';
export const AccountsContainer = ({
pinnedAsset,
@@ -25,6 +26,7 @@ export const AccountsContainer = ({
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
const currentRouteId = useGetCurrentRouteId();
const setViews = useSidebar((store) => store.setViews);
const setDepositAsset = usePersistentDepositStore((store) => store.saveValue);
const gridStore = useAccountStore((store) => store.gridStore);
const updateGridStore = useAccountStore((store) => store.updateGridStore);
@@ -55,7 +57,10 @@ export const AccountsContainer = ({
setViews({ type: ViewType.Withdraw, assetId }, currentRouteId);
}}
onClickDeposit={(assetId) => {
setViews({ type: ViewType.Deposit, assetId }, currentRouteId);
setViews({ type: ViewType.Deposit }, currentRouteId);
if (assetId) {
setDepositAsset({ assetId });
}
}}
onClickTransfer={(assetId) => {
setViews({ type: ViewType.Transfer, assetId }, currentRouteId);
@@ -0,0 +1,66 @@
import { render, screen } from '@testing-library/react';
import { ChartContainer } from './chart-container';
import { useChartSettingsStore } from './use-chart-settings';
import { useEnvironment } from '@vegaprotocol/environment';
jest.mock('@vegaprotocol/candles-chart', () => ({
...jest.requireActual('@vegaprotocol/candles-chart'),
CandlesChartContainer: ({ marketId }: { marketId: string }) => (
<div data-testid="pennant">{marketId}</div>
),
}));
jest.mock('@vegaprotocol/trading-view', () => ({
...jest.requireActual('@vegaprotocol/trading-view'),
TradingViewContainer: ({ marketId }: { marketId: string }) => (
<div data-testid="tradingview">{marketId}</div>
),
}));
describe('ChartContainer', () => {
it('renders pennant if no library path is set', () => {
useChartSettingsStore.setState({
chartlib: 'tradingview',
});
useEnvironment.setState({
CHARTING_LIBRARY_PATH: undefined,
CHARTING_LIBRARY_HASH: undefined,
});
const marketId = 'market-id';
render(<ChartContainer marketId={marketId} />);
expect(screen.getByTestId('pennant')).toHaveTextContent(marketId);
});
it('renders trading view if library path is set', () => {
useChartSettingsStore.setState({
chartlib: 'tradingview',
});
useEnvironment.setState({
CHARTING_LIBRARY_PATH: 'dummy-path',
CHARTING_LIBRARY_HASH: 'hash',
});
const marketId = 'market-id';
render(<ChartContainer marketId={marketId} />);
expect(screen.getByTestId('tradingview')).toHaveTextContent(marketId);
});
it('renders pennant chart if stored in settings', () => {
useChartSettingsStore.setState({
chartlib: 'pennant',
});
const marketId = 'market-id';
render(<ChartContainer marketId={marketId} />);
expect(screen.getByTestId('pennant')).toHaveTextContent(marketId);
});
});
@@ -0,0 +1,120 @@
import invert from 'lodash/invert';
import { type Interval } from '@vegaprotocol/types';
import {
TradingViewContainer,
ALLOWED_TRADINGVIEW_HOSTNAMES,
TRADINGVIEW_INTERVAL_MAP,
} from '@vegaprotocol/trading-view';
import {
CandlesChartContainer,
PENNANT_INTERVAL_MAP,
} from '@vegaprotocol/candles-chart';
import { useEnvironment } from '@vegaprotocol/environment';
import { useChartSettings, STUDY_SIZE } from './use-chart-settings';
/**
* Renders either the pennant chart or the tradingview chart
*/
export const ChartContainer = ({ marketId }: { marketId: string }) => {
const { CHARTING_LIBRARY_PATH, CHARTING_LIBRARY_HASH } = useEnvironment();
const {
chartlib,
interval,
chartType,
overlays,
studies,
studySizes,
tradingViewStudies,
setInterval,
setStudies,
setStudySizes,
setOverlays,
setTradingViewStudies,
} = useChartSettings();
const pennantChart = (
<CandlesChartContainer
marketId={marketId}
interval={toPennantInterval(interval)}
chartType={chartType}
overlays={overlays}
studies={studies}
studySizes={studySizes}
setStudySizes={setStudySizes}
setStudies={setStudies}
setOverlays={setOverlays}
defaultStudySize={STUDY_SIZE}
/>
);
if (!ALLOWED_TRADINGVIEW_HOSTNAMES.includes(window.location.hostname)) {
return pennantChart;
}
if (!CHARTING_LIBRARY_PATH || !CHARTING_LIBRARY_HASH) {
return pennantChart;
}
switch (chartlib) {
case 'tradingview': {
return (
<TradingViewContainer
libraryPath={CHARTING_LIBRARY_PATH}
libraryHash={CHARTING_LIBRARY_HASH}
marketId={marketId}
interval={toTradingViewResolution(interval)}
studies={tradingViewStudies}
onIntervalChange={(newInterval) => {
setInterval(fromTradingViewResolution(newInterval));
}}
onAutoSaveNeeded={(data: { studies: string[] }) => {
setTradingViewStudies(data.studies);
}}
/>
);
}
case 'pennant': {
return pennantChart;
}
default: {
throw new Error('invalid chart lib');
}
}
};
const toTradingViewResolution = (interval: Interval) => {
const resolution = TRADINGVIEW_INTERVAL_MAP[interval];
if (!resolution) {
throw new Error(
`failed to convert interval: ${interval} to valid resolution`
);
}
return resolution;
};
const fromTradingViewResolution = (resolution: string) => {
const interval = invert(TRADINGVIEW_INTERVAL_MAP)[resolution];
if (!interval) {
throw new Error(
`failed to convert resolution: ${resolution} to valid interval`
);
}
return interval as Interval;
};
const toPennantInterval = (interval: Interval) => {
const pennantInterval = PENNANT_INTERVAL_MAP[interval];
if (!pennantInterval) {
throw new Error(
`failed to convert interval: ${interval} to valid pennant interval`
);
}
return pennantInterval;
};
@@ -0,0 +1,140 @@
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ChartMenu } from './chart-menu';
import {
useChartSettingsStore,
DEFAULT_CHART_SETTINGS,
} from './use-chart-settings';
import { Overlay, Study, overlayLabels, studyLabels } from 'pennant';
import { useEnvironment } from '@vegaprotocol/environment';
describe('ChartMenu', () => {
it('doesnt show trading view option if library path undefined', () => {
useEnvironment.setState({ CHARTING_LIBRARY_PATH: undefined });
render(<ChartMenu />);
expect(
screen.queryByRole('button', { name: 'TradingView' })
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: 'Vega chart' })
).not.toBeInTheDocument();
});
it('can switch between charts if library path', async () => {
useEnvironment.setState({ CHARTING_LIBRARY_PATH: 'dummy' });
render(<ChartMenu />);
await userEvent.click(screen.getByRole('button', { name: 'TradingView' }));
expect(useChartSettingsStore.getState().chartlib).toEqual('tradingview');
await userEvent.click(screen.getByRole('button', { name: 'Vega chart' }));
expect(useChartSettingsStore.getState().chartlib).toEqual('pennant');
});
describe('tradingview', () => {
beforeEach(() => {
useEnvironment.setState({ CHARTING_LIBRARY_PATH: 'dummy-path' });
// clear store each time to avoid conditional testing of defaults
useChartSettingsStore.setState({
chartlib: 'tradingview',
});
});
it('only shows chartlib switch and attribution', () => {
render(<ChartMenu />);
const buttons = screen.getAllByRole('button');
expect(buttons).toHaveLength(1);
expect(buttons[0]).toHaveTextContent('Vega chart');
expect(screen.getByText('Chart by')).toBeInTheDocument();
});
});
describe('pennant', () => {
const openDropdown = async () => {
await userEvent.click(
screen.getByRole('button', {
name: 'Indicators',
})
);
};
beforeEach(() => {
// clear store each time to avoid conditional testing of defaults
useChartSettingsStore.setState({
chartlib: 'pennant',
overlays: [],
studies: [],
});
});
it.each(Object.values(Overlay))('can set %s overlay', async (overlay) => {
render(<ChartMenu />);
await openDropdown();
const menu = within(await screen.findByRole('menu'));
await userEvent.click(menu.getByText(overlayLabels[overlay as Overlay]));
// re-open the dropdown
await openDropdown();
expect(
screen.getByText(overlayLabels[overlay as Overlay])
).toHaveAttribute('data-state', 'checked');
});
it.each(Object.values(Study))('can set %s study', async (study) => {
render(<ChartMenu />);
await openDropdown();
const menu = within(await screen.findByRole('menu'));
await userEvent.click(menu.getByText(studyLabels[study as Study]));
// re-open the dropdown
await openDropdown();
expect(screen.getByText(studyLabels[study as Study])).toHaveAttribute(
'data-state',
'checked'
);
});
it('should render with the correct default studies and overlays', async () => {
useChartSettingsStore.setState({
...DEFAULT_CHART_SETTINGS,
chartlib: 'pennant',
});
render(<ChartMenu />);
await userEvent.click(
screen.getByRole('button', {
name: 'Indicators',
})
);
const menu = within(await screen.findByRole('menu'));
expect(menu.getByText(studyLabels.volume)).toHaveAttribute(
'data-state',
'checked'
);
expect(menu.getByText(studyLabels.macd)).toHaveAttribute(
'data-state',
'checked'
);
expect(menu.getByText(overlayLabels.movingAverage)).toHaveAttribute(
'data-state',
'checked'
);
});
});
});
@@ -1,14 +1,12 @@
import 'pennant/dist/style.css';
import {
ChartType,
Interval,
Overlay,
Study,
chartTypeLabels,
intervalLabels,
overlayLabels,
studyLabels,
} from 'pennant';
import { Trans } from 'react-i18next';
import {
TradingButton,
TradingDropdown,
@@ -20,10 +18,21 @@ import {
TradingDropdownTrigger,
Icon,
} from '@vegaprotocol/ui-toolkit';
import { type IconName } from '@blueprintjs/icons';
import { IconNames } from '@blueprintjs/icons';
import { useCandlesChartSettings } from './use-candles-chart-settings';
import { useT } from './use-t';
import { Interval } from '@vegaprotocol/types';
import { useEnvironment } from '@vegaprotocol/environment';
import { ALLOWED_TRADINGVIEW_HOSTNAMES } from '@vegaprotocol/trading-view';
import { IconNames, type IconName } from '@blueprintjs/icons';
import { useChartSettings } from './use-chart-settings';
import { useT } from '../../lib/use-t';
const INTERVALS = [
Interval.INTERVAL_I1M,
Interval.INTERVAL_I5M,
Interval.INTERVAL_I15M,
Interval.INTERVAL_I1H,
Interval.INTERVAL_I6H,
Interval.INTERVAL_I1D,
];
const chartTypeIcon = new Map<ChartType, IconName>([
[ChartType.AREA, IconNames.TIMELINE_AREA_CHART],
@@ -32,30 +41,46 @@ const chartTypeIcon = new Map<ChartType, IconName>([
[ChartType.OHLC, IconNames.WATERFALL_CHART],
]);
export const CandlesMenu = () => {
export const ChartMenu = () => {
const { CHARTING_LIBRARY_PATH } = useEnvironment();
const {
chartlib,
interval,
chartType,
studies,
overlays,
setChartlib,
setInterval,
setType,
setStudies,
setOverlays,
} = useCandlesChartSettings();
} = useChartSettings();
const t = useT();
const triggerClasses = 'text-xs';
const contentAlign = 'end';
const triggerClasses = 'text-xs';
const triggerButtonProps = { size: 'extra-small' } as const;
return (
const isPennant = chartlib === 'pennant';
const commonMenuItems = (
<TradingButton
onClick={() => {
setChartlib(isPennant ? 'tradingview' : 'pennant');
}}
size="extra-small"
>
{isPennant ? 'TradingView' : t('Vega chart')}
</TradingButton>
);
const pennantMenuItems = (
<>
<TradingDropdown
trigger={
<TradingDropdownTrigger className={triggerClasses}>
<TradingButton {...triggerButtonProps}>
{t('Interval: {{interval}}', {
interval: intervalLabels[interval],
interval: t(interval),
})}
</TradingButton>
</TradingDropdownTrigger>
@@ -68,13 +93,13 @@ export const CandlesMenu = () => {
setInterval(value as Interval);
}}
>
{Object.values(Interval).map((timeInterval) => (
{INTERVALS.map((timeInterval) => (
<TradingDropdownRadioItem
key={timeInterval}
inset
value={timeInterval}
>
{intervalLabels[timeInterval]}
{t(timeInterval)}
<TradingDropdownItemIndicator />
</TradingDropdownRadioItem>
))}
@@ -158,4 +183,50 @@ export const CandlesMenu = () => {
</TradingDropdown>
</>
);
const tradingViewMenuItems = (
<p className="text-xs mr-2 whitespace-nowrap">
<Trans
i18nKey="Chart by <0>TradingView</0>"
components={[
// eslint-disable-next-line
<a
className="underline"
target="_blank"
href="https://www.tradingview.com"
/>,
]}
/>
</p>
);
if (!ALLOWED_TRADINGVIEW_HOSTNAMES.includes(window.location.hostname)) {
return pennantMenuItems;
}
if (!CHARTING_LIBRARY_PATH) {
return pennantMenuItems;
}
switch (chartlib) {
case 'tradingview': {
return (
<>
{tradingViewMenuItems}
{commonMenuItems}
</>
);
}
case 'pennant': {
return (
<>
{pennantMenuItems}
{commonMenuItems}
</>
);
}
default: {
throw new Error('invalid chart lib');
}
}
};
@@ -0,0 +1,2 @@
export { ChartContainer } from './chart-container';
export { ChartMenu } from './chart-menu';
@@ -1,18 +1,23 @@
import { getValidItem, getValidSubset } from '@vegaprotocol/react-helpers';
import { ChartType, Interval, Study } from 'pennant';
import { Overlay } from 'pennant';
import { ChartType, Overlay, Study } from 'pennant';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { Interval } from '@vegaprotocol/types';
import { getValidItem, getValidSubset } from '@vegaprotocol/react-helpers';
type StudySizes = { [S in Study]?: number };
export type Chartlib = 'pennant' | 'tradingview';
interface StoredSettings {
chartlib: Chartlib;
// For interval we use the enum from @vegaprotocol/types, this is to make mapping between different
// chart types easier and more consistent
interval: Interval;
type: ChartType;
overlays: Overlay[];
studies: Study[];
studySizes: StudySizes;
tradingViewStudies: string[];
}
export const STUDY_SIZE = 90;
@@ -25,20 +30,24 @@ const STUDY_ORDER: Study[] = [
];
export const DEFAULT_CHART_SETTINGS = {
interval: Interval.I15M,
chartlib: 'pennant' as const,
interval: Interval.INTERVAL_I15M,
type: ChartType.CANDLE,
overlays: [Overlay.MOVING_AVERAGE],
studies: [Study.MACD, Study.VOLUME],
studySizes: {},
tradingViewStudies: ['Volume'],
};
export const useCandlesChartSettingsStore = create<
export const useChartSettingsStore = create<
StoredSettings & {
setType: (type: ChartType) => void;
setInterval: (interval: Interval) => void;
setOverlays: (overlays?: Overlay[]) => void;
setStudies: (studies?: Study[]) => void;
setStudySizes: (sizes: number[]) => void;
setChartlib: (lib: Chartlib) => void;
setTradingViewStudies: (studies: string[]) => void;
}
>()(
persist(
@@ -81,6 +90,16 @@ export const useCandlesChartSettingsStore = create<
});
});
},
setChartlib: (lib) => {
set((state) => {
state.chartlib = lib;
});
},
setTradingViewStudies: (studies: string[]) => {
set((state) => {
state.tradingViewStudies = studies;
});
},
})),
{
name: 'vega_candles_chart_store',
@@ -88,13 +107,13 @@ export const useCandlesChartSettingsStore = create<
)
);
export const useCandlesChartSettings = () => {
const settings = useCandlesChartSettingsStore();
export const useChartSettings = () => {
const settings = useChartSettingsStore();
const interval: Interval = getValidItem(
settings.interval,
Object.values(Interval),
Interval.I15M
Interval.INTERVAL_I15M
);
const chartType: ChartType = getValidItem(
@@ -122,15 +141,19 @@ export const useCandlesChartSettings = () => {
});
return {
chartlib: settings.chartlib,
interval,
chartType,
overlays,
studies,
studySizes,
tradingViewStudies: settings.tradingViewStudies,
setInterval: settings.setInterval,
setType: settings.setType,
setStudies: settings.setStudies,
setOverlays: settings.setOverlays,
setStudySizes: settings.setStudySizes,
setChartlib: settings.setChartlib,
setTradingViewStudies: settings.setTradingViewStudies,
};
};
@@ -24,7 +24,13 @@ import classNames from 'classnames';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const VegaWalletConnectButton = () => {
export const VegaWalletConnectButton = ({
intent = Intent.None,
onClick,
}: {
intent?: Intent;
onClick?: () => void;
}) => {
const t = useT();
const [dropdownOpen, setDropdownOpen] = useState(false);
const openVegaWalletDialog = useVegaWalletDialogStore(
@@ -117,9 +123,12 @@ export const VegaWalletConnectButton = () => {
return (
<Button
data-testid="connect-vega-wallet"
onClick={openVegaWalletDialog}
onClick={() => {
onClick?.();
openVegaWalletDialog();
}}
size="small"
intent={Intent.None}
intent={intent}
icon={<VegaIcon name={VegaIconNames.ARROW_RIGHT} size={14} />}
>
<span className="whitespace-nowrap uppercase">
@@ -1,17 +1,23 @@
import { useEffect } from 'react';
import { useMatch } from 'react-router-dom';
import { matchPath, useLocation } from 'react-router-dom';
import { Dialog, Intent } from '@vegaprotocol/ui-toolkit';
import { useEnvironment } from '@vegaprotocol/environment';
import { VegaConnectDialog } from '@vegaprotocol/wallet';
import { useConnectors } from '../../lib/vega-connectors';
import { useT } from '../../lib/use-t';
import { Links } from '../../lib/links';
import { Routes } from '../../lib/links';
import { RiskMessage } from './risk-message';
import { WelcomeDialogContent } from './welcome-dialog-content';
import { useOnboardingStore } from './use-get-onboarding-step';
import { ensureSuffix } from '@vegaprotocol/utils';
/**
* A list of paths on which the welcome dialog should be omitted.
*/
const OMIT_ON_LIST = [ensureSuffix(Routes.REFERRALS, '/*')];
export const WelcomeDialog = () => {
const isReferrals = useMatch(Links.REFERRALS());
const { pathname } = useLocation();
const t = useT();
const { VEGA_ENV } = useEnvironment();
const connectors = useConnectors();
@@ -27,10 +33,14 @@ export const WelcomeDialog = () => {
);
useEffect(() => {
if (dismissed) return;
if (isReferrals) return;
const shouldOmit = OMIT_ON_LIST.map((path) =>
matchPath(path, pathname)
).some((m) => !!m);
if (dismissed || shouldOmit) return;
setDialogOpen(true);
}, [dismissed, isReferrals, setDialogOpen]);
}, [dismissed, pathname, setDialogOpen]);
const content = walletDialogOpen ? (
<VegaConnectDialog
+1 -1
View File
@@ -1,2 +1,2 @@
CONSOLE_IMAGE_NAME=vegaprotocol/trading:latest
VEGA_VERSION=v0.73.8
VEGA_VERSION=v0.73.9
+1 -1
View File
@@ -1,2 +1,2 @@
CONSOLE_IMAGE_NAME=vegaprotocol/trading:develop
VEGA_VERSION=v0.73.8
VEGA_VERSION=v0.73.9
+20 -2
View File
@@ -87,10 +87,9 @@ docker build -f docker/node-outside-docker.Dockerfile --build-arg APP=trading --
## Running Tests 🧪
Before running make sure the docker daemon is runnign so that the app can be served.
Before running make sure the docker daemon is running.
To run a specific test, use the `-k` option followed by the name of the test.
Run all tests:
```bash
@@ -109,6 +108,25 @@ Run from anywhere:
yarn trading:test -- "test_name" -s --headed
```
Run using your locally served console:
Within one terminal
```bash
yarn nx build trading
```
```bash
yarn nx serve trading
```
Once console is served you can use the flag --local-server
```bash
poetry run pytest -k "test_name" -s --headed --local-server
```
## Running Tests in Parallel 🔢
To run tests in parallel, use the `--numprocesses auto` option. The `--dist loadfile` setting ensures that multiple runners are not assigned to a single test file.
+29 -4
View File
@@ -6,23 +6,27 @@ from typing import Optional
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
ASSET_NAME = "tDAI"
def wait_for_toast_confirmation(page: Page, timeout: int = 30000):
page.wait_for_function("""
document.querySelector('[data-testid="toast-content"]') &&
document.querySelector('[data-testid="toast-content"]').innerText.includes('AWAITING CONFIRMATION')
""", timeout=timeout)
def create_and_faucet_wallet(
vega: VegaServiceNull,
wallet: WalletConfig,
symbol: Optional[str] = None,
amount: float = 1e4,
):
asset_id = vega.find_asset_id(symbol=symbol if symbol is not None else ASSET_NAME)
asset_id = vega.find_asset_id(
symbol=symbol if symbol is not None else ASSET_NAME)
vega.create_key(wallet.name)
vega.mint(wallet.name, asset_id, amount)
def next_epoch(vega: VegaServiceNull):
forwards = 0
epoch_seq = vega.statistics().epoch_seq
@@ -36,13 +40,34 @@ def next_epoch(vega: VegaServiceNull):
vega.wait_fn(1)
vega.wait_for_total_catchup()
def truncate_middle(market_id, start=6, end=4):
if len(market_id) < 11:
return market_id
return market_id[:start] + '\u2026' + market_id[-end:]
def change_keys(page: Page, vega:VegaServiceNull, key_name):
def change_keys(page: Page, vega: VegaServiceNull, key_name):
page.get_by_test_id("manage-vega-wallet").click()
page.get_by_test_id("key-" + vega.wallet.public_key(key_name)).click()
page.click(f'data-testid=key-{vega.wallet.public_key(key_name)} >> .inline-flex')
page.click(
f'data-testid=key-{vega.wallet.public_key(key_name)} >> .inline-flex')
page.reload()
def forward_time(vega: VegaServiceNull, forward_epoch: bool = False):
vega.wait_fn(1)
vega.wait_for_total_catchup()
if forward_epoch:
next_epoch(vega)
# This is for when the element will initially load but contain an outdated value. It will wait for the element to contain the expected text, returning False after a timeout or exception
def selector_contains_text(page: Page, selector, expected_text, timeout=5000):
try:
page.wait_for_selector(
f'{selector} >> text={expected_text}', timeout=timeout)
return True
except:
return False
+5 -4
View File
@@ -1,6 +1,7 @@
from typing import List, Tuple, Optional
from vega_sim.service import VegaService, PeggedOrder
def submit_order(
vega: VegaService,
wallet_name: str,
@@ -35,7 +36,7 @@ def submit_multiple_orders(
submit_order(vega, wallet_name, market_id, side, volume, price)
def submit_liquidity(vega: VegaService, wallet_name: str, market_id: str):
def submit_liquidity(vega: VegaService, wallet_name: str, market_id: str, buy_vol=99, sell_vol=99, custom_price=None):
vega.submit_simple_liquidity(
key_name=wallet_name,
market_id=market_id,
@@ -51,7 +52,7 @@ def submit_liquidity(vega: VegaService, wallet_name: str, market_id: str):
pegged_order=PeggedOrder(reference="PEGGED_REFERENCE_MID", offset=1),
wait=False,
time_in_force="TIME_IN_FORCE_GTC",
volume=99,
volume=buy_vol,
)
vega.submit_order(
market_id=market_id,
@@ -61,5 +62,5 @@ def submit_liquidity(vega: VegaService, wallet_name: str, market_id: str):
pegged_order=PeggedOrder(reference="PEGGED_REFERENCE_MID", offset=1),
wait=False,
time_in_force="TIME_IN_FORCE_GTC",
volume=99,
)
volume=sell_vol,
)
+17 -6
View File
@@ -7,7 +7,6 @@ import time
import docker
import http.server
from contextlib import contextmanager
from vega_sim.null_service import VegaServiceNull
from playwright.sync_api import Browser, Page
@@ -102,11 +101,23 @@ def init_vega(request=None):
logger.info(f"Removing container {container.id}")
container.remove()
def pytest_addoption(parser):
parser.addoption(
"--local-server", action="store_true", default=False,
help="Build and serve locally instead of using a container"
)
@pytest.fixture(scope="session")
def local_server(pytestconfig):
return pytestconfig.getoption("--local-server")
@contextmanager
def init_page(vega: VegaServiceNull, browser: Browser, request: pytest.FixtureRequest):
def init_page(vega: VegaServiceNull, browser: Browser, request: pytest.FixtureRequest, local_server: bool):
server_port = "4200" if local_server else str(vega.console_port)
with browser.new_context(
viewport={"width": 1920, "height": 1080},
base_url=f"http://localhost:{vega.console_port}",
base_url=f"http://localhost:{server_port}",
) as context, context.new_page() as page:
context.tracing.start(screenshots=True, snapshots=True, sources=True)
try:
@@ -115,7 +126,7 @@ def init_page(vega: VegaServiceNull, browser: Browser, request: pytest.FixtureRe
while attempts < 100:
try:
code = requests.get(
f"http://localhost:{vega.console_port}/"
f"http://localhost:{server_port}/"
).status_code
if code == 200:
break
@@ -161,8 +172,8 @@ def vega(request):
@pytest.fixture
def page(vega, browser, request):
with init_page(vega, browser, request) as page_instance:
def page(vega, browser, request, local_server):
with init_page(vega, browser, request, local_server) as page_instance:
yield page_instance
+30 -11
View File
@@ -8,12 +8,17 @@ logger = logging.getLogger()
mint_amount: float = 10e5
market_name = "BTC:DAI_2023"
default_sell_orders = [[1, 110], [1, 105]]
default_buy_orders = [[1, 90], [1, 95]]
def setup_simple_market(
vega: VegaService,
approve_proposal=True,
custom_market_name=market_name,
custom_asset_name="tDAI",
custom_asset_symbol="tDAI",
custom_quantum=1
):
for wallet in wallets:
vega.create_key(wallet.name)
@@ -37,6 +42,7 @@ def setup_simple_market(
symbol=custom_asset_symbol,
decimals=5,
max_faucet_amount=1e10,
quantum=custom_quantum,
)
vega.wait_fn(1)
vega.wait_for_total_catchup()
@@ -111,16 +117,17 @@ def setup_simple_successor_market(
return market_id
def setup_opening_auction_market(vega: VegaService, market_id: str = None, **kwargs):
if market_id is None or market_id not in vega.all_markets():
def setup_opening_auction_market(vega: VegaService, market_id: str = None, buy_orders=default_buy_orders, sell_orders=default_sell_orders, add_liquidity=True, **kwargs):
if not market_exists(vega, market_id):
market_id = setup_simple_market(vega, **kwargs)
submit_liquidity(vega, MM_WALLET.name, market_id)
if add_liquidity:
submit_liquidity(vega, MM_WALLET.name, market_id)
submit_multiple_orders(
vega, MM_WALLET.name, market_id, "SIDE_SELL", [[1, 110], [1, 105]]
vega, MM_WALLET.name, market_id, "SIDE_SELL", sell_orders
)
submit_multiple_orders(
vega, MM_WALLET2.name, market_id, "SIDE_BUY", [[1, 90], [1, 95]]
vega, MM_WALLET2.name, market_id, "SIDE_BUY", buy_orders
)
vega.forward("10s")
@@ -130,11 +137,22 @@ def setup_opening_auction_market(vega: VegaService, market_id: str = None, **kwa
return market_id
def setup_continuous_market(vega: VegaService, market_id: str = None, **kwargs):
if market_id is None or market_id not in vega.all_markets():
market_id = setup_opening_auction_market(vega, **kwargs)
def market_exists(vega: VegaService, market_id: str):
if market_id is None:
return False
all_markets = vega.all_markets()
market_ids = [market.id for market in all_markets]
return market_id in market_ids
submit_order(vega, "Key 1", market_id, "SIDE_BUY", 1, 110)
# Add sell orders and buy orders to put on the book
def setup_continuous_market(vega: VegaService, market_id: str = None, buy_orders=default_buy_orders, sell_orders=default_sell_orders, add_liquidity=True, **kwargs):
if not market_exists(vega, market_id) or buy_orders != default_buy_orders or sell_orders != default_sell_orders:
market_id = setup_opening_auction_market(
vega, market_id, buy_orders, sell_orders, add_liquidity, **kwargs)
submit_order(vega, "Key 1", market_id, "SIDE_BUY",
sell_orders[0][0], sell_orders[0][1])
vega.forward("10s")
vega.wait_fn(1)
@@ -142,6 +160,7 @@ def setup_continuous_market(vega: VegaService, market_id: str = None, **kwargs):
return market_id
def setup_perps_market(
vega: VegaService,
custom_asset_name="tDAI",
@@ -210,7 +229,7 @@ def setup_perps_market(
settlement_data_key=TERMINATE_WALLET.name,
funding_payment_frequency_in_seconds=10,
market_decimals=5,
)
)
vega.wait_for_total_catchup()
submit_liquidity(vega, MM_WALLET.name, market_id)
@@ -225,4 +244,4 @@ def setup_perps_market(
vega.wait_fn(1)
vega.wait_for_total_catchup()
return market_id
return market_id
+14 -8
View File
@@ -56,11 +56,12 @@ label_value_tooltip_pairs = [
def tooltip(page: Page, index: int, test_id: str, tooltip: str):
page.locator(f"data-testid={index}_{test_id}").hover()
expect(page.locator('[role="tooltip"]').locator("div")).to_have_text(tooltip)
expect(page.locator('[role="tooltip"]').locator(
"div")).to_have_text(tooltip)
page.get_by_test_id("dialog-title").click()
@pytest.mark.usefixtures("page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("continuous_market", "auth", "risk_accepted")
def test_asset_details(page: Page):
page.goto("/#/portfolio")
page.locator('[data-testid="tab-collateral"] >> text=tDAI').click()
@@ -73,17 +74,22 @@ def test_asset_details(page: Page):
value = pair.get("value", "")
label_tooltip = pair.get("labelTooltip", "")
value_tooltip = pair.get("valueToolTip", "")
if label == "ID":
expect(page.get_by_role("button", name="Copy id to clipboard")).to_be_visible()
asset_id_text = page.locator(f"[data-testid='{index}_value']").inner_text()
expect(page.get_by_role(
"button", name="Copy id to clipboard")).to_be_visible()
asset_id_text = page.locator(
f"[data-testid='{index}_value']").inner_text()
pattern = r"^[0-9a-f]{6}\u2026[0-9a-f]{4}"
assert re.match(pattern, asset_id_text), f"Expected ID to match pattern but got {asset_id_text}"
assert re.match(
pattern, asset_id_text), f"Expected ID to match pattern but got {asset_id_text}"
else:
expect(page.locator(f"[data-testid='{index}_label']")).to_have_text(label)
expect(page.locator(f"[data-testid='{index}_value']")).to_have_text(value)
expect(page.locator(
f"[data-testid='{index}_label']")).to_have_text(label)
expect(page.locator(
f"[data-testid='{index}_value']")).to_have_text(value)
if label_tooltip:
tooltip(page, index, "label", label_tooltip)
@@ -14,19 +14,16 @@ market_order = "order-type-Market"
tif = "order-tif"
expire = "expire"
@pytest.fixture(scope="module")
def vega(request):
with init_vega(request) as vega:
yield vega
@pytest.fixture(scope="module")
def continuous_market(vega):
return setup_continuous_market(vega)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_limit_buy_order_GTT(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id(tif).select_option("Good 'til Time (GTT)")
@@ -54,8 +51,7 @@ def test_limit_buy_order_GTT(continuous_market, vega: VegaService, page: Page):
"BTC:DAI_2023Futr10+10LimitFilled120.00GTT:"
)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_limit_buy_order(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
@@ -72,8 +68,7 @@ def test_limit_buy_order(continuous_market, vega: VegaService, page: Page):
"BTC:DAI_2023Futr10+10LimitFilled120.00GTC"
)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_limit_sell_order(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id(order_size).fill("10")
@@ -97,8 +92,7 @@ def test_limit_sell_order(continuous_market, vega: VegaService, page: Page):
"BTC:DAI_2023Futr10-10LimitFilled100.00GFN"
)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_market_sell_order(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id(market_order).click()
@@ -122,8 +116,7 @@ def test_market_sell_order(continuous_market, vega: VegaService, page: Page):
"BTC:DAI_2023Futr10-10MarketFilled-IOC"
)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_market_buy_order(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id(market_order).click()
@@ -13,7 +13,7 @@ def continuous_market(vega):
return setup_continuous_market(vega)
@pytest.mark.skip("We currently can't approve wallet connection through Sim")
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_connect_vega_wallet(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id("order-price").fill("101")
@@ -25,7 +25,7 @@ def test_connect_vega_wallet(continuous_market, page: Page):
expect(page.get_by_test_id("order-type-Limit")).to_be_checked()
expect(page.get_by_test_id("order-price")).to_have_value("101")
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_sidebar_should_be_open_after_reload(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
expect(page.get_by_test_id("deal-ticket-form")).to_be_visible()
@@ -12,7 +12,7 @@ market_trading_mode = "market-trading-mode"
@pytest.mark.skip("tbd")
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_margin_and_fees_estimations(continuous_market, vega: VegaService, page: Page):
# setup continuous trading market with one user buy trade
market_id = continuous_market
@@ -38,7 +38,6 @@ timeInForce_col = '[col-id="submission.timeInForce"]'
updatedAt_col = '[col-id="updatedAt"]'
close_toast = "toast-close"
def create_position(vega: VegaService, market_id):
submit_order(vega, "Key 1", market_id, "SIDE_SELL", 100, 110)
submit_order(vega, "Key 1", market_id, "SIDE_BUY", 100, 110)
@@ -46,7 +45,7 @@ def create_position(vega: VegaService, market_id):
vega.wait_fn(1)
vega.wait_for_total_catchup
@pytest.mark.usefixtures("page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_stop_order_form_error_validation(continuous_market, page: Page):
# 7002-SORD-032
page.goto(f"/#/markets/{continuous_market}")
@@ -69,7 +68,7 @@ def test_stop_order_form_error_validation(continuous_market, page: Page):
)
@pytest.mark.skip("core issue")
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_order_rejected(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id(stop_orders_tab).click()
@@ -107,7 +106,7 @@ def test_submit_stop_order_rejected(continuous_market, vega: VegaService, page:
).not_to_be_empty()
@pytest.mark.skip("core issue")
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_market_order_triggered(
continuous_market, vega: VegaService, page: Page
):
@@ -165,7 +164,7 @@ def test_submit_stop_market_order_triggered(
).not_to_be_empty()
@pytest.mark.skip("core issue")
@pytest.mark.usefixtures("continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_limit_order_pending(
continuous_market, vega: VegaService, page: Page
):
@@ -226,7 +225,7 @@ def test_submit_stop_limit_order_pending(
).not_to_be_empty()
@pytest.mark.skip("core issue")
@pytest.mark.usefixtures("continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_limit_order_cancel(
continuous_market, vega: VegaService, page: Page
):
@@ -270,7 +269,7 @@ class TestStopOcoValidation:
def continuous_market(self, vega):
return setup_continuous_market(vega)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_stop_market_order_form_validation(self, continuous_market, page: Page):
# 7002-SORD-052
# 7002-SORD-055
@@ -303,7 +302,7 @@ class TestStopOcoValidation:
expect(page.get_by_test_id(order_size)).to_be_empty
expect(page.get_by_test_id(order_price)).not_to_be_visible()
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_stop_limit_order_form_validation(self, continuous_market, page: Page):
# 7002-SORD-020
# 7002-SORD-021
@@ -347,7 +346,7 @@ class TestStopOcoValidation:
expect(page.get_by_test_id(order_price)).to_be_empty()
@pytest.mark.skip("core issue")
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_maximum_number_of_active_stop_orders(
self, continuous_market, vega: VegaService, page: Page
):
@@ -4,7 +4,6 @@ from vega_sim.service import VegaService
from actions.vega import submit_order
from actions.utils import wait_for_toast_confirmation
stop_order_btn = "order-type-Stop"
stop_limit_order_btn = "order-type-StopLimit"
stop_market_order_btn = "order-type-StopMarket"
@@ -50,7 +49,7 @@ def create_position(vega: VegaService, market_id):
vega.wait_for_total_catchup
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_order_market_oco_rejected(
continuous_market, vega: VegaService, page: Page
):
@@ -127,7 +126,7 @@ def test_submit_stop_order_market_oco_rejected(
assert trigger_price_list.sort() == trigger_value_list.sort()
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_oco_market_order_triggered(
continuous_market, vega: VegaService, page: Page
):
@@ -204,7 +203,7 @@ def test_submit_stop_oco_market_order_triggered(
assert trigger_price_list.sort() == trigger_value_list.sort()
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_oco_market_order_pending(
continuous_market, vega: VegaService, page: Page
):
@@ -236,7 +235,7 @@ def test_submit_stop_oco_market_order_pending(
"PendingOCO"
)
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("page", "continuous_market", "auth", "risk_accepted")
def test_submit_stop_oco_limit_order_pending(
continuous_market, vega: VegaService, page: Page
):
@@ -287,7 +286,7 @@ def test_submit_stop_oco_limit_order_pending(
assert trigger_price_list.sort() == trigger_value_list.sort()
@pytest.mark.usefixtures("page", "vega", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_submit_stop_oco_limit_order_cancel(
continuous_market, vega: VegaService, page: Page
):
@@ -325,5 +324,3 @@ def test_submit_stop_oco_limit_order_cancel(
expect(
page.locator(".ag-center-cols-container").locator('[col-id="status"]').last
).to_have_text("CancelledOCO")
@@ -5,8 +5,6 @@ from actions.utils import change_keys
from conftest import init_vega
from fixtures.market import setup_continuous_market
order_size = "order-size"
order_price = "order-price"
place_order = "place-order"
@@ -18,13 +16,12 @@ def vega(request):
with init_vega(request) as vega:
yield vega
@pytest.fixture(scope="module")
def continuous_market(vega):
return setup_continuous_market(vega)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def test_should_display_info_and_button_for_deposit(continuous_market, vega: VegaService, page: Page):
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_should_display_info_and_button_for_deposit(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id(order_size).fill("200000")
page.get_by_test_id(order_price).fill("20")
@@ -35,7 +32,7 @@ def test_should_display_info_and_button_for_deposit(continuous_market, vega: Veg
page.get_by_test_id(deal_ticket_deposit_dialog_button).nth(0).click()
expect(page.get_by_test_id("sidebar-content")).to_contain_text("DepositFrom")
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_should_show_an_error_if_your_balance_is_zero(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
vega.create_key("key_empty")
@@ -10,20 +10,16 @@ import logging
logger = logging.getLogger()
@pytest.fixture(scope="class")
def vega():
with init_vega() as vega:
yield vega
# we can reuse vega market-sim service and market in almost all tests
@pytest.fixture(scope="class")
def simple_market(vega: VegaService):
return setup_simple_market(vega)
class TestGetStarted:
@pytest.mark.usefixtures("page")
def test_get_started_interactive(self, vega: VegaService, page: Page):
page.goto("/")
# 0007-FUGS-001
@@ -134,8 +130,7 @@ class TestGetStarted:
# Assert dialog isn't visible
expect(page.get_by_test_id("welcome-dialog")).not_to_be_visible()
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_get_started_seen_already(self, simple_market, page: Page):
page.goto(f"/#/markets/{simple_market}")
get_started_locator = page.get_by_test_id("connect-vega-wallet")
@@ -148,8 +143,6 @@ class TestGetStarted:
# 0007-FUGS-007
expect(page.get_by_test_id("dialog-content").nth(1)).to_be_visible()
@pytest.mark.usefixtures("page")
def test_browser_wallet_installed(self, simple_market, page: Page):
page.add_init_script("window.vega = {}")
page.goto(f"/#/markets/{simple_market}")
@@ -159,14 +152,13 @@ class TestGetStarted:
expect(locator).to_be_visible
expect(locator).to_have_text("Connect")
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_get_started_deal_ticket(self,simple_market, page: Page):
page.goto(f"/#/markets/{simple_market}")
expect(page.get_by_test_id("order-connect-wallet")).to_have_text("Connect wallet")
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_browser_wallet_installed_deal_ticket(simple_market, page: Page):
page.add_init_script("window.vega = {}")
page.goto(f"/#/markets/{simple_market}")
@@ -174,7 +166,6 @@ class TestGetStarted:
page.wait_for_selector('[data-testid="sidebar-content"]', state="visible")
expect(page.get_by_test_id("get-started-banner")).not_to_be_visible()
@pytest.mark.usefixtures("page")
def test_redirect_default_market(self, continuous_market, vega: VegaService, page: Page):
page.goto("/")
# 0007-FUGS-012
@@ -186,7 +177,6 @@ class TestGetStarted:
expect(page.get_by_test_id("welcome-dialog")).not_to_be_visible()
class TestBrowseAll:
@pytest.mark.usefixtures("page")
def test_get_started_browse_all(self, simple_market, vega: VegaService, page: Page):
page.goto("/")
print(simple_market)
@@ -11,7 +11,6 @@ def hover_and_assert_tooltip(page: Page, element_text):
element.hover()
expect(page.get_by_role("tooltip")).to_be_visible()
class TestIcebergOrdersValidations:
@pytest.fixture(scope="class")
def vega(self, request):
@@ -22,7 +21,7 @@ class TestIcebergOrdersValidations:
def continuous_market(self, vega):
return setup_continuous_market(vega)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_iceberg_submit(self, continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id("iceberg").click()
@@ -47,7 +46,7 @@ class TestIcebergOrdersValidations:
(page.get_by_role("row").locator('[col-id="type"]')).nth(1)
).to_have_text("Limit (Iceberg)")
@pytest.mark.usefixtures("vega", "page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_iceberg_open_order(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
@@ -17,27 +17,34 @@ def continuous_market(vega):
return setup_continuous_market(vega)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_liquidity_provision_amendment(continuous_market, vega: VegaService, page: Page):
# TODO Refactor asserting the grid
page.goto(f"/#/liquidity/{continuous_market}")
change_keys(page, vega, "market_maker")
row = page.get_by_test_id("tab-myLP").locator(".ag-center-cols-container .ag-row").first
row = page.get_by_test_id(
"tab-myLP").locator(".ag-center-cols-container .ag-row").first
expect(row).to_contain_text(
"Active"
)
# 5002-LIQP-006
expect(page.get_by_test_id("target-stake")).to_have_text("Target stake5.82757 tDAI")
expect(page.get_by_test_id("target-stake")
).to_have_text("Target stake5.82757 tDAI")
# 5002-LIQP-007
expect(page.get_by_test_id("supplied-stake")).to_have_text("Supplied stake10,000.00 tDAI")
expect(page.get_by_test_id("supplied-stake")
).to_have_text("Supplied stake10,000.00 tDAI")
# 5002-LIQP-008
expect(page.get_by_test_id("liquidity-supplied")).to_have_text("Liquidity supplied 171,598.11%")
expect(page.get_by_test_id("liquidity-supplied")
).to_have_text("Liquidity supplied 171,598.11%")
expect(page.get_by_test_id("fees-paid")).to_have_text("Fees paid-")
# 5002-LIQP-009
expect(page.get_by_test_id("liquidity-market-id")).to_have_text("Market ID" + truncate_middle(continuous_market))
expect(page.get_by_test_id("liquidity-learn-more")).to_have_text("Learn moreProviding liquidity")
expect(page.get_by_test_id("liquidity-market-id")
).to_have_text("Market ID" + truncate_middle(continuous_market))
expect(page.get_by_test_id("liquidity-learn-more")
).to_have_text("Learn moreProviding liquidity")
# 002-LIQP-010
expect(page.get_by_test_id("liquidity-learn-more").get_by_test_id("external-link")).to_have_attribute("href", "https://docs.vega.xyz/testnet/concepts/liquidity/provision")
expect(page.get_by_test_id("liquidity-learn-more").get_by_test_id("external-link")
).to_have_attribute("href", "https://docs.vega.xyz/testnet/concepts/liquidity/provision")
vega.submit_simple_liquidity(
key_name="market_maker",
@@ -50,26 +57,32 @@ def test_liquidity_provision_amendment(continuous_market, vega: VegaService, pag
vega.wait_fn(1)
vega.wait_for_total_catchup()
page.reload()
row = page.get_by_test_id("tab-myLP").locator(".ag-center-cols-container .ag-row").first
row = page.get_by_test_id(
"tab-myLP").locator(".ag-center-cols-container .ag-row").first
expect(row).to_contain_text(
"Updating next epoch"
)
next_epoch(vega=vega)
page.reload()
expect(page.get_by_test_id("supplied-stake")).to_have_text("Supplied stake1.00001 tDAI")
expect(page.get_by_test_id("liquidity-supplied")).to_have_text("Liquidity supplied 17.16%")
row = page.get_by_test_id("tab-myLP").locator(".ag-center-cols-container .ag-row").first
expect(page.get_by_test_id("supplied-stake")
).to_have_text("Supplied stake1.00001 tDAI")
expect(page.get_by_test_id("liquidity-supplied")
).to_have_text("Liquidity supplied 17.16%")
row = page.get_by_test_id(
"tab-myLP").locator(".ag-center-cols-container .ag-row").first
expect(row).to_contain_text(
"Active"
)
@pytest.mark.skip("Waiting for the ability to cancel LP")
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_liquidity_provision_inactive(continuous_market, vega: VegaService, page: Page):
# TODO Refactor asserting the grid
page.goto(f"/#/liquidity/{continuous_market}")
change_keys(page,vega, "market_maker")
row = page.get_by_test_id("tab-myLP").locator(".ag-center-cols-container .ag-row").first
change_keys(page, vega, "market_maker")
row = page.get_by_test_id(
"tab-myLP").locator(".ag-center-cols-container .ag-row").first
expect(row).to_contain_text(
"Active"
)
@@ -82,4 +95,3 @@ def test_liquidity_provision_inactive(continuous_market, vega: VegaService, page
)
vega.wait_fn(1)
vega.wait_for_total_catchup()
@@ -12,6 +12,7 @@ def vega():
with init_vega() as vega:
yield vega
@pytest.fixture(scope="class")
def create_settled_market(vega: VegaService):
market_id = setup_continuous_market(vega)
@@ -73,8 +74,9 @@ class TestSettledMarket:
# 6001-MARK-010
pattern = r"(\d+)\s+(months|hours|days)\s+ago"
date_text = row_selector.locator('[col-id="settlementDate"]').inner_text()
assert re.match(pattern, date_text), f"Expected text to match pattern but got {date_text}"
assert re.match(
pattern, date_text
), f"Expected text to match pattern but got {date_text}"
expected_pattern = re.compile(r"https://.*?/oracles/[a-f0-9]{64}")
actual_href = row_selector.locator(
@@ -87,12 +89,12 @@ class TestSettledMarket:
expect(row_selector.locator('[col-id="bestBidPrice"]')).to_have_text("0.00")
# 6001-MARK-012
expect(row_selector.locator('[col-id="bestOfferPrice"]')).to_have_text("0.00")
# 6001-MARK-013
# 6001-MARK-013
expect(row_selector.locator('[col-id="markPrice"]')).to_have_text("110.00")
# 6001-MARK-014
# 6001-MARK-015
# 6001-MARK-016
#tbd currently we have value unknown
# tbd currently we have value unknown
# expect(row_selector.locator('[col-id="settlementDataOracleId"]')).to_have_text(
# "110.00"
# )
@@ -107,7 +109,9 @@ class TestSettledMarket:
# 6001-MARK-018
expect(row_selector.locator('[col-id="settlementAsset"]')).to_have_text("tDAI")
# 6001-MARK-020
assert re.match(pattern, date_text), f"Expected text to match pattern but got {date_text}"
assert re.match(
pattern, date_text
), f"Expected text to match pattern but got {date_text}"
@pytest.mark.usefixtures("risk_accepted", "auth")
+15 -9
View File
@@ -31,7 +31,7 @@ initial_spread: float = 0.1
market_name = "BTC:DAI_2023"
@pytest.mark.usefixtures("vega", "page", "simple_market", "risk_accepted", "auth")
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_price_monitoring(simple_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/all")
expect(page.locator(table_row_selector).locator(trading_mode_col)).to_have_text(
@@ -75,7 +75,7 @@ def test_price_monitoring(simple_market, vega: VegaService, page: Page):
time_in_force="TIME_IN_FORCE_GTC",
volume=99,
)
#6002-MDET-009
# 6002-MDET-009
expect(
page.get_by_test_id(liquidity_supplied).get_by_test_id(item_value)
).to_have_text("0.00 (0.00%)")
@@ -154,7 +154,7 @@ def test_price_monitoring(simple_market, vega: VegaService, page: Page):
vega.forward("10s")
vega.wait_fn(1)
vega.wait_for_total_catchup()
vega.wait_for_total_catchup()
expect(
page.get_by_test_id(price_monitoring_bounds_row).first.get_by_text(
"135.44204 BTC"
@@ -191,22 +191,28 @@ def test_price_monitoring(simple_market, vega: VegaService, page: Page):
)
# commented out because we have an issue #4233
# expect(page.get_by_text("Opening auction")).to_be_hidden()
#6002-MDET-009
# 6002-MDET-009
expect(
page.get_by_test_id(liquidity_supplied).get_by_test_id(item_value)
).to_have_text("50.00 (>100%)")
COL_ID_FEE = ".ag-center-cols-container [col-id='fee'] .ag-cell-value"
@pytest.mark.usefixtures("vega", "page", "continuous_market", "risk_accepted", "auth")
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_auction_uncross_fees(continuous_market, vega: VegaService, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id("Fills").click()
expect(page.locator(COL_ID_FEE)).to_have_text("0.00 tDAI")
page.locator(COL_ID_FEE).hover()
expect(page.get_by_test_id("fee-breakdown-tooltip")).to_have_text("If the market was suspendedIf the market is in monitoring auction, half of the infrastructure and liquidity fees will be paid.Infrastructure fee0.00 tDAILiquidity fee0.00 tDAIMaker fee0.00 tDAITotal fees0.00 tDAI")
change_keys(page,vega, "market_maker")
expect(page.get_by_test_id("fee-breakdown-tooltip")).to_have_text(
"If the market was suspendedIf the market is in monitoring auction, half of the infrastructure and liquidity fees will be paid.Infrastructure fee0.00 tDAILiquidity fee0.00 tDAIMaker fee0.00 tDAITotal fees0.00 tDAI"
)
change_keys(page, vega, "market_maker")
expect(page.locator(COL_ID_FEE)).to_have_text("0.00 tDAI")
page.locator(COL_ID_FEE).hover()
expect(page.get_by_test_id("fee-breakdown-tooltip")).to_have_text("If the market was suspendedIf the market is in monitoring auction, half of the infrastructure and liquidity fees will be paid.Infrastructure fee0.00 tDAILiquidity fee0.00 tDAIMaker fee0.00 tDAITotal fees0.00 tDAI")
expect(page.get_by_test_id("fee-breakdown-tooltip")).to_have_text(
"If the market was suspendedIf the market is in monitoring auction, half of the infrastructure and liquidity fees will be paid.Infrastructure fee0.00 tDAILiquidity fee0.00 tDAIMaker fee0.00 tDAITotal fees0.00 tDAI"
)
@@ -3,7 +3,6 @@ import pytest
from playwright.sync_api import Page, expect
from vega_sim.service import VegaService
from fixtures.market import setup_continuous_market
from conftest import init_page, init_vega, risk_accepted_setup
market_title_test_id = "accordion-title"
@@ -15,10 +14,9 @@ def vega():
yield vega
# setting up everything in this single fixture, as all of the tests need the same setup, so no point in creating separate ones
@pytest.fixture(scope="module")
def page(vega, browser, request):
with init_page(vega, browser, request) as page:
def page(vega, browser, request, local_server):
with init_page(vega, browser, request, local_server) as page:
setup_continuous_market(vega)
risk_accepted_setup(page)
page.goto("/")
@@ -122,7 +120,9 @@ def test_market_info_instrument(page: Page):
# @pytest.mark.skip("oracle test to be fixed")
def test_market_info_oracle(page: Page, vega: VegaService):
def test_market_info_oracle(page: Page):
# 6002-MDET-203
page.get_by_test_id(market_title_test_id).get_by_text("Oracle").click()
expect(
@@ -2,7 +2,7 @@ import pytest
from playwright.sync_api import expect, Page
@pytest.mark.usefixtures("page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_market_selector(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
expect(page.get_by_test_id("market-selector")).not_to_be_visible()
@@ -27,7 +27,7 @@ def test_market_selector(continuous_market, page: Page):
expect(btc_market.locator('[data-testid="sparkline-svg"]')).not_to_be_visible
@pytest.mark.usefixtures("page", "continuous_market", "simple_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("simple_market", "auth", "risk_accepted")
@pytest.mark.parametrize(
"simple_market",
[
@@ -1,6 +1,5 @@
import pytest
from playwright.sync_api import Page, expect
from vega_sim.service import VegaService
from conftest import init_page, init_vega, risk_accepted_setup
@@ -12,8 +11,8 @@ def vega(request):
@pytest.fixture(scope="module")
def page(vega, browser, request):
with init_page(vega, browser, request) as page:
def page(vega, browser, request, local_server):
with init_page(vega, browser, request, local_server) as page:
risk_accepted_setup(page)
page.goto("/#/markets/all")
yield page
@@ -5,7 +5,7 @@ from playwright.sync_api import Page, expect
from vega_sim.service import VegaService
from conftest import init_vega
from fixtures.market import setup_simple_market
from wallet_config import MM_WALLET, MM_WALLET2, TERMINATE_WALLET, wallets
from wallet_config import MM_WALLET
row_selector = '[data-testid="tab-proposed-markets"] .ag-center-cols-container .ag-row'
col_market_id = '[col-id="market"] [data-testid="stack-cell-primary"]'
@@ -16,6 +16,7 @@ def vega(request):
with init_vega(request) as vega:
yield vega
@pytest.fixture(scope="module")
def proposed_market(vega: VegaService):
# setup market without liquidity provided
@@ -7,6 +7,7 @@ from conftest import init_vega
from actions.utils import wait_for_toast_confirmation
from wallet_config import MM_WALLET, MM_WALLET2
@pytest.fixture(scope="module")
def vega(request):
with init_vega(request) as vega:
@@ -17,6 +18,7 @@ def vega(request):
def simple_market(vega):
return setup_simple_market(vega)
@pytest.fixture(scope="module")
def setup_market_monitoring_auction(vega: VegaService, simple_market):
vega.submit_liquidity(
@@ -48,12 +50,18 @@ def setup_market_monitoring_auction(vega: VegaService, simple_market):
volume=99,
)
# add orders to provide liquidity
submit_order(vega, MM_WALLET.name, simple_market, "SIDE_BUY", 1, 1)
submit_order(vega, MM_WALLET.name, simple_market, "SIDE_SELL", 1, 1)
submit_order(vega,MM_WALLET.name,simple_market, "SIDE_BUY",1,1 + 0.1 / 2,)
submit_order(vega,MM_WALLET.name,simple_market,"SIDE_SELL",1,1 + 0.1 / 2)
submit_order(
vega,
MM_WALLET.name,
simple_market,
"SIDE_BUY",
1,
1 + 0.1 / 2,
)
submit_order(vega, MM_WALLET.name, simple_market, "SIDE_SELL", 1, 1 + 0.1 / 2)
submit_order(vega, MM_WALLET2.name, simple_market, "SIDE_SELL", 1, 1)
vega.forward("10s")
@@ -71,9 +79,11 @@ def setup_market_monitoring_auction(vega: VegaService, simple_market):
vega.wait_fn(1)
vega.wait_for_total_catchup()
@pytest.mark.usefixtures("page", "risk_accepted", "simple_market", "auth", "setup_market_monitoring_auction")
def test_market_monitoring_auction_price_volatility_limit_order(page: Page, simple_market, vega: VegaService):
@pytest.mark.usefixtures("risk_accepted", "auth", "setup_market_monitoring_auction")
def test_market_monitoring_auction_price_volatility_limit_order(
page: Page, simple_market, vega: VegaService
):
page.goto(f"/#/markets/{simple_market}")
page.get_by_test_id("order-size").clear()
page.get_by_test_id("order-size").type("1")
@@ -82,10 +92,14 @@ def test_market_monitoring_auction_price_volatility_limit_order(page: Page, simp
page.get_by_test_id("order-tif").select_option("Fill or Kill (FOK)")
page.get_by_test_id("place-order").click()
expect(page.get_by_test_id("deal-ticket-error-message-tif")).to_have_text("This market is in auction due to high price volatility. Until the auction ends, you can only place GFA, GTT, or GTC limit orders.")
expect(page.get_by_test_id("deal-ticket-error-message-tif")).to_have_text(
"This market is in auction due to high price volatility. Until the auction ends, you can only place GFA, GTT, or GTC limit orders."
)
expect(page.get_by_test_id("deal-ticket-error-message-tif")).to_be_visible()
expect(page.get_by_test_id("deal-ticket-warning-auction")).to_have_text("Any orders placed now will not trade until the auction ends")
expect(page.get_by_test_id("deal-ticket-warning-auction")).to_have_text(
"Any orders placed now will not trade until the auction ends"
)
expect(page.get_by_test_id("deal-ticket-warning-auction")).to_be_visible()
page.get_by_test_id("order-tif").select_option("Good 'til Cancelled (GTC)")
@@ -103,8 +117,11 @@ def test_market_monitoring_auction_price_volatility_limit_order(page: Page, simp
"BTC:DAI_2023Futr0+1LimitActive110.00GTC"
)
@pytest.mark.usefixtures("page", "risk_accepted", "simple_market", "auth", "setup_market_monitoring_auction")
def test_market_monitoring_auction_price_volatility_market_order(page: Page, simple_market):
@pytest.mark.usefixtures("risk_accepted", "auth", "setup_market_monitoring_auction")
def test_market_monitoring_auction_price_volatility_market_order(
page: Page, simple_market
):
page.goto(f"/#/markets/{simple_market}")
page.get_by_test_id("order-type-Market").click()
page.get_by_test_id("order-size").clear()
@@ -112,8 +129,12 @@ def test_market_monitoring_auction_price_volatility_market_order(page: Page, sim
# 7002-SORD-060
page.get_by_test_id("place-order").click()
expect(page.get_by_test_id("deal-ticket-error-message-tif")).to_have_text("This market is in auction due to high price volatility. Until the auction ends, you can only place GFA, GTT, or GTC limit orders.")
expect(page.get_by_test_id("deal-ticket-error-message-tif")).to_have_text(
"This market is in auction due to high price volatility. Until the auction ends, you can only place GFA, GTT, or GTC limit orders."
)
expect(page.get_by_test_id("deal-ticket-error-message-tif")).to_be_visible()
expect(page.get_by_test_id("deal-ticket-error-message-type")).to_have_text("This market is in auction due to high price volatility. Only limit orders are permitted when market is in auction.")
expect(page.get_by_test_id("deal-ticket-error-message-type")).to_have_text(
"This market is in auction due to high price volatility. Only limit orders are permitted when market is in auction."
)
expect(page.get_by_test_id("deal-ticket-error-message-type")).to_be_visible()
@@ -9,8 +9,7 @@ from actions.utils import next_epoch
from wallet_config import MM_WALLET, MM_WALLET2, GOVERNANCE_WALLET
@pytest.mark.usefixtures("vega", "page", "proposed_market", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_market_lifecycle(proposed_market, vega: VegaService, page: Page):
# 7002-SORD-001
# 7002-SORD-002
@@ -27,8 +26,12 @@ def test_market_lifecycle(proposed_market, vega: VegaService, page: Page):
# 6002-MDET-002
expect(page.get_by_test_id("market-expiry")).to_have_text("ExpiryNot time-based")
page.get_by_test_id("market-expiry").hover()
expect(page.get_by_test_id("expiry-tooltip").first).to_have_text("This market expires when triggered by its oracle, not on a set date.View oracle specification")
expect(page.get_by_test_id("expiry-tooltip").first.get_by_test_id("link")).to_have_attribute("href", re.compile('.*'))
expect(page.get_by_test_id("expiry-tooltip").first).to_have_text(
"This market expires when triggered by its oracle, not on a set date.View oracle specification"
)
expect(
page.get_by_test_id("expiry-tooltip").first.get_by_test_id("link")
).to_have_attribute("href", re.compile(".*"))
# 6002-MDET-003
expect(page.get_by_test_id("market-price")).to_have_text("Mark Price0.00")
# 6002-MDET-004
@@ -36,18 +39,30 @@ def test_market_lifecycle(proposed_market, vega: VegaService, page: Page):
# 6002-MDET-005
expect(page.get_by_test_id("market-volume")).to_have_text("Volume (24h)-")
# 6002-MDET-008
expect(page.get_by_test_id("market-settlement-asset")).to_have_text("Settlement assettDAI")
expect(page.get_by_test_id("liquidity-supplied")).to_have_text("Liquidity supplied 0.00 (0.00%)")
expect(page.get_by_test_id("market-settlement-asset")).to_have_text(
"Settlement assettDAI"
)
expect(page.get_by_test_id("liquidity-supplied")).to_have_text(
"Liquidity supplied 0.00 (0.00%)"
)
page.get_by_test_id("liquidity-supplied").hover()
expect(page.get_by_test_id("liquidity-supplied-tooltip").first).to_have_text("Supplied stake0.00Target stake0.00View liquidity provision tableLearn about providing liquidity")
expect(page.get_by_test_id("liquidity-supplied-tooltip").first.get_by_test_id("link").first).to_have_text("View liquidity provision table")
expect(page.get_by_test_id("liquidity-supplied-tooltip").first).to_have_text(
"Supplied stake0.00Target stake0.00View liquidity provision tableLearn about providing liquidity"
)
expect(
page.get_by_test_id("liquidity-supplied-tooltip")
.first.get_by_test_id("link")
.first
).to_have_text("View liquidity provision table")
# check that market is in proposed state
# 6002-MDET-006
# 6002-MDET-007
# 7002-SORD-061
expect(trading_mode).to_have_text("No trading")
trading_mode.hover()
expect(page.get_by_test_id("trading-mode-tooltip").first).to_have_text("No trading enabled for this market.")
expect(page.get_by_test_id("trading-mode-tooltip").first).to_have_text(
"No trading enabled for this market."
)
expect(market_state).to_have_text("Proposed")
# approve market
@@ -182,4 +197,4 @@ def test_market_closing_banners(page: Page, continuous_market, vega: VegaService
will_close_pattern = r"TRADING ON MARKET BTC:DAI_2023 WILL STOP ON \d+ \w+\nYou will no longer be able to hold a position on this market when it closes in \d+ days \d+ hours\. The final price will be 107\.00 BTC\."
match_result = re.fullmatch(will_close_pattern, page.locator(".grow").inner_text())
assert match_result is not None
"""
"""
@@ -12,8 +12,8 @@ def vega():
# we can reuse single page instance in all tests
@pytest.fixture(scope="module")
def page(vega, browser, request):
with init_page(vega, browser, request) as page:
def page(vega, browser, request, local_server):
with init_page(vega, browser, request, local_server) as page:
yield page
@@ -48,8 +48,9 @@ def verify_order_value(
else:
expect(element).to_have_text(expected_text)
@pytest.mark.skip("tbd")
@pytest.mark.usefixtures("vega", "page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_order_details_are_correctly_displayed(
continuous_market, vega: VegaService, page: Page
):
@@ -8,6 +8,7 @@ from actions.vega import submit_order
logger = logging.getLogger()
# Could be turned into a helper function in the future.
def verify_data_grid(page: Page, data_test_id, expected_pattern):
page.get_by_test_id(data_test_id).click()
@@ -49,9 +50,7 @@ def submit_order(vega: VegaService, wallet_name, market_id, side, volume, price)
)
@pytest.mark.usefixtures(
"vega", "page", "opening_auction_market", "auth", "risk_accepted"
)
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_limit_order_trade_open_order(
opening_auction_market, vega: VegaService, page: Page
):
@@ -80,7 +79,7 @@ def test_limit_order_trade_open_order(
verify_data_grid(page, "Open", expected_open_order)
@pytest.mark.usefixtures("vega", "page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_limit_order_trade_open_position(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
@@ -148,7 +147,7 @@ def test_limit_order_trade_open_position(continuous_market, page: Page):
expect(unrealisedPNL).to_have_text(position["unrealised_pnl"])
@pytest.mark.usefixtures("vega", "page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_limit_order_trade_order_trade_away(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
# Assert that the order is no longer on the orderbook
@@ -223,8 +223,8 @@ def markets(vega: VegaService):
@pytest.fixture(scope="module")
def page(vega, browser, request):
with init_page(vega, browser, request) as page:
def page(vega, browser, request, local_server):
with init_page(vega, browser, request, local_server) as page:
risk_accepted_setup(page)
auth_setup(vega, page)
page.goto("/")
@@ -6,6 +6,7 @@ from conftest import init_vega
from fixtures.market import setup_simple_market
from wallet_config import MM_WALLET, MM_WALLET2
@pytest.fixture(scope="module")
def vega():
with init_vega() as vega:
@@ -78,8 +79,9 @@ def verify_prices_descending(page: Page):
prices = [float(price.text_content()) for price in prices_locator.all()]
assert prices == sorted(prices, reverse=True)
@pytest.mark.skip("tbd")
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_orderbook_grid_content(setup_market, page: Page):
vega = setup_market[0]
market_id = setup_market[1]
@@ -138,7 +140,7 @@ def test_orderbook_grid_content(setup_market, page: Page):
verify_prices_descending(page)
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_orderbook_resolution_change(setup_market, page: Page):
market_id = setup_market[1]
# 6003-ORDB-008
@@ -188,7 +190,7 @@ def test_orderbook_resolution_change(setup_market, page: Page):
# verify_orderbook_grid(page, resolution[1])
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_orderbook_price_size_copy(setup_market, page: Page):
market_id = setup_market[1]
# 6003-ORDB-009
@@ -206,8 +208,9 @@ def test_orderbook_price_size_copy(setup_market, page: Page):
volume.click()
expect(page.get_by_test_id("order-size")).to_have_value(volume.text_content())
@pytest.mark.skip("tbd")
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_orderbook_price_movement(setup_market, page: Page):
vega = setup_market[0]
market_id = setup_market[1]
@@ -13,8 +13,8 @@ from wallet_config import MM_WALLET, MM_WALLET2, TERMINATE_WALLET
row_selector = '[data-testid="tab-funding-payments"] .ag-center-cols-container .ag-row'
col_amount = '[col-id="amount"]'
class TestPerpetuals:
class TestPerpetuals:
@pytest.fixture(scope="class")
def vega(self, request):
with init_vega(request) as vega:
@@ -53,31 +53,33 @@ class TestPerpetuals:
vega.wait_for_total_catchup()
return perps_market
@pytest.mark.usefixtures("page","risk_accepted", "auth")
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_funding_payment_profit(self, perps_market, page: Page):
page.goto(f"/#/markets/{perps_market}")
page.goto(f"/#/markets/{perps_market}")
page.get_by_test_id("Funding payments").click()
row = page.locator(row_selector)
expect(row.locator(col_amount)).to_have_text("9.00 tDAI")
@pytest.mark.usefixtures("page","risk_accepted", "auth")
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_funding_payment_loss(self, perps_market, page: Page, vega):
page.goto(f"/#/markets/{perps_market}")
page.goto(f"/#/markets/{perps_market}")
change_keys(page, vega, "market_maker")
page.get_by_test_id("Funding payments").click()
row = page.locator(row_selector)
expect(row.locator(col_amount)).to_have_text("-27.00 tDAI")
@pytest.mark.usefixtures("page","risk_accepted", "auth")
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_funding_header(self, perps_market, page: Page):
page.goto(f"/#/markets/{perps_market}")
expect(page.get_by_test_id("market-funding")).to_contain_text("Funding Rate / Countdown-8.1818%")
expect(page.get_by_test_id("market-funding")).to_contain_text(
"Funding Rate / Countdown-8.1818%"
)
expect(page.get_by_test_id("index-price")).to_have_text("Index Price110.00")
@pytest.mark.skip("Skipped due to issue #5421")
@pytest.mark.usefixtures("page","risk_accepted", "auth")
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_funding_payment_history(perps_market, page: Page, vega):
page.goto(f"/#/markets/{perps_market}")
page.goto(f"/#/markets/{perps_market}")
change_keys(page, vega, "market_maker")
page.get_by_test_id("Funding history").click()
element = page.get_by_test_id("tab-funding-history")
@@ -92,30 +94,36 @@ class TestPerpetuals:
else:
print("Bounding box not found for the element")
@pytest.mark.usefixtures("page","risk_accepted", "auth")
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_perps_market_termination_proposed(page: Page, vega: VegaService):
perpetual_market = setup_perps_market(vega)
page.goto(f"/#/markets/{perpetual_market}")
page.goto(f"/#/markets/{perpetual_market}")
vega.update_market_state(
proposal_key=MM_WALLET.name,
market_id=perpetual_market,
market_state=MarketStateUpdateType.Terminate,
price=100,
vote_closing_time = datetime.now() + timedelta(seconds=15),
vote_enactment_time = datetime.now() + timedelta(seconds=60),
approve_proposal = True,
forward_time_to_enactment = False,
vote_closing_time=datetime.now() + timedelta(seconds=15),
vote_enactment_time=datetime.now() + timedelta(seconds=60),
approve_proposal=True,
forward_time_to_enactment=False,
)
vega.forward("10s")
vega.wait_fn(1)
vega.wait_for_total_catchup()
banner_text = page.get_by_test_id(f"termination-warning-banner-{perpetual_market}").text_content()
banner_text = page.get_by_test_id(
f"termination-warning-banner-{perpetual_market}"
).text_content()
pattern = re.compile(
r"Trading on Market BTC:DAI_Perpetual may stop on \d{2} [A-Za-z]+\. There is open proposal to close this market\.Proposed final price is 100\.00 BTC\.View proposal"
r"Trading on Market BTC:DAI_Perpetual may stop on \d{2} [A-Za-z]+\. There is open proposal to close this market\.Proposed final price is 100\.00 BTC\.View proposal"
)
assert pattern.search(banner_text), f"Text did not match pattern. Text was: {banner_text}"
assert pattern.search(
banner_text
), f"Text did not match pattern. Text was: {banner_text}"
@pytest.mark.usefixtures("page","risk_accepted", "auth" )
@pytest.mark.usefixtures("risk_accepted", "auth")
def test_perps_market_terminated(page: Page, vega: VegaService):
perpetual_market = setup_perps_market(vega)
vega.update_market_state(
@@ -123,20 +131,29 @@ def test_perps_market_terminated(page: Page, vega: VegaService):
market_id=perpetual_market,
market_state=MarketStateUpdateType.Terminate,
price=100,
approve_proposal = True,
forward_time_to_enactment = True,
approve_proposal=True,
forward_time_to_enactment=True,
)
vega.forward("10s")
vega.wait_fn(1)
vega.wait_for_total_catchup()
page.goto(f"/#/markets/{perpetual_market}")
page.goto(f"/#/markets/{perpetual_market}")
# TODO change back to have text once bug #5465 is fixed
expect(page.get_by_test_id("market-price")).to_have_text("Mark Price100.00")
expect(page.get_by_test_id("market-change")).to_have_text("Change (24h)-")
expect(page.get_by_test_id("market-volume")).to_have_text("Volume (24h)-")
expect(page.get_by_test_id("market-trading-mode")).to_have_text("Trading modeNo trading")
expect(page.get_by_test_id("market-change")).to_contain_text("Change (24h)-")
expect(page.get_by_test_id("market-volume")).to_contain_text("Volume (24h)-")
expect(page.get_by_test_id("market-trading-mode")).to_have_text(
"Trading modeNo trading"
)
expect(page.get_by_test_id("market-state")).to_have_text("StatusClosed")
expect(page.get_by_test_id("liquidity-supplied")).to_have_text("Liquidity supplied 0.00 (0.00%)")
expect(page.get_by_test_id("market-funding")).to_contain_text("Funding Rate / Countdown")
expect(page.get_by_test_id("liquidity-supplied")).to_have_text(
"Liquidity supplied 0.00 (0.00%)"
)
expect(page.get_by_test_id("market-funding")).to_contain_text(
"Funding Rate / Countdown"
)
expect(page.get_by_test_id("index-price")).to_contain_text("Index Price")
expect(page.get_by_test_id("deal-ticket-error-message-summary")).to_have_text("This market is closed and not accepting orders")
expect(page.get_by_test_id("deal-ticket-error-message-summary")).to_have_text(
"This market is closed and not accepting orders"
)
+9 -3
View File
@@ -4,13 +4,15 @@ from vega_sim.service import VegaService
from actions.vega import submit_order
from actions.utils import change_keys
def check_pnl_color_value(element, expected_color, expected_value):
color = element.evaluate("element => getComputedStyle(element).color")
value = element.inner_text()
assert color == expected_color, f"Unexpected color: {color}"
assert value == expected_value, f"Unexpected value: {value}"
@pytest.mark.usefixtures("vega", "page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_pnl(continuous_market, vega: VegaService, page: Page):
page.set_viewport_size({"width": 1748, "height": 977})
submit_order(vega, "Key 1", continuous_market, "SIDE_BUY", 1, 104.50000)
@@ -59,9 +61,13 @@ def test_pnl(continuous_market, vega: VegaService, page: Page):
key_1_unrealised_pnl = key_1.query_selector('xpath=./div[@col-id="unrealisedPNL"]')
key_1_realised_pnl = key_1.query_selector('xpath=./div[@col-id="realisedPNL"]')
key_mm_unrealised_pnl = key_mm.query_selector('xpath=./div[@col-id="unrealisedPNL"]')
key_mm_unrealised_pnl = key_mm.query_selector(
'xpath=./div[@col-id="unrealisedPNL"]'
)
key_mm_realised_pnl = key_mm.query_selector('xpath=./div[@col-id="realisedPNL"]')
key_mm2_unrealised_pnl = key_mm2.query_selector('xpath=./div[@col-id="unrealisedPNL"]')
key_mm2_unrealised_pnl = key_mm2.query_selector(
'xpath=./div[@col-id="unrealisedPNL"]'
)
key_mm2_realised_pnl = key_mm2.query_selector('xpath=./div[@col-id="realisedPNL"]')
check_pnl_color_value(key_1_realised_pnl, "rgb(0, 0, 0)", "0.00")
check_pnl_color_value(key_1_unrealised_pnl, "rgb(236, 0, 60)", "-4.00")
@@ -2,30 +2,31 @@ import os
import pytest
from playwright.sync_api import Page, expect
from actions.utils import wait_for_toast_confirmation
@pytest.mark.usefixtures("page", "auth", "risk_accepted", "continuous_market")
#TODO migrate to jest
@pytest.mark.usefixtures("auth", "risk_accepted", "continuous_market")
def test_ledger_entries_downloads(page: Page):
page.goto("/#/portfolio")
page.get_by_test_id("Ledger entries").click()
expect(page.get_by_test_id("ledger-download-button")).to_be_enabled()
# 7007-LEEN-001
page.get_by_test_id("ledger-download-button").click()
#7007-LEEN-009
# 7007-LEEN-009
expect(page.get_by_test_id("toast-content")).to_contain_text(("Your file is ready"))
# Get the user's Downloads directory
downloads_directory = os.path.expanduser("~") + "/Downloads/"
# Start waiting for the download
with page.expect_download() as download_info:
# Perform the action that initiates download
# Perform the action that initiates download
page.get_by_role("link", name="Get file here").click()
download = download_info.value
# Wait for the download process to complete and save the downloaded file in the Downloads directory
download.save_as(os.path.join(downloads_directory, download.suggested_filename))
# Verify the download by asserting that the file exists
downloaded_file_path = os.path.join(downloads_directory, download.suggested_filename)
assert os.path.exists(downloaded_file_path), f"Download failed! File not found at: {downloaded_file_path}"
downloaded_file_path = os.path.join(
downloads_directory, download.suggested_filename
)
assert os.path.exists(
downloaded_file_path
), f"Download failed! File not found at: {downloaded_file_path}"
@@ -8,44 +8,60 @@ TOOLTIP_LABEL = "margin-health-tooltip-label"
TOOLTIP_VALUE = "margin-health-tooltip-value"
COL_ID_USED = ".ag-center-cols-container [col-id='used'] .ag-cell-value"
@pytest.fixture(scope="module")
def vega(request):
with init_vega(request) as vega:
yield vega
@pytest.fixture(scope="module")
def continuous_market(vega: VegaService):
return setup_continuous_market(vega)
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_usage_breakdown(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id("Collateral").click()
page.locator(".ag-floating-top-container .ag-row [col-id='used']").click()
usage_breakdown = page.get_by_test_id('usage-breakdown')
usage_breakdown = page.get_by_test_id("usage-breakdown")
# Verify headers
headers = ['Market', 'Account type', 'Balance', 'Margin health']
ag_headers = usage_breakdown.locator('.ag-header-cell-text').element_handles()
headers = ["Market", "Account type", "Balance", "Margin health"]
ag_headers = usage_breakdown.locator(".ag-header-cell-text").element_handles()
for i, header_element in enumerate(ag_headers):
header_text = header_element.text_content()
assert header_text == headers[i]
# Other expectations
expect(usage_breakdown.locator('[class="mb-2 text-sm"]')).to_have_text("You have 1,000,000.00 tDAI in total.")
expect(usage_breakdown.locator('[class="mb-2 text-sm"]')).to_have_text(
"You have 1,000,000.00 tDAI in total."
)
expect(usage_breakdown.locator(COL_ID_USED).first).to_have_text("8.50269 (0%)")
expect(usage_breakdown.locator(COL_ID_USED).nth(1)).to_have_text("999,991.49731 (99%)")
expect(usage_breakdown.locator(COL_ID_USED).nth(1)).to_have_text(
"999,991.49731 (99%)"
)
# Maintenance Level
expect(usage_breakdown.locator(".ag-center-cols-container [col-id='market.id'] .ag-cell-value").first).to_have_text("2.85556 above maintenance level")
expect(
usage_breakdown.locator(
".ag-center-cols-container [col-id='market.id'] .ag-cell-value"
).first
).to_have_text("2.85556 above maintenance level")
# Margin health tooltip
usage_breakdown.get_by_test_id("margin-health-chart-track").hover()
tooltip_data = [("maintenance level", "5.64713"), ("search level", "6.21184"), ("initial level", "8.47069"), ("balance", "8.50269"), ("release level", "9.60012")]
tooltip_data = [
("maintenance level", "5.64713"),
("search level", "6.21184"),
("initial level", "8.47069"),
("balance", "8.50269"),
("release level", "9.60012"),
]
for index, (label, value) in enumerate(tooltip_data):
expect(page.get_by_test_id(TOOLTIP_LABEL).nth(index)).to_have_text(label)
expect(page.get_by_test_id(TOOLTIP_VALUE).nth(index)).to_have_text(value)
page.get_by_test_id('dialog-close').click()
page.get_by_test_id("dialog-close").click()
@@ -5,6 +5,7 @@ from fixtures.market import (
setup_continuous_market,
)
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_closed_market_position(vega: VegaService, page: Page):
market_id = setup_continuous_market(vega)
@@ -26,4 +27,3 @@ def test_closed_market_position(vega: VegaService, page: Page):
expect(market.get_by_test_id("stack-cell-primary")).to_have_text("BTC:DAI_2023")
page.get_by_test_id("open-transfer").click()
expect(page.locator(".ag-overlay-panel")).to_have_text("No positions")
@@ -0,0 +1,175 @@
import pytest
from playwright.sync_api import Page, expect
from vega_sim.service import VegaService
from conftest import init_vega
from fixtures.market import setup_continuous_market, setup_simple_market
from actions.utils import change_keys, create_and_faucet_wallet, forward_time, selector_contains_text
from actions.vega import submit_order, submit_liquidity
from wallet_config import MM_WALLET, PARTY_A, PARTY_B
SELL_ORDERS = [[1, 111], [1, 111], [1, 112], [1, 112], [
1, 113], [1, 113], [1, 114], [1, 114], [1, 115], [1, 115]]
BUY_ORDERS = [[1, 106], [1, 107], [1, 108]]
@pytest.fixture(scope="module")
def vega(request):
with init_vega(request) as vega:
yield vega
@pytest.fixture(scope="module")
def continuous_market(vega):
market = setup_simple_market(vega, custom_quantum=100000)
return setup_continuous_market(vega, market, BUY_ORDERS, SELL_ORDERS, add_liquidity=False)
def generate_referrer_expected_value_dic(expected_base_commission, expected_staking_multiplier, expected_final_commission_rate, expected_volume, expected_num_traders, expected_total_commission):
return {
'[data-testid=my-volume-value]': expected_volume,
'[data-testid=total-commission-value]': expected_total_commission,
'[data-testid=base-commission-rate-value]': expected_base_commission,
'[data-testid=number-of-traders-value]': expected_num_traders,
'[data-testid=final-commission-rate-value]': expected_final_commission_rate,
'[data-testid=staking-multiplier-value]': expected_staking_multiplier
}
def generate_referral_expected_value_dic(expected_volume, expected_tier, expected_discount, expected_epochs, expected_epochs_to_next_tier):
return {
'[data-testid=combined-volume-value]': expected_volume,
'[data-testid=current-tier-value]': expected_tier,
'[data-testid=discount-value]': expected_discount,
'[data-testid=epochs-in-set-value]': expected_epochs,
'[data-testid=epochs-to-next-tier-value]': expected_epochs_to_next_tier
}
def check_tile_values(page: Page, expected_results: dict):
if "referrals" in page.url:
page.reload()
else:
page.goto("/#/referrals/")
for selector, expected_text in expected_results.items():
assert selector_contains_text(
page, selector, expected_text), f"Expected text '{expected_text}' not found in selector '{selector}'"
def create_benefit_tier(minimum_running_notional_taker_volume, minimum_epochs, referral_reward_factor, referral_discount_factor):
return {
"minimum_running_notional_taker_volume": minimum_running_notional_taker_volume,
"minimum_epochs": minimum_epochs,
"referral_reward_factor": referral_reward_factor,
"referral_discount_factor": referral_discount_factor,
}
def create_staking_tier(minimum_staked_tokens, referral_reward_multiplier):
return {
"minimum_staked_tokens": minimum_staked_tokens,
"referral_reward_multiplier": referral_reward_multiplier,
}
def setup_market_and_referral_scheme(vega: VegaService, continuous_market: str, page: Page):
page.goto(f"/#/markets/{continuous_market}")
create_and_faucet_wallet(vega=vega, wallet=PARTY_A)
create_and_faucet_wallet(vega=vega, wallet=PARTY_B)
forward_time(vega)
benefit_tiers = []
staking_tiers = []
for i in range(1, 4):
benefit_tiers.append(create_benefit_tier(
i * 100, i, i * 0.01, i * 0.01))
staking_tiers.append(create_staking_tier(
i * 100, i))
vega.update_referral_program(
proposal_key=MM_WALLET.name,
benefit_tiers=benefit_tiers,
staking_tiers=staking_tiers,
window_length=1,
)
forward_time(vega, True)
vega.create_referral_set(key_name=PARTY_A.name)
forward_time(vega, True)
referral_set_id = list(vega.list_referral_sets().keys())[0]
vega.apply_referral_code(key_name=PARTY_B.name, id=referral_set_id)
tdai_id = vega.find_asset_id(symbol="tDAI")
vega.mint(
"Key 1",
asset=tdai_id,
amount=10e6,
)
vega.mint(
PARTY_B.name,
asset=tdai_id,
amount=10e6,
)
submit_liquidity(vega, MM_WALLET.name, continuous_market, 100, 100)
forward_time(vega)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def test_can_traverse_up_and_down_through_tiers(continuous_market, vega: VegaService, page: Page):
setup_market_and_referral_scheme(vega, continuous_market, page)
change_keys(page, vega, PARTY_B.name)
submit_order(vega, PARTY_B.name, continuous_market, "SIDE_BUY", 1, 115)
forward_time(vega, True)
check_tile_values(page, generate_referral_expected_value_dic(
"110", "1", "1%", "1", "1"))
change_keys(page, vega, PARTY_A.name)
check_tile_values(page, generate_referrer_expected_value_dic(
"1%", "1", "1%", "0", "1", "0"))
change_keys(page, vega, PARTY_B.name)
submit_order(vega, PARTY_B.name, continuous_market, "SIDE_BUY", 2, 115)
forward_time(vega, True)
check_tile_values(page, generate_referral_expected_value_dic(
"221", "2", "2%", "2", "1"))
change_keys(page, vega, PARTY_A.name)
check_tile_values(page, generate_referrer_expected_value_dic(
"2%", "1", "2%", "0", "1", "0"))
change_keys(page, vega, PARTY_B.name)
submit_order(vega, PARTY_B.name, continuous_market, "SIDE_BUY", 3, 115)
forward_time(vega, True)
check_tile_values(page, generate_referral_expected_value_dic(
"331", "3", "3%", "3", "0"))
change_keys(page, vega, PARTY_A.name)
check_tile_values(page, generate_referrer_expected_value_dic(
"3%", "1", "3%", "0", "1", "1"))
change_keys(page, vega, PARTY_B.name)
submit_order(vega, PARTY_B.name, continuous_market, "SIDE_BUY", 1, 115)
forward_time(vega, True)
check_tile_values(page, generate_referral_expected_value_dic(
"110", "1", "1%", "4", "0"))
change_keys(page, vega, PARTY_A.name)
check_tile_values(page, generate_referrer_expected_value_dic(
"1%", "1", "1%", "0", "1", "1"))
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def test_does_not_move_up_tiers_when_not_enough_epochs(continuous_market, vega: VegaService, page: Page):
setup_market_and_referral_scheme(vega, continuous_market, page)
change_keys(page, vega, PARTY_B.name)
submit_order(vega, PARTY_B.name, continuous_market, "SIDE_BUY", 2, 115)
forward_time(vega, True)
check_tile_values(page, generate_referral_expected_value_dic(
"221", "1", "1%", "1", "1"))
change_keys(page, vega, PARTY_A.name)
check_tile_values(page, generate_referrer_expected_value_dic(
"2%", "1", "2%", "0", "1", "0"))
@@ -9,10 +9,9 @@ def vega():
yield vega
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_share_usage_data(page: Page):
page.goto("/")
# page.get_by_test_id("icon-cross").click()
page.get_by_test_id("Settings").click()
telemetry_switch = page.locator("#switch-settings-telemetry-switch")
expect(telemetry_switch).to_have_attribute("data-state", "unchecked")
@@ -41,7 +40,7 @@ ICON_TO_TOAST = {
}
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_toast_positions(page: Page):
page.goto("/")
page.get_by_test_id("Settings").click()
@@ -52,7 +51,7 @@ def test_toast_positions(page: Page):
expect(page.locator(f"[{toast_selector}]")).to_be_visible()
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_dark_mode(page: Page):
page.goto("/")
page.get_by_test_id("Settings").click()
@@ -5,7 +5,7 @@ from fixtures.market import setup_continuous_market, setup_simple_successor_mark
@pytest.fixture
@pytest.mark.usefixtures("vega")
@pytest.mark.usefixtures()
def successor_market(vega: VegaService):
parent_market_id = setup_continuous_market(vega)
tdai_id = vega.find_asset_id(symbol="tDAI")
@@ -23,8 +23,7 @@ def successor_market(vega: VegaService):
return successor_market_id
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_succession_line(page: Page, successor_market):
page.goto(f"/#/markets/{successor_market}")
page.get_by_test_id("Info").click()
@@ -45,8 +45,10 @@ def verify_data_grid(page: Page, data_test_id, expected_pattern):
raise AssertionError(f"Pattern does not match: {expected} != {actual}")
@pytest.mark.usefixtures("page", "continuous_market", "auth", "risk_accepted")
def test_limit_order_new_trade_top_of_list(continuous_market, vega: VegaService, page: Page):
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_limit_order_new_trade_top_of_list(
continuous_market, vega: VegaService, page: Page
):
submit_order(vega, "Key 1", continuous_market, "SIDE_BUY", 1, 110)
vega.wait_fn(1)
vega.wait_for_total_catchup()
@@ -67,7 +69,7 @@ def test_limit_order_new_trade_top_of_list(continuous_market, vega: VegaService,
verify_data_grid(page, "Trades", expected_trade)
@pytest.mark.usefixtures("page", "continuous_market", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_price_copied_to_deal_ticket(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id("Trades").click()
@@ -4,10 +4,9 @@ from vega_sim.service import VegaService
from actions.vega import submit_multiple_orders
@pytest.mark.skip("tbd")
@pytest.mark.usefixtures(
"page", "vega", "opening_auction_market", "auth", "risk_accepted"
)
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_trade_match_table(opening_auction_market: str, vega: VegaService, page: Page):
row_locator = ".ag-center-cols-container .ag-row"
page.goto(f"/#/markets/{opening_auction_market}")
@@ -12,7 +12,7 @@
# InfoItem = namedtuple('InfoItem', ['name', 'infoText'])
# @pytest.mark.skip("temporary skip")
# @pytest.mark.parametrize("vega", [120], indirect=True)
# @pytest.mark.parametrize(, [120], indirect=True)
# @pytest.mark.usefixtures("continuous_market","risk_accepted", "auth")
# def test_trading_chart(continuous_market, vega: VegaService, page: Page):
# page.goto(f"/#/markets/{continuous_market}")
@@ -2,7 +2,13 @@ import pytest
import re
from playwright.sync_api import Page, expect
from vega_sim.service import VegaService
from actions.utils import wait_for_toast_confirmation, create_and_faucet_wallet, WalletConfig, next_epoch, change_keys
from actions.utils import (
wait_for_toast_confirmation,
create_and_faucet_wallet,
WalletConfig,
next_epoch,
change_keys,
)
import vega_sim.proto.vega as vega_protos
LIQ = WalletConfig("liq", "liq")
@@ -10,7 +16,8 @@ PARTY_A = WalletConfig("party_a", "party_a")
PARTY_B = WalletConfig("party_b", "party_b")
PARTY_C = WalletConfig("party_c", "party_c")
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_transfer_submit(continuous_market, vega: VegaService, page: Page):
# 1003-TRAN-001
# 1003-TRAN-006
@@ -19,38 +26,50 @@ def test_transfer_submit(continuous_market, vega: VegaService, page: Page):
# 1003-TRAN-009
# 1003-TRAN-010
# 1003-TRAN-023
page.goto('/#/portfolio')
page.goto("/#/portfolio")
expect(page.get_by_test_id('transfer-form')).to_be_visible
page.get_by_test_id('select-asset').click()
expect(page.get_by_test_id('rich-select-option')).to_have_count(1)
expect(page.get_by_test_id("transfer-form")).to_be_visible
page.get_by_test_id("select-asset").click()
expect(page.get_by_test_id("rich-select-option")).to_have_count(1)
page.get_by_test_id('rich-select-option').click()
page.get_by_test_id("rich-select-option").click()
page.select_option('[data-testid=transfer-form] [name="toVegaKey"]', index=2)
page.select_option('[data-testid=transfer-form] [name="fromAccount"]', index=1)
expected_asset_text = re.compile(r"tDAI tDAI999991.49731 tDAI.{6}….{4}")
actual_asset_text = page.get_by_test_id('select-asset').text_content().strip()
actual_asset_text = page.get_by_test_id("select-asset").text_content().strip()
assert expected_asset_text.search(actual_asset_text), f"Expected pattern not found in {actual_asset_text}"
assert expected_asset_text.search(
actual_asset_text
), f"Expected pattern not found in {actual_asset_text}"
page.locator('[data-testid=transfer-form] input[name="amount"]').fill('1')
expect(page.locator('[data-testid=transfer-form] input[name="amount"]')).not_to_be_empty()
page.locator('[data-testid=transfer-form] input[name="amount"]').fill("1")
expect(
page.locator('[data-testid=transfer-form] input[name="amount"]')
).not_to_be_empty()
page.locator('[data-testid=transfer-form] [type="submit"]').click()
wait_for_toast_confirmation(page)
vega.forward("10s")
vega.wait_fn(1)
vega.wait_for_total_catchup()
expected_confirmation_text = re.compile(r"Transfer completeYour transaction has been confirmedView in block explorerTransferTo .{6}….{6}1\.00 tDAI")
actual_confirmation_text = page.get_by_test_id('toast-content').text_content()
assert expected_confirmation_text.search(actual_confirmation_text), f"Expected pattern not found in {actual_confirmation_text}"
expected_confirmation_text = re.compile(
r"Transfer completeYour transaction has been confirmedView in block explorerTransferTo .{6}….{6}1\.00 tDAI"
)
actual_confirmation_text = page.get_by_test_id("toast-content").text_content()
assert expected_confirmation_text.search(
actual_confirmation_text
), f"Expected pattern not found in {actual_confirmation_text}"
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def test_transfer_vesting_below_minimum(continuous_market, vega: VegaService, page: Page):
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_transfer_vesting_below_minimum(
continuous_market, vega: VegaService, page: Page
):
vega.update_network_parameter(
"market_maker", parameter="transfer.minTransferQuantumMultiple", new_value="100000"
"market_maker",
parameter="transfer.minTransferQuantumMultiple",
new_value="100000",
)
vega.wait_for_total_catchup()
@@ -94,28 +113,34 @@ def test_transfer_vesting_below_minimum(continuous_market, vega: VegaService, pa
vega.wait_for_total_catchup()
next_epoch(vega=vega)
next_epoch(vega=vega)
page.goto('/#/portfolio')
expect(page.get_by_test_id('transfer-form')).to_be_visible
page.goto("/#/portfolio")
expect(page.get_by_test_id("transfer-form")).to_be_visible
change_keys(page, vega, "party_b")
page.get_by_test_id('select-asset').click()
page.get_by_test_id('rich-select-option').click()
page.get_by_test_id("select-asset").click()
page.get_by_test_id("rich-select-option").click()
option_value = page.locator('[data-testid="transfer-form"] [name="fromAccount"] option[value^="ACCOUNT_TYPE_VESTED_REWARDS"]').first.get_attribute("value")
option_value = page.locator(
'[data-testid="transfer-form"] [name="fromAccount"] option[value^="ACCOUNT_TYPE_VESTED_REWARDS"]'
).first.get_attribute("value")
page.select_option('[data-testid="transfer-form"] [name="fromAccount"]', option_value)
page.select_option(
'[data-testid="transfer-form"] [name="fromAccount"]', option_value
)
page.locator('[data-testid=transfer-form] input[name="amount"]').fill('0.000001')
page.locator('[data-testid=transfer-form] input[name="amount"]').fill("0.000001")
page.locator('[data-testid=transfer-form] [type="submit"]').click()
expect(page.get_by_test_id('input-error-text')).to_be_visible
expect(page.get_by_test_id('input-error-text')).to_have_text("Amount below minimum requirements for partial transfer. Use max to bypass")
expect(page.get_by_test_id("input-error-text")).to_be_visible
expect(page.get_by_test_id("input-error-text")).to_have_text(
"Amount below minimum requirements for partial transfer. Use max to bypass"
)
vega.one_off_transfer(
from_key_name=PARTY_B.name,
to_key_name=PARTY_B.name,
from_account_type= vega_protos.vega.AccountType.ACCOUNT_TYPE_VESTED_REWARDS,
to_account_type= vega_protos.vega.AccountType.ACCOUNT_TYPE_GENERAL,
asset= asset_id,
amount= 24.999999,
from_account_type=vega_protos.vega.AccountType.ACCOUNT_TYPE_VESTED_REWARDS,
to_account_type=vega_protos.vega.AccountType.ACCOUNT_TYPE_GENERAL,
asset=asset_id,
amount=24.999999,
)
vega.forward("10s")
vega.wait_fn(10)
@@ -127,6 +152,10 @@ def test_transfer_vesting_below_minimum(continuous_market, vega: VegaService, pa
vega.forward("10s")
vega.wait_fn(1)
vega.wait_for_total_catchup()
expected_confirmation_text = re.compile(r"Transfer completeYour transaction has been confirmedView in block explorerTransferTo .{6}….{6}0\.00001 tDAI")
actual_confirmation_text = page.get_by_test_id('toast-content').text_content()
assert expected_confirmation_text.search(actual_confirmation_text), f"Expected pattern not found in {actual_confirmation_text}"
expected_confirmation_text = re.compile(
r"Transfer completeYour transaction has been confirmedView in block explorerTransferTo .{6}….{6}0\.00001 tDAI"
)
actual_confirmation_text = page.get_by_test_id("toast-content").text_content()
assert expected_confirmation_text.search(
actual_confirmation_text
), f"Expected pattern not found in {actual_confirmation_text}"
+63 -45
View File
@@ -15,6 +15,7 @@ tif = "order-tif"
expire = "expire"
api_request_match = r"http://localhost:\d+/api/v2/requests"
@pytest.fixture(scope="module")
def vega(request):
with init_vega(request) as vega:
@@ -25,50 +26,59 @@ def vega(request):
def continuous_market(vega):
return setup_continuous_market(vega)
def handle_route_connection_lost(route: Route, request):
if request.method == "POST" and re.match(api_request_match, request.url):
route.fulfill(
status=200,
headers={"Content-Type": "application/json"},
body='{"jsonrpc": "2.0", "id": "1"}'
)
else:
route.continue_()
if request.method == "POST" and re.match(api_request_match, request.url):
route.fulfill(
status=200,
headers={"Content-Type": "application/json"},
body='{"jsonrpc": "2.0", "id": "1"}',
)
else:
route.continue_()
def handle_route_connection_rejected(route: Route, request):
if request.method == "POST" and re.match(api_request_match, request.url):
custom_response = {
"jsonrpc": "2.0",
"error": {
"code": 3001,
"data": "the user rejected the wallet connection",
"message": "User error"
},
"id": "0"
}
route.fulfill(
status=400,
headers={"Content-Type": "application/json"},
body=json.dumps(custom_response)
)
else:
route.continue_()
if request.method == "POST" and re.match(api_request_match, request.url):
custom_response = {
"jsonrpc": "2.0",
"error": {
"code": 3001,
"data": "the user rejected the wallet connection",
"message": "User error",
},
"id": "0",
}
route.fulfill(
status=400,
headers={"Content-Type": "application/json"},
body=json.dumps(custom_response),
)
else:
route.continue_()
def assert_connection_approve(route: Route, request, page:Page):
if request.method == "POST" and re.match(api_request_match, request.url):
expect(page.get_by_test_id("toast-content")).to_have_text("Please go to your Vega wallet application and approve or reject the transaction.")
else:
route.continue_()
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def assert_connection_approve(route: Route, request, page: Page):
if request.method == "POST" and re.match(api_request_match, request.url):
expect(page.get_by_test_id("toast-content")).to_have_text(
"Please go to your Vega wallet application and approve or reject the transaction."
)
else:
route.continue_()
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_wallet_connection_error(continuous_market, page: Page):
page.goto(f"/#/markets/{continuous_market}")
page.route("**/*", handle_route_connection_lost)
page.get_by_test_id("connect-vega-wallet").click()
page.get_by_test_id("connector-jsonRpc").click()
expect(page.get_by_test_id("wallet-dialog-title")).to_have_text("Something went wrong")
expect(page.get_by_test_id("wallet-dialog-title")).to_have_text(
"Something went wrong"
)
@pytest.mark.usefixtures("page", "risk_accepted")
@pytest.mark.usefixtures("risk_accepted")
def test_wallet_connection_rejected(continuous_market, page: Page):
# 0002-WCON-002
# 0002-WCON-005
@@ -78,11 +88,13 @@ def test_wallet_connection_rejected(continuous_market, page: Page):
page.route("**/*", handle_route_connection_rejected)
page.get_by_test_id("connect-vega-wallet").click()
page.get_by_test_id("connector-jsonRpc").click()
expect(page.get_by_test_id("dialog-content").nth(1)).to_have_text("User errorthe user rejected the wallet connectionTry againAbout the Vega wallet | Supported browsers ")
expect(page.get_by_test_id("dialog-content").nth(1)).to_have_text(
"User errorthe user rejected the wallet connectionTry againAbout the Vega wallet | Supported browsers "
)
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def test_wallet_connection_error_transaction(continuous_market, vega: VegaService, page: Page):
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_wallet_connection_error_transaction(continuous_market, page: Page):
# 0003-WTXN-009
# 0003-WTXN-011
# 0002-WCON-016
@@ -92,20 +104,26 @@ def test_wallet_connection_error_transaction(continuous_market, vega: VegaServic
page.get_by_test_id(order_price).fill("120")
page.route("**/*", handle_route_connection_lost)
page.get_by_test_id(place_order).click()
expect(page.get_by_test_id("toast-content")).to_have_text("Wallet disconnectedThe connection to your Vega Wallet has been lost.Connect vega wallet")
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def test_wallet_transaction_rejected(continuous_market, vega: VegaService, page: Page):
expect(page.get_by_test_id("toast-content")).to_have_text(
"Wallet disconnectedThe connection to your Vega Wallet has been lost.Connect vega wallet"
)
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_wallet_transaction_rejected(continuous_market, page: Page):
# 0003-WTXN-007
page.goto(f"/#/markets/{continuous_market}")
page.get_by_test_id(order_size).fill("10")
page.get_by_test_id(order_price).fill("120")
page.route("**/*", handle_route_connection_rejected)
page.get_by_test_id(place_order).click()
expect(page.get_by_test_id("toast-content")).to_have_text("Error occurredthe user rejected the wallet connection")
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
def test_wallet_connection_approve(continuous_market, vega: VegaService, page: Page):
expect(page.get_by_test_id("toast-content")).to_have_text(
"Error occurredthe user rejected the wallet connection"
)
@pytest.mark.usefixtures("auth", "risk_accepted")
def test_wallet_connection_approve(continuous_market, page: Page):
# 0002-WCON-005
# 0002-WCON-007
# 0002-WCON-009
@@ -113,4 +131,4 @@ def test_wallet_connection_approve(continuous_market, vega: VegaService, page: P
page.get_by_test_id(order_size).fill("10")
page.get_by_test_id(order_price).fill("120")
page.route("**/*", assert_connection_approve)
page.get_by_test_id(place_order).click()
page.get_by_test_id(place_order).click()
+4 -1
View File
@@ -7,6 +7,9 @@ WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
MM_WALLET = WalletConfig("market_maker", "pin")
MM_WALLET2 = WalletConfig("market_maker_2", "pin2")
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
GOVERNANCE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
GOVERNANCE_WALLET = WalletConfig(
"FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
PARTY_A = WalletConfig("party_a", "party_a")
PARTY_B = WalletConfig("party_b", "party_b")
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET, GOVERNANCE_WALLET]
+10 -1
View File
@@ -4,9 +4,18 @@ export default {
preset: '../../jest.preset.js',
transform: {
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nx/react/plugins/jest',
'^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nx/next/babel'] }],
'^.+\\.[tj]sx?$': [
'babel-jest',
{
presets: ['@nx/next/babel'],
// required for pennant to work in jest, due to having untranspiled exports
plugins: [['@babel/plugin-proposal-private-methods']],
},
],
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/apps/trading',
setupFilesAfterEnv: ['./setup-tests.ts'],
// dont ignore pennant from transpilation
transformIgnorePatterns: ['<rootDir>/node_modules/pennant'],
};
@@ -0,0 +1,62 @@
import {
Intent,
useToasts,
ToastHeading,
CLOSE_AFTER,
} from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useEffect, useMemo } from 'react';
import { useT } from '../use-t';
import { VegaWalletConnectButton } from '../../components/vega-wallet-connect-button';
const WALLET_DISCONNECTED_TOAST_ID = 'WALLET_DISCONNECTED_TOAST_ID';
export const useWalletDisconnectedToasts = () => {
const t = useT();
const [hasToast, setToast, updateToast] = useToasts((state) => [
state.hasToast,
state.setToast,
state.update,
]);
const { isAlive } = useVegaWallet();
const toast = useMemo(
() => ({
id: WALLET_DISCONNECTED_TOAST_ID,
intent: Intent.Danger,
content: (
<>
<ToastHeading>{t('Wallet connection lost')}</ToastHeading>
<p>{t('The connection to the Vega wallet has been lost.')}</p>
<p className="mt-2">
<VegaWalletConnectButton
intent={Intent.Danger}
onClick={() => {
updateToast(WALLET_DISCONNECTED_TOAST_ID, {
hidden: true,
});
}}
/>
</p>
</>
),
onClose: () => {
updateToast(WALLET_DISCONNECTED_TOAST_ID, {
hidden: true,
});
},
closeAfter: CLOSE_AFTER,
}),
[t, updateToast]
);
useEffect(() => {
if (isAlive === false) {
if (hasToast(WALLET_DISCONNECTED_TOAST_ID)) {
updateToast(WALLET_DISCONNECTED_TOAST_ID, { hidden: false });
} else {
setToast(toast);
}
}
}, [hasToast, isAlive, setToast, t, toast, updateToast]);
};
+1
View File
@@ -75,6 +75,7 @@ i18n
'positions',
'trades',
'trading',
'trading-view',
'ui-toolkit',
'utils',
'wallet',
+2
View File
@@ -6,6 +6,7 @@ import { useEthereumWithdrawApprovalsToasts } from '@vegaprotocol/web3';
import { useReadyToWithdrawalToasts } from '@vegaprotocol/withdraws';
import { Links } from '../lib/links';
import { useReferralToasts } from '../client-pages/referrals/hooks/use-referral-toasts';
import { useWalletDisconnectedToasts } from '../lib/hooks/use-wallet-disconnected-toasts';
export const ToastsManager = () => {
useProposalToasts();
@@ -16,6 +17,7 @@ export const ToastsManager = () => {
withdrawalsLink: Links.PORTFOLIO(),
});
useReferralToasts();
useWalletDisconnectedToasts();
const toasts = useToasts((store) => store.toasts);
return <ToastsContainer order="desc" toasts={toasts} />;
+26 -17
View File
@@ -1,43 +1,52 @@
import 'pennant/dist/style.css';
import { CandlestickChart } from 'pennant';
import {
CandlestickChart,
type Overlay,
type ChartType,
type Interval,
type Study,
} from 'pennant';
import { VegaDataSource } from './data-source';
import { useApolloClient } from '@apollo/client';
import { useMemo } from 'react';
import debounce from 'lodash/debounce';
import AutoSizer from 'react-virtualized-auto-sizer';
import { useVegaWallet } from '@vegaprotocol/wallet';
import {
STUDY_SIZE,
useCandlesChartSettings,
} from './use-candles-chart-settings';
import { useT } from './use-t';
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
export type CandlesChartContainerProps = {
marketId: string;
interval: Interval;
chartType: ChartType;
overlays: Overlay[];
studies: Study[];
studySizes: number[];
defaultStudySize: number;
setStudies: (studies?: Study[]) => void;
setStudySizes: (sizes: number[]) => void;
setOverlays: (overlays?: Overlay[]) => void;
};
const CANDLES_TO_WIDTH_FACTOR = 0.2;
export const CandlesChartContainer = ({
marketId,
interval,
chartType,
overlays,
studies,
studySizes,
defaultStudySize,
setStudies,
setStudySizes,
setOverlays,
}: CandlesChartContainerProps) => {
const client = useApolloClient();
const { pubKey } = useVegaWallet();
const { theme } = useThemeSwitcher();
const t = useT();
const {
interval,
chartType,
overlays,
studies,
studySizes,
setStudies,
setStudySizes,
setOverlays,
} = useCandlesChartSettings();
const handlePaneChange = useMemo(
() =>
debounce((sizes: number[]) => {
@@ -69,7 +78,7 @@ export const CandlesChartContainer = ({
</span>
),
initialNumCandlesToDisplay: candlesCount,
studySize: STUDY_SIZE,
studySize: defaultStudySize,
studySizes,
}}
interval={interval}
@@ -1,85 +0,0 @@
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CandlesMenu } from './candles-menu';
import {
useCandlesChartSettingsStore,
DEFAULT_CHART_SETTINGS,
} from './use-candles-chart-settings';
import { Overlay, Study, overlayLabels, studyLabels } from 'pennant';
describe('CandlesMenu', () => {
const openDropdown = async () => {
await userEvent.click(
screen.getByRole('button', {
name: 'Indicators',
})
);
};
beforeEach(() => {
// clear store each time to avoid conditional testing of defaults
useCandlesChartSettingsStore.setState({ overlays: [], studies: [] });
});
it.each(Object.values(Overlay))('can set %s overlay', async (overlay) => {
render(<CandlesMenu />);
await openDropdown();
const menu = within(await screen.findByRole('menu'));
await userEvent.click(menu.getByText(overlayLabels[overlay as Overlay]));
// re-open the dropdown
await openDropdown();
expect(screen.getByText(overlayLabels[overlay as Overlay])).toHaveAttribute(
'data-state',
'checked'
);
});
it.each(Object.values(Study))('can set %s study', async (study) => {
render(<CandlesMenu />);
await openDropdown();
const menu = within(await screen.findByRole('menu'));
await userEvent.click(menu.getByText(studyLabels[study as Study]));
// re-open the dropdown
await openDropdown();
expect(screen.getByText(studyLabels[study as Study])).toHaveAttribute(
'data-state',
'checked'
);
});
it('should render with the correct default studies and overlays', async () => {
useCandlesChartSettingsStore.setState(DEFAULT_CHART_SETTINGS);
render(<CandlesMenu />);
await userEvent.click(
screen.getByRole('button', {
name: 'Indicators',
})
);
const menu = within(await screen.findByRole('menu'));
expect(menu.getByText(studyLabels.volume)).toHaveAttribute(
'data-state',
'checked'
);
expect(menu.getByText(studyLabels.macd)).toHaveAttribute(
'data-state',
'checked'
);
expect(menu.getByText(overlayLabels.movingAverage)).toHaveAttribute(
'data-state',
'checked'
);
});
});
+12
View File
@@ -0,0 +1,12 @@
import { Interval as PennantInterval } from 'pennant';
import { Interval } from '@vegaprotocol/types';
export const PENNANT_INTERVAL_MAP = {
[Interval.INTERVAL_BLOCK]: undefined, // TODO: handle block tick
[Interval.INTERVAL_I1M]: PennantInterval.I1M,
[Interval.INTERVAL_I5M]: PennantInterval.I5M,
[Interval.INTERVAL_I15M]: PennantInterval.I15M,
[Interval.INTERVAL_I1H]: PennantInterval.I1H,
[Interval.INTERVAL_I6H]: PennantInterval.I6H,
[Interval.INTERVAL_I1D]: PennantInterval.I1D,
} as const;
+5 -1
View File
@@ -56,6 +56,7 @@ const defaultConfig = {
*/
export class VegaDataSource implements DataSource {
client: ApolloClient<object>;
from?: Date;
marketId: string;
partyId: null | string;
_decimalPlaces = 0;
@@ -158,6 +159,7 @@ export class VegaDataSource implements DataSource {
*/
async query(interval: PennantInterval, from: string) {
try {
this.from = new Date(from);
const { data } = await this.client.query<
CandlesQuery,
CandlesQueryVariables
@@ -215,7 +217,9 @@ export class VegaDataSource implements DataSource {
this.decimalPlaces,
this.positionDecimalPlaces
);
if (!this.from || candle.date < this.from) {
return;
}
onSubscriptionData(candle);
}
});
+1 -1
View File
@@ -1,5 +1,5 @@
export * from './__generated__/Candles';
export * from './__generated__/Chart';
export * from './candles-chart';
export * from './candles-menu';
export { PENNANT_INTERVAL_MAP } from './constants';
export * from './data-source';
+11 -10
View File
@@ -5,7 +5,7 @@ import { prepend0x } from '@vegaprotocol/smart-contracts';
import sortBy from 'lodash/sortBy';
import { useSubmitApproval } from './use-submit-approval';
import { useSubmitFaucet } from './use-submit-faucet';
import { useCallback, useState } from 'react';
import { useCallback, useEffect } from 'react';
import { useDepositBalances } from './use-deposit-balances';
import type { Asset } from '@vegaprotocol/assets';
import {
@@ -30,7 +30,7 @@ export const DepositManager = ({
const { config } = useEthereumConfig();
const [persistentDeposit, savePersistentDeposit] =
usePersistentDeposit(initialAssetId);
const [assetId, setAssetId] = useState(persistentDeposit?.assetId);
const assetId = persistentDeposit?.assetId;
const asset = assets.find((a) => a.id === assetId);
const bridgeContract = useBridgeContract();
@@ -70,18 +70,19 @@ export const DepositManager = ({
[savePersistentDeposit, persistentDeposit]
);
useEffect(() => {
// When we change asset, also clear the tracked faucet/approve transactions so
// we dont render stale UI
approve.reset();
faucet.reset();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [assetId]);
return (
<DepositForm
selectedAsset={asset}
onDisconnect={reset}
onSelectAsset={(id) => {
setAssetId(id);
savePersistentDeposit({ assetId: id });
// When we change asset, also clear the tracked faucet/approve transactions so
// we dont render stale UI
approve.reset();
faucet.reset();
}}
onSelectAsset={(assetId) => savePersistentDeposit({ assetId })}
handleAmountChange={onAmountChange}
assets={sortBy(assets, 'name')}
submitApprove={approve.perform}
+1
View File
@@ -13,3 +13,4 @@ export * from './use-get-deposit-maximum';
export * from './use-get-deposited-amount';
export * from './use-submit-approval';
export * from './use-submit-faucet';
export * from './use-persistent-deposit';
@@ -10,7 +10,7 @@ interface PersistedDeposit {
}
type PersistedDepositData = Record<string, PersistedDeposit>;
const usePersistentDepositStore = create<{
export const usePersistentDepositStore = create<{
deposits: PersistedDepositData;
saveValue: (entry: PersistedDeposit) => void;
lastVisited?: PersistedDeposit;
@@ -154,6 +154,7 @@ const compileEnvVars = () => {
'VEGA_ENV',
process.env['NX_VEGA_ENV']
) as Networks;
const env: Environment = {
VEGA_URL: windowOrDefault('VEGA_URL', process.env['NX_VEGA_URL']),
VEGA_ENV,
@@ -253,6 +254,14 @@ const compileEnvVars = () => {
'NX_MOZILLA_EXTENSION_URL',
process.env['NX_MOZILLA_EXTENSION_URL']
),
CHARTING_LIBRARY_PATH: windowOrDefault(
'NX_CHARTING_LIBRARY_PATH',
process.env['NX_CHARTING_LIBRARY_PATH']
),
CHARTING_LIBRARY_HASH: windowOrDefault(
'NX_CHARTING_LIBRARY_HASH',
process.env['NX_CHARTING_LIBRARY_HASH']
),
};
return env;
@@ -360,6 +369,7 @@ export const compileFeatureFlags = (refresh = false): FeatureFlags => {
) as string
),
};
const EXPLORER_FLAGS = {
EXPLORER_ASSETS: TRUTHY.includes(
windowOrDefault(
@@ -416,6 +426,7 @@ export const compileFeatureFlags = (refresh = false): FeatureFlags => {
) as string
),
};
const GOVERNANCE_FLAGS = {
GOVERNANCE_NETWORK_DOWN: TRUTHY.includes(
windowOrDefault(
@@ -60,6 +60,8 @@ export const envSchema = z
TENDERMINT_WEBSOCKET_URL: z.optional(z.string()),
CHROME_EXTENSION_URL: z.optional(z.string()),
MOZILLA_EXTENSION_URL: z.optional(z.string()),
CHARTING_LIBRARY_PATH: z.optional(z.string()),
CHARTING_LIBRARY_HASH: z.optional(z.string()),
})
.refine(
(data) => {
+2
View File
@@ -11,6 +11,7 @@ import en_fills from './locales/en/fills.json';
import en_funding_payments from './locales/en/funding-payments.json';
import en_governance from './locales/en/governance.json';
import en_trading from './locales/en/trading.json';
import en_trading_view from './locales/en/trading-view.json';
import en_markets from './locales/en/markets.json';
import en_web3 from './locales/en/web3.json';
import en_proposals from './locales/en/proposals.json';
@@ -32,6 +33,7 @@ export const locales = {
'funding-payments': en_funding_payments,
governance: en_governance,
trading: en_trading,
trading_view: en_trading_view,
markets: en_markets,
web3: en_web3,
positions: en_positions,
@@ -1,5 +1,3 @@
{
"Indicators": "Indicators",
"Interval: {{interval}}": "Interval: {{interval}}",
"No open orders": "No open orders"
}
+3 -3
View File
@@ -298,8 +298,8 @@
"liquidityOnsenIntro": "Earn rewards for providing liquidity on the",
"liquidityOnsenLinkText": "SushiSwap Onsen Menu",
"liquidityProviderVote": "Liquidity provider vote",
"liquidityProviderVotesAgainst": "LP votes against",
"liquidityProviderVotesFor": "LP votes for",
"liquidityProviderVotesAgainst": "LP share against",
"liquidityProviderVotesFor": "LP share for",
"liquidityRewardsTitle": "Active liquidity rewards",
"liquidityRewardsTitlePrevious": "Previous liquidity rewards",
"liquidityStakedBalance": "SLP token balance",
@@ -759,7 +759,7 @@
"Total stake": "Total stake",
"Total supply": "Total supply",
"totalDistributed": "Total distributed",
"totalLiquidityProviderTokensVoted": "Total LP tokens voted",
"totalLiquidityProviderTokensVoted": "Total LP share voted",
"totalPenalties": "Total penalties",
"TotalPenaltiesDescription": "Total of penalties taking into account performance (considering proportion of blocks proposed against the number of blocks the validator was expected to propose) and any overstaking.",
"totalStake": "Total stake",
@@ -0,0 +1,4 @@
{
"Failed to initialize Trading view": "Failed to initialize Trading view",
"Loading Trading View": "Loading Trading View"
}
+13 -1
View File
@@ -26,9 +26,10 @@
"Best offer": "Best offer",
"Browse": "Browse",
"By using the Vega Console, you acknowledge that you have read and understood the <0>Vega Console Disclaimer</0>": "By using the Vega Console, you acknowledge that you have read and understood the <0>Vega Console Disclaimer</0>",
"Candles": "Candles",
"Chart": "Chart",
"Change (24h)": "Change (24h)",
"Chart": "Chart",
"Chart by <0>TradingView</0>": "Chart by <0>TradingView</0>",
"checkOutProposalsAndVote": "Check out the terms of the proposals and vote:",
"checkOutProposalsAndVote_one": "Check out the terms of the proposal and vote:",
"checkOutProposalsAndVote_other": "Check out the terms of the proposals and vote:",
@@ -120,7 +121,15 @@
"Improve vega console": "Improve vega console",
"Inactive": "Inactive",
"Index Price": "Index Price",
"Indicators": "Indicators",
"Infrastructure": "Infrastructure",
"Interval: {{interval}}": "Interval: {{interval}}",
"INTERVAL_I1M": "1m",
"INTERVAL_I5M": "5m",
"INTERVAL_I15M": "15m",
"INTERVAL_I1H": "1H",
"INTERVAL_I6H": "6H",
"INTERVAL_I1D": "1D",
"Invite friends and earn rewards from the trading fees they pay. Stake those rewards to earn multipliers on future rewards.": "Invite friends and earn rewards from the trading fees they pay. Stake those rewards to earn multipliers on future rewards.",
"Learn about providing liquidity": "Learn about providing liquidity",
"Learn more": "Learn more",
@@ -192,6 +201,7 @@
"pastEpochs": "Past {{count}} epochs",
"pastEpochs_one": "Past {{count}} epoch",
"pastEpochs_other": "Past {{count}} epochs",
"Pennant": "Pennant",
"Perpetuals": "Perpetuals",
"Please choose another market from the <0>market list</0>": "Please choose another market from the <0>market list</0>",
"Please connect Vega wallet": "Please connect Vega wallet",
@@ -291,6 +301,7 @@
"Trader": "Trader",
"Trades": "Trades",
"Trading": "Trading",
"TradingView": "TradingView",
"Trading has been terminated as a result of the product definition": "Trading has been terminated as a result of the product definition",
"Trading mode": "Trading mode",
"Trading on Market {{name}} may stop on {{date}}. There is open proposal to close this market.": "Trading on Market {{name}} may stop on {{date}}. There is open proposal to close this market.",
@@ -302,6 +313,7 @@
"totalCommission_other": "Total commission (last {{count}} epochs)",
"Unknown": "Unknown",
"Unknown settlement date": "Unknown settlement date",
"Vega chart": "Vega chart",
"Vega Reward pot": "Vega Reward pot",
"Vega Wallet <0>full featured<0>": "Vega Wallet <0>full featured<0>",
"Vesting": "Vesting",
+1 -1
View File
@@ -198,7 +198,7 @@ export const Orderbook = ({
);
return (
<div
className="overflow-hidden grid"
className="overflow-hidden grid relative"
data-testid="orderbook-grid-element"
style={{
width,
@@ -135,7 +135,7 @@ describe('MarketInfoPanels', () => {
render(<DataSourceProof dataSourceSpecId={''} {...props} />);
expect(screen.getByText('Internal conditions')).toBeInTheDocument();
const dateFromUnixTimestamp = condition.value
? getDateTimeFormat().format(new Date(parseInt(condition.value)))
? getDateTimeFormat().format(new Date(parseInt(condition.value) * 1000))
: '-';
expect(
screen.getByText(
@@ -1263,7 +1263,9 @@ export const DataSourceProof = ({
{data.sourceType.sourceType?.conditions?.map((condition, i) => {
if (!condition) return null;
const dateFromUnixTimestamp = condition.value
? getDateTimeFormat().format(new Date(parseInt(condition.value)))
? getDateTimeFormat().format(
new Date(parseInt(condition.value) * 1000)
)
: '-';
return (
<p key={i}>
+12 -13
View File
@@ -8,11 +8,13 @@ export const LiquidationPrice = ({
openVolume,
collateralAvailable,
decimalPlaces,
className,
}: {
marketId: string;
openVolume: string;
collateralAvailable: string;
decimalPlaces: number;
className?: string;
}) => {
const t = useT();
const { data: currentData, previousData } = useEstimatePositionQuery({
@@ -39,22 +41,19 @@ export const LiquidationPrice = ({
return (
<Tooltip
align="end"
description={
<table>
<tbody>
<tr>
<th>{t('Worst case')}</th>
<td className="pl-2 text-right font-mono">{worstCase}</td>
</tr>
<tr>
<th>{t('Best case')}</th>
<td className="pl-2 text-right font-mono">{bestCase}</td>
</tr>
</tbody>
</table>
<dl className="grid grid-cols-2">
<dt>{t('Worst case')}</dt>
<dd className="pl-2 text-right font-mono">{worstCase}</dd>
<dt className="font-normal">{t('Best case')}</dt>
<dd className="pl-2 text-right font-mono">{bestCase}</dd>
</dl>
}
>
<span data-testid="liquidation-price">{worstCase}</span>
<span data-testid="liquidation-price" className={className}>
{worstCase}
</span>
</Tooltip>
);
};
@@ -314,7 +314,9 @@ describe('Positions', () => {
});
const cells = screen.getAllByRole('gridcell');
const cell = cells[1];
await userEvent.hover(cell);
const tooltipTrigger = cell.querySelector('[data-state="closed"]');
expect(tooltipTrigger).not.toBeNull();
await userEvent.hover(tooltipTrigger as Element);
const tooltip = within(await screen.findByRole('tooltip'));
expect(tooltip.getByText(data.text)).toBeInTheDocument();
});
@@ -329,8 +331,9 @@ describe('Positions', () => {
});
const cells = screen.getAllByRole('gridcell');
const cell = cells[5];
await userEvent.hover(cell);
const tooltipTrigger = cell.querySelector('[data-state="closed"]');
expect(tooltipTrigger).not.toBeNull();
await userEvent.hover(tooltipTrigger as Element);
const tooltip = within(await screen.findByRole('tooltip'));
expect(tooltip.getByText('Realised PNL: 1.23')).toBeInTheDocument();
expect(
+95 -100
View File
@@ -1,5 +1,5 @@
import { useMemo, type CSSProperties, type ReactNode } from 'react';
import { type ColDef, type ITooltipParams } from 'ag-grid-community';
import { type ColDef } from 'ag-grid-community';
import {
AgGrid,
COL_DEFS,
@@ -20,6 +20,7 @@ import {
ExternalLink,
VegaIcon,
VegaIconNames,
Tooltip,
} from '@vegaprotocol/ui-toolkit';
import {
volumePrefix,
@@ -148,15 +149,6 @@ export const PositionsTable = ({
data.positionDecimalPlaces
).toNumber();
},
tooltipValueGetter: ({ data }: ITooltipParams<Position>) => {
if (
!data ||
data.status === PositionStatus.POSITION_STATUS_UNSPECIFIED
) {
return null;
}
return data.status;
},
valueFormatter: ({
data,
}: VegaValueFormatterParams<Position, 'openVolume'>): string => {
@@ -171,68 +163,6 @@ export const PositionsTable = ({
return vol;
},
tooltipComponent: (args: ITooltipParams<Position>) => {
if (!args.data) {
return null;
}
const POSITION_RESOLUTION_LINK =
DocsLinks?.POSITION_RESOLUTION ?? '';
let primaryTooltip;
switch (args.data.status) {
case PositionStatus.POSITION_STATUS_CLOSED_OUT:
primaryTooltip = t('Your position was closed.');
break;
case PositionStatus.POSITION_STATUS_ORDERS_CLOSED:
primaryTooltip = t('Your open orders were cancelled.');
break;
case PositionStatus.POSITION_STATUS_DISTRESSED:
primaryTooltip = t('Your position is distressed.');
break;
}
let secondaryTooltip;
switch (args.data.status) {
case PositionStatus.POSITION_STATUS_CLOSED_OUT:
secondaryTooltip = t(
`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:
secondaryTooltip = t(
'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.'
);
break;
case PositionStatus.POSITION_STATUS_DISTRESSED:
secondaryTooltip = t(
'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.'
);
break;
default:
secondaryTooltip = t('Maintained by network');
}
return (
<TooltipCellComponent
{...args}
value={
<>
<p className="mb-2">{primaryTooltip}</p>
<p className="mb-2">{secondaryTooltip}</p>
<p className="mb-2">
{t('Status: {{status}}', {
status: PositionStatusMapping[args.data.status],
})}
</p>
{POSITION_RESOLUTION_LINK && (
<ExternalLink href={POSITION_RESOLUTION_LINK}>
{t('Read more about position resolution')}
</ExternalLink>
)}
</>
}
/>
);
},
cellRenderer: OpenVolumeCell,
},
{
@@ -337,12 +267,15 @@ export const PositionsTable = ({
return '-';
}
return (
<LiquidationPrice
marketId={data.marketId}
openVolume={data.openVolume}
collateralAvailable={data.totalBalance}
decimalPlaces={data.marketDecimalPlaces}
/>
<div className="flex h-[45px] items-center">
<LiquidationPrice
className="block text-right grow"
marketId={data.marketId}
openVolume={data.openVolume}
collateralAvailable={data.totalBalance}
decimalPlaces={data.marketDecimalPlaces}
/>
</div>
);
},
},
@@ -354,13 +287,13 @@ export const PositionsTable = ({
cellClass: 'font-mono text-right',
filter: 'agNumberColumnFilter',
valueGetter: realisedPNLValueGetter,
// @ts-ignore no type overlap, but the functions are identical
tooltipValueGetter: realisedPNLValueGetter,
tooltipComponent: (args: ITooltipParams) => {
cellRenderer: (
args: VegaICellRendererParams<Position, 'realisedPNL'>
) => {
const LOSS_SOCIALIZATION_LINK =
DocsLinks?.LOSS_SOCIALIZATION ?? '';
if (!args.data) {
if (!args.data || args.value === undefined) {
return null;
}
@@ -371,7 +304,11 @@ export const PositionsTable = ({
if (losses <= 0) {
// eslint-disable-next-line react/jsx-no-useless-fragment
return (
<TooltipCellComponent {...args} value={args.valueFormatted} />
<Tooltip description={args.valueFormatted} align="end">
<div>
<PNLCell {...args} />
</div>
</Tooltip>
);
}
@@ -381,20 +318,24 @@ export const PositionsTable = ({
);
return (
<TooltipCellComponent
{...args}
value={
<Tooltip
align="end"
description={
<>
<p className="mb-2">
{t('Realised PNL: {{value}}', {
value: args.value,
nsSeparator: '*',
replace: { value: args.value },
})}
</p>
<p className="mb-2">
{t(
'Lifetime loss socialisation deductions: {{losses}}',
{
losses: lossesFormatted,
nsSeparator: '*',
replace: {
losses: lossesFormatted,
},
}
)}
</p>
@@ -411,7 +352,11 @@ export const PositionsTable = ({
)}
</>
}
/>
>
<div>
<PNLCell {...args} />
</div>
</Tooltip>
);
},
valueFormatter: ({
@@ -428,7 +373,6 @@ export const PositionsTable = ({
headerTooltip: t(
'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.'
),
cellRenderer: PNLCell,
},
{
headerName: t('Unrealised PNL'),
@@ -520,10 +464,66 @@ export const OpenVolumeCell = ({
valueFormatted,
data,
}: VegaICellRendererParams<Position, 'openVolume'>) => {
const t = useT();
if (!valueFormatted || !data || !data.notional) {
return <>-</>;
}
const POSITION_RESOLUTION_LINK = DocsLinks?.POSITION_RESOLUTION ?? '';
let primaryTooltip;
switch (data.status) {
case PositionStatus.POSITION_STATUS_CLOSED_OUT:
primaryTooltip = t('Your position was closed.');
break;
case PositionStatus.POSITION_STATUS_ORDERS_CLOSED:
primaryTooltip = t('Your open orders were cancelled.');
break;
case PositionStatus.POSITION_STATUS_DISTRESSED:
primaryTooltip = t('Your position is distressed.');
break;
}
let secondaryTooltip;
switch (data.status) {
case PositionStatus.POSITION_STATUS_CLOSED_OUT:
secondaryTooltip = t(
`You did not have enough {{assetSymbol}} collateral to meet the maintenance margin requirements for your position, so it was closed by the network.`,
{ assetSymbol: data.assetSymbol }
);
break;
case PositionStatus.POSITION_STATUS_ORDERS_CLOSED:
secondaryTooltip = t(
'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.'
);
break;
case PositionStatus.POSITION_STATUS_DISTRESSED:
secondaryTooltip = t(
'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.'
);
break;
default:
secondaryTooltip = t('Maintained by network');
}
const description = (
<>
<p className="mb-2">{primaryTooltip}</p>
<p className="mb-2">{secondaryTooltip}</p>
<p className="mb-2">
{t('Status: {{status}}', {
nsSeparator: '*',
replace: {
status: PositionStatusMapping[data.status],
},
})}
</p>
{POSITION_RESOLUTION_LINK && (
<ExternalLink href={POSITION_RESOLUTION_LINK}>
{t('Read more about position resolution')}
</ExternalLink>
)}
</>
);
const notional = addDecimalsFormatNumber(
data.notional,
data.marketDecimalPlaces
@@ -539,16 +539,11 @@ export const OpenVolumeCell = ({
}
return (
<WarningCell
showIcon={
// not sure why but data.status has become a union of all the enum values
// rather than just being the enum itself
(data.status as PositionStatus) !==
PositionStatus.POSITION_STATUS_UNSPECIFIED
}
>
{cellContent}
</WarningCell>
<Tooltip description={description}>
<div>
<WarningCell showIcon>{cellContent}</WarningCell>
</div>
</Tooltip>
);
};
+2 -1
View File
@@ -1,3 +1,4 @@
export * from './use-copy-timeout';
export * from './use-fetch';
export * from './use-local-storage';
export * from './use-mutation-observer';
@@ -11,4 +12,4 @@ export * from './use-theme-switcher';
export * from './use-storybook-theme-observer';
export * from './use-yesterday';
export * from './use-previous';
export * from './use-copy-timeout';
export { useScript } from './use-script';
@@ -0,0 +1,18 @@
import { renderHook, waitFor } from '@testing-library/react';
import { useScript } from './use-script';
describe('useScript', () => {
it('appends a script to the body', async () => {
const url = 'http://localhost:8080/foo.js';
const { result } = renderHook(() => useScript(url, 'integrity-hash'));
expect(result.current).toBe('loading');
await waitFor(() => {
const script = document.body.getElementsByTagName('script')[0];
expect(script).toBeInTheDocument();
expect(script).toHaveAttribute('src', url);
});
});
});

Some files were not shown because too many files have changed in this diff Show More