Compare commits

..
Author SHA1 Message Date
Matthew Russell ad27cbc16b chore: delete netlify configs 2023-11-15 11:41:43 -08:00
Matthew Russell df41b36d88 chore: remove netlify build targets 2023-11-15 11:40:02 -08:00
132 changed files with 1068 additions and 3362 deletions
+2 -2
View File
@@ -48,12 +48,12 @@ cypress.env.json
# Next.js
.next
# cypress
#cypress
/apps/**/cypress/reports/
/apps/**/cypress/downloads/
/apps/**/fixtures/wallet/node**
# apps/trading/e2e
#console-test
__pycache__/
apps/trading/e2e/logs/
apps/trading/e2e/.pytest_cache/
-8
View File
@@ -1,7 +1,6 @@
# Add files here to ignore them from prettier formatting
/dist
/dist-result
/coverage
__generated__
__generated___
@@ -14,10 +13,3 @@ apps/static/src/assets/testnet-tranches.json
/apps/**/cypress/downloads/
/.nx/cache
# apps/trading/e2e
__pycache__/
apps/trading/e2e/logs/
apps/trading/e2e/.pytest_cache/
apps/trading/e2e/traces/
.pytest_cache/
@@ -302,17 +302,14 @@ context(
cy.getByTestId(vegaWalletCurrencyTitle)
.contains(name)
.parent() // back to currency-title
.parent() // back to container
.within(() => {
cy.get(
'[data-account-type="account_type_general"] [data-value]'
).should((elementAmount) => {
const displayedAmount = parseFloat(elementAmount.text());
// @ts-ignore clash between jest and cypress
expect(displayedAmount).be.gte(expectedAmount);
});
.parent()
.siblings(txTimeout)
.should((elementAmount) => {
const displayedAmount = parseFloat(elementAmount.text());
// @ts-ignore clash between jest and cypress
expect(displayedAmount).be.gte(expectedAmount);
});
cy.getByTestId(vegaWalletCurrencyTitle)
.contains(name)
.parent()
@@ -256,7 +256,10 @@ export function validateWalletCurrency(
.parent()
.parent()
.within(() => {
cy.get('[data-value]', txTimeout).should('have.text', expectedAmount);
cy.getByTestId('currency-value', txTimeout).should(
'have.text',
expectedAmount
);
});
}
@@ -114,16 +114,6 @@ export const usePollForDelegations = () => {
isAssetTypeERC20(a.asset) &&
a.asset.source.contractAddress === vegaToken.address;
const isVesting =
a.type === Schema.AccountType.ACCOUNT_TYPE_VESTED_REWARDS ||
a.type === Schema.AccountType.ACCOUNT_TYPE_VESTING_REWARDS;
let icon = noIcon;
if (isVega) {
if (isVesting) icon = vegaVesting;
else icon = vegaBlack;
}
return {
isVega,
name: a.asset.name,
@@ -134,7 +124,14 @@ export const usePollForDelegations = () => {
balance: new BigNumber(
addDecimal(a.balance, a.asset.decimals)
),
image: icon,
image: isVega
? vegaBlack
: a.type ===
Schema.AccountType.ACCOUNT_TYPE_VESTED_REWARDS ||
a.type ===
Schema.AccountType.ACCOUNT_TYPE_VESTING_REWARDS
? vegaVesting
: noIcon,
border: isVega,
address: isAssetTypeERC20(a.asset)
? a.asset.source.contractAddress
@@ -11,10 +11,7 @@ import { BigNumber } from '../../lib/bignumber';
import { truncateMiddle } from '../../lib/truncate-middle';
import Routes from '../../routes/routes';
import { BulletHeader } from '../bullet-header';
import type {
WalletCardAssetProps,
WalletCardAssetWithMultipleBalancesProps,
} from '../wallet-card';
import type { WalletCardAssetProps } from '../wallet-card';
import {
WalletCard,
WalletCardActions,
@@ -30,7 +27,6 @@ import { Button, ButtonLink } from '@vegaprotocol/ui-toolkit';
import { toBigNum } from '@vegaprotocol/utils';
import { usePendingBalancesStore } from '../../hooks/use-pending-balances-manager';
import { StakingEventType } from '../../hooks/use-get-association-breakdown';
import omit from 'lodash/omit';
export const VegaWallet = () => {
const { t } = useTranslation();
@@ -103,29 +99,12 @@ const VegaWalletAssetList = ({ accounts }: VegaWalletAssetsListProps) => {
if (!accounts.length) {
return null;
}
const groupedByAsset = accounts.reduce((all, a) => {
const foundIndex = all.findIndex((acc) => acc.assetId === a.assetId);
if (foundIndex > -1) {
const found = all[foundIndex];
all[foundIndex] = {
...found,
balances: [...found.balances, { balance: a.balance, type: a.type }],
};
return all;
}
const acc = {
...omit(a, 'balance', 'type'),
balances: [{ balance: a.balance, type: a.type }],
};
return [...all, acc];
}, [] as WalletCardAssetWithMultipleBalancesProps[]);
return (
<>
<WalletCardHeader>
<BulletHeader tag="h2">{t('assets')}</BulletHeader>
</WalletCardHeader>
{groupedByAsset.map((a, i) => (
{accounts.map((a, i) => (
<WalletCardAsset key={i} {...a} />
))}
</>
@@ -203,7 +182,6 @@ const VegaWalletConnected = ({ vegaKeys }: VegaWalletConnectedProps) => {
subheading={t('Associated')}
symbol="VEGA"
balance={currentStakeAvailable}
allowZeroBalance={true}
/>
{totalPending.eq(0) ? null : (
<>
@@ -214,7 +192,6 @@ const VegaWalletConnected = ({ vegaKeys }: VegaWalletConnectedProps) => {
subheading={t('Pending association')}
symbol="VEGA"
balance={totalPending}
allowZeroBalance={true}
/>
<WalletCardAsset
image={vegaWhite}
@@ -223,7 +200,6 @@ const VegaWalletConnected = ({ vegaKeys }: VegaWalletConnectedProps) => {
subheading={t('Total associated after pending')}
symbol="VEGA"
balance={pendingStakeAmount}
allowZeroBalance={true}
/>
</>
)}
@@ -103,7 +103,7 @@ export const WalletCardActions = ({
return <div className="flex justify-end gap-2 mb-4">{children}</div>;
};
export type WalletCardAssetProps = {
export interface WalletCardAssetProps {
image: string;
name: string;
symbol: string;
@@ -113,61 +113,42 @@ export type WalletCardAssetProps = {
border?: boolean;
subheading?: string;
type?: Schema.AccountType;
allowZeroBalance?: boolean;
};
export type WalletCardAssetWithMultipleBalancesProps = Omit<
WalletCardAssetProps,
'balance' | 'type'
> & {
balances: { balance: BigNumber; type?: Schema.AccountType }[];
};
}
export const WalletCardAsset = ({
image,
name,
symbol,
balance,
decimals,
assetId,
border,
subheading,
allowZeroBalance = false,
...props
}: WalletCardAssetProps | WalletCardAssetWithMultipleBalancesProps) => {
const balance = 'balance' in props ? props.balance : undefined;
const type = 'type' in props ? props.type : undefined;
const balances =
'balances' in props
? props.balances
: balance
? [{ balance, type }]
: undefined;
type,
}: WalletCardAssetProps) => {
const [integers, decimalsPlaces, separator] = useNumberParts(
balance,
decimals
);
const { t } = useTranslation();
const consoleLink = useLinks(DApp.Console);
const transferAssetLink = (assetId: string) =>
consoleLink(CONSOLE_TRANSFER_ASSET.replace(':assetId', assetId));
const { param: baseRate } = useNetworkParam('rewards_vesting_baseRate');
const values =
balances &&
balances.length > 0 &&
balances
.filter((b) => allowZeroBalance || !b.balance.isZero())
.sort((a, b) => {
const order = [
Schema.AccountType.ACCOUNT_TYPE_VESTING_REWARDS,
Schema.AccountType.ACCOUNT_TYPE_VESTED_REWARDS,
Schema.AccountType.ACCOUNT_TYPE_GENERAL,
undefined,
];
return order.indexOf(a.type) - order.indexOf(b.type);
})
.map(({ balance, type }, i) => (
<CurrencyValue
key={i}
balance={balance}
decimals={decimals}
type={type}
assetId={assetId}
/>
));
const isRedeemable =
type === Schema.AccountType.ACCOUNT_TYPE_VESTED_REWARDS && assetId;
if (!values || values.length === 0) return;
const accountTypeTooltip = useMemo(() => {
if (type === Schema.AccountType.ACCOUNT_TYPE_VESTED_REWARDS) {
return t('VestedRewardsTooltip');
}
if (type === Schema.AccountType.ACCOUNT_TYPE_VESTING_REWARDS && baseRate) {
return t('VestingRewardsTooltip', { baseRate });
}
return null;
}, [baseRate, t, type]);
return (
<div className="flex flex-nowrap gap-2 mt-2 mb-4">
@@ -188,92 +169,35 @@ export const WalletCardAsset = ({
{subheading || symbol}
</div>
</div>
{values}
</div>
</div>
);
};
const useAccountTypeTooltip = (type?: Schema.AccountType) => {
const { t } = useTranslation();
const { param: baseRate } = useNetworkParam('rewards_vesting_baseRate');
const accountTypeTooltip = useMemo(() => {
if (type === Schema.AccountType.ACCOUNT_TYPE_VESTED_REWARDS) {
return t('VestedRewardsTooltip');
}
if (type === Schema.AccountType.ACCOUNT_TYPE_VESTING_REWARDS && baseRate) {
return t('VestingRewardsTooltip', { baseRate });
}
return null;
}, [baseRate, t, type]);
return accountTypeTooltip;
};
const CurrencyValue = ({
balance,
decimals,
type,
assetId,
}: {
balance: BigNumber;
decimals: number;
type?: Schema.AccountType;
assetId?: string;
}) => {
const { t } = useTranslation();
const consoleLink = useLinks(DApp.Console);
const transferAssetLink = (assetId: string) =>
consoleLink(CONSOLE_TRANSFER_ASSET.replace(':assetId', assetId));
const [integers, decimalsPlaces, separator] = useNumberParts(
balance,
decimals
);
const accountTypeTooltip = useAccountTypeTooltip(type);
const accountType = type && (
<Tooltip description={accountTypeTooltip}>
<span className="px-2 py-1 leading-none text-xs bg-vega-cdark-700 rounded">
{Schema.AccountTypeMapping[type]}
</span>
</Tooltip>
);
const isRedeemable =
type === Schema.AccountType.ACCOUNT_TYPE_VESTED_REWARDS && assetId;
const redeemBtn = isRedeemable ? (
<Tooltip description={t('RedeemRewardsTooltip')}>
<AnchorButton
variant="primary"
size="xs"
href={transferAssetLink(assetId)}
target="_blank"
className="px-2 py-1 leading-none text-xs bg-vega-yellow text-black rounded"
>
{t('Redeem')}
</AnchorButton>
</Tooltip>
) : null;
return (
<div
className="basis-full font-mono mb-1"
data-account-type={type?.toLowerCase() || 'unspecified'}
data-testid="currency-value"
>
{type && (
<div data-type className="flex gap-1">
{accountType}
{redeemBtn}
{type ? (
<div className="mb-[2px] flex gap-2 items-baseline">
<Tooltip description={accountTypeTooltip}>
<span className="px-2 py-1 leading-none text-xs bg-vega-cdark-700 rounded">
{Schema.AccountTypeMapping[type]}
</span>
</Tooltip>
{isRedeemable ? (
<Tooltip description={t('RedeemRewardsTooltip')}>
<AnchorButton
variant="primary"
size="xs"
href={transferAssetLink(assetId)}
target="_blank"
className="px-2 py-1 leading-none text-xs bg-vega-yellow text-black rounded"
>
{t('Redeem')}
</AnchorButton>
</Tooltip>
) : null}
</div>
) : null}
<div className="basis-full font-mono" data-testid="currency-value">
<span>
{integers}
{separator}
</span>
<span className="text-neutral-400">{decimalsPlaces}</span>
</div>
)}
<div data-value>
<span>
{integers}
{separator}
</span>
<span className="text-neutral-400">{decimalsPlaces}</span>
</div>
</div>
);
-1
View File
@@ -34,7 +34,6 @@ i18n
ns: ['governance'],
defaultNS: 'governance',
keySeparator: false, // we use content as keys
nsSeparator: false,
backend,
saveMissing: useLocize && !!process.env.NX_LOCIZE_API_KEY,
interpolation: {
+14
View File
@@ -0,0 +1,14 @@
export const useTranslation = () => ({
t: (label: string, replacements?: Record<string, string>) => {
let translatedLabel = label;
if (typeof replacements === 'object' && replacements !== null) {
Object.keys(replacements).forEach((key) => {
translatedLabel = translatedLabel.replace(
`{{${key}}}`,
replacements[key]
);
});
}
return translatedLabel;
},
});
+1 -2
View File
@@ -1,10 +1,9 @@
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
import { Links } from '../../lib/links';
import classNames from 'classnames';
import { NavLink, Outlet } from 'react-router-dom';
export const Assets = () => {
const t = useT();
const linkClasses = ({ isActive }: { isActive: boolean }) => {
return classNames('border-b-2 border-transparent', {
'border-vega-yellow': isActive,
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import { Intent, TradingAnchorButton } from '@vegaprotocol/ui-toolkit';
import { GetStartedCheckList } from '../../components/welcome-dialog';
import {
@@ -7,10 +8,8 @@ import {
} from '../../components/welcome-dialog/use-get-onboarding-step';
import { Links } from '../../lib/links';
import classNames from 'classnames';
import { useT } from '../../lib/use-t';
export const DepositGetStarted = () => {
const t = useT();
const onboardingDismissed = useOnboardingStore((store) => store.dismissed);
const dismiss = useOnboardingStore((store) => store.dismiss);
const step = useGetOnboardingStep();
@@ -1,7 +1,6 @@
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
export const Disclaimer = () => {
const t = useT();
return (
<>
<h1 className="text-4xl uppercase xl:text-5xl font-alpha calt">
@@ -9,44 +8,37 @@ export const Disclaimer = () => {
</h1>
<p className="mt-10 mb-6">
{t(
'DISCLAIMER_P1',
'Vega is a decentralised peer-to-peer protocol that can be used to trade derivatives with cryptoassets. The Vega Protocol is an implementation layer (layer one) protocol made of free, public, open-source or source-available software. Use of the Vega Protocol involves various risks, including but not limited to, losses while digital assets are supplied to the Vega Protocol and losses due to the fluctuation of prices of assets.'
'Vega is a decentralised peer-to-peer protocol that can be used to trade derivatives with cryptoassets. The Vega Protocol is an implementation layer (layer one) protocol made of free, public, open-source or source-available software. Use of the Vega Protocol involves various risks, including but not limited to, losses while digital assets are supplied to the Vega Protocol and losses due to the fluctuation of prices of assets.'
)}
</p>
<p className="mb-6">
{t(
'DISCLAIMER_P2',
'Before using the Vega Protocol, review the relevant documentation at docs.vega.xyz to make sure that you understand how it works. Conduct your own due diligence and consult your financial advisor before making any investment decisions.'
'Before using the Vega Protocol, review the relevant documentation at docs.vega.xyz to make sure that you understand how it works. Conduct your own due diligence and consult your financial advisor before making any investment decisions.'
)}
</p>
<p className="mb-6">
{t(
'DISCLAIMER_P3',
'As described in the Vega Protocol core license, the Vega Protocol is provided “as is”, at your own risk, and without warranties of any kind. Although Gobalsky Labs Limited developed much of the initial code for the Vega Protocol, it does not provide or control the Vega Protocol, which is run by third parties deploying it on a bespoke blockchain. Upgrades and modifications to the Vega Protocol are managed in a community-driven way by holders of the VEGA governance token.'
'As described in the Vega Protocol core license, the Vega Protocol is provided “as is”, at your own risk, and without warranties of any kind. Although Gobalsky Labs Limited developed much of the initial code for the Vega Protocol, it does not provide or control the Vega Protocol, which is run by third parties deploying it on a bespoke blockchain. Upgrades and modifications to the Vega Protocol are managed in a community-driven way by holders of the VEGA governance token.'
)}
</p>
<p className="mb-8">
{t(
'DISCLAIMER_P4',
'No developer or entity involved in creating the Vega Protocol will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the Vega Protocol, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or legal costs, or loss of profits, cryptoassets, tokens or anything else of value.'
)}
</p>
<p className="mb-8">
{t(
'DISCLAIMER_P5',
'This website is hosted on a decentralised network, the Interplanetary File System (“IPFS”). The IPFS decentralised web is made up of all the computers (nodes) connected to it. Data is therefore stored on many different computers.'
'This website is hosted on a decentralised network, the Interplanetary File System (“IPFS”). The IPFS decentralised web is made up of all the computers (nodes) connected to it. Data is therefore stored on many different computers.'
)}
</p>
<p className="mb-8">
{t(
'DISCLAIMER_P6',
"The information provided on this website does not constitute investment advice, financial advice, trading advice, or any other sort of advice and you should not treat any of the website's content as such. No party recommends that any cryptoasset should be bought, sold, or held by you via this website. No party ensures the accuracy of information listed on this website or holds any responsibility for any missing or wrong information. You understand that you are using any and all information available here at your own risk."
"The information provided on this website does not constitute investment advice, financial advice, trading advice, or any other sort of advice and you should not treat any of the website's content as such. No party recommends that any cryptoasset should be bought, sold, or held by you via this website. No party ensures the accuracy of information listed on this website or holds any responsibility for any missing or wrong information. You understand that you are using any and all information available here at your own risk."
)}
</p>
<p className="mb-8">
{t(
'DISCLAIMER_P7',
'Additionally, just as you can access email protocols such as SMTP through multiple email clients, you can potentially access the Vega Protocol through many web or mobile interfaces. You are responsible for doing your own diligence on those interfaces to understand the associated risks and any fees.'
'Additionally, just as you can access email protocols such as SMTP through multiple email clients, you can potentially access the Vega Protocol through many web or mobile interfaces. You are responsible for doing your own diligence on those interfaces to understand the associated risks and any fees.'
)}
</p>
</>
+1 -2
View File
@@ -1,8 +1,7 @@
import { t } from '@vegaprotocol/i18n';
import { FeesContainer } from '../../components/fees-container';
import { useT } from '../../lib/use-t';
export const Fees = () => {
const t = useT();
return (
<div className="container p-4 mx-auto">
<h1 className="px-4 pb-4 text-2xl">{t('Fees')}</h1>
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import { VegaIconNames } from '@vegaprotocol/ui-toolkit';
import {
SidebarButton,
@@ -5,10 +6,8 @@ import {
ViewType,
} from '../../components/sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const LiquiditySidebar = () => {
const t = useT();
const currentRouteId = useGetCurrentRouteId();
return (
@@ -1,11 +1,11 @@
import { matchFilter, lpAggregatedDataProvider } from '@vegaprotocol/liquidity';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { Tab, Tabs } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { LiquidityContainer } from '../../components/liquidity-container';
import { useT } from '../../lib/use-t';
const enum LiquidityTabs {
Active = 'active',
@@ -24,7 +24,6 @@ export const LiquidityViewContainer = ({
}: {
marketId: string | undefined;
}) => {
const t = useT();
const [tab, setTab] = useState<string | undefined>(undefined);
const { pubKey } = useVegaWallet();
@@ -0,0 +1,3 @@
import { t } from '@vegaprotocol/i18n';
export const NO_MARKET = t('No market');
@@ -9,6 +9,7 @@ import {
getExpiryDate,
getMarketExpiryDate,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
Last24hPriceChange,
Last24hVolume,
@@ -30,14 +31,12 @@ import { MarketLiquiditySupplied } from '../../components/liquidity-supplied';
import { useEffect, useState } from 'react';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { PriceCell } from '@vegaprotocol/datagrid';
import { useT } from '../../lib/use-t';
interface MarketHeaderStatsProps {
market: Market;
}
export const MarketHeaderStats = ({ market }: MarketHeaderStatsProps) => {
const t = useT();
const { VEGA_EXPLORER_URL } = useEnvironment();
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
@@ -235,7 +234,6 @@ const useFormatCountdown = (
startTime?: number,
every?: number
) => {
const t = useT();
if (startTime && every) {
const diff = every - ((now - startTime) % every);
const hours = (diff / 3.6e6) | 0;
@@ -278,7 +276,6 @@ const ExpiryTooltipContent = ({
market,
explorerUrl,
}: ExpiryTooltipContentProps) => {
const t = useT();
if (market.marketTimestamps.close === null) {
const oracleId =
market.tradableInstrument.instrument.product.__typename === 'Future'
+5 -15
View File
@@ -1,5 +1,6 @@
import React, { useEffect, useMemo } from 'react';
import { addDecimalsFormatNumber, titlefy } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useScreenDimensions } from '@vegaprotocol/react-helpers';
import { useThrottledDataProvider } from '@vegaprotocol/data-provider';
import { ExternalLink, Loader, Splash } from '@vegaprotocol/ui-toolkit';
@@ -11,8 +12,6 @@ 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';
const calculatePrice = (markPrice?: string, decimalPlaces?: number) => {
return markPrice && decimalPlaces
@@ -58,7 +57,6 @@ const TitleUpdater = ({
};
export const MarketPage = () => {
const t = useT();
const { marketId } = useParams();
const navigate = useNavigate();
const currentRouteId = useGetCurrentRouteId();
@@ -113,18 +111,10 @@ export const MarketPage = () => {
{t('This market URL is not available any more.')}
</p>
<p className="justify-center text-sm">
<Trans
defaults="Please choose another market from the <0>market list<0>"
ns={ns}
components={[
<ExternalLink
onClick={() => navigate(Links.MARKETS())}
key="link"
>
market list
</ExternalLink>,
]}
/>
{t(`Please choose another market from the`)}{' '}
<ExternalLink onClick={() => navigate(Links.MARKETS())}>
{t('market list')}
</ExternalLink>
</p>
</span>
</Splash>
@@ -4,8 +4,10 @@ import { LayoutPriority } from 'allotment';
import classNames from 'classnames';
import AutoSizer from 'react-virtualized-auto-sizer';
import type { PinnedAsset } from '@vegaprotocol/accounts';
import { t } from '@vegaprotocol/i18n';
import { OracleBanner, useMarket } from '@vegaprotocol/markets';
import type { Market } from '@vegaprotocol/markets';
import { Filter } from '@vegaprotocol/orders';
import { Tab, LocalStoragePersistTabs as Tabs } from '@vegaprotocol/ui-toolkit';
import {
ResizableGrid,
@@ -19,7 +21,6 @@ import {
MarketTerminationBanner,
} from '../../components/market-banner';
import { FLAGS } from '@vegaprotocol/environment';
import { useT } from '../../lib/use-t';
interface TradeGridProps {
market: Market | null;
@@ -34,7 +35,6 @@ const MainGrid = memo(
marketId: string;
pinnedAsset?: PinnedAsset;
}) => {
const t = useT();
const { data: market } = useMarket(marketId);
const [sizes, handleOnLayoutChange] = usePaneLayout({ id: 'top' });
const [sizesMiddle, handleOnMiddleLayoutChange] = usePaneLayout({
@@ -125,13 +125,13 @@ const MainGrid = memo(
name={t('Open')}
menu={<TradingViews.activeOrders.menu />}
>
<TradingViews.activeOrders.component />
<TradingViews.orders.component filter={Filter.Open} />
</Tab>
<Tab id="closed-orders" name={t('Closed')}>
<TradingViews.closedOrders.component />
<TradingViews.orders.component filter={Filter.Closed} />
</Tab>
<Tab id="rejected-orders" name={t('Rejected')}>
<TradingViews.rejectedOrders.component />
<TradingViews.orders.component filter={Filter.Rejected} />
</Tab>
<Tab
id="orders"
@@ -4,6 +4,8 @@ import { OracleBanner } from '@vegaprotocol/markets';
import type { TradingView } from './trade-views';
import { TradingViews } from './trade-views';
import { useState } from 'react';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { NO_MARKET } from './constants';
import AutoSizer from 'react-virtualized-auto-sizer';
import classNames from 'classnames';
import {
@@ -12,8 +14,6 @@ import {
MarketTerminationBanner,
} from '../../components/market-banner';
import { FLAGS } from '@vegaprotocol/environment';
import { useT } from '../../lib/use-t';
import { Splash } from '@vegaprotocol/ui-toolkit';
interface TradePanelsProps {
market: Market | null;
@@ -30,10 +30,8 @@ export const TradePanels = ({ market, pinnedAsset }: TradePanelsProps) => {
throw new Error(`No component for view: ${view}`);
}
if (!market) return <NoMarketSplash />;
if (!market) return <Splash>{NO_MARKET}</Splash>;
// Watch out here, we don't know what component is being rendered
// so watch out for clashes in props
return <Component marketId={market?.id} pinnedAsset={pinnedAsset} />;
};
@@ -76,89 +74,33 @@ export const TradePanels = ({ market, pinnedAsset }: TradePanelsProps) => {
</AutoSizer>
</div>
<div className="flex flex-nowrap overflow-x-auto max-w-full border-t border-default">
{Object.keys(TradingViews)
// filter to control available views for the current market
// eg only perps should get the funding views
.filter((_key) => {
const key = _key as TradingView;
const perpOnlyViews = ['funding', 'fundingPayments'];
if (
market?.tradableInstrument.instrument.product.__typename ===
'Perpetual'
) {
return true;
{Object.keys(TradingViews).map((key) => {
const isActive = view === key;
const className = classNames(
'py-2 px-4 min-w-[100px] capitalize text-sm',
{
'bg-vega-clight-500 dark:bg-vega-cdark-500': isActive,
}
if (perpOnlyViews.includes(key)) {
return false;
}
return true;
})
.map((_key) => {
const key = _key as TradingView;
const isActive = view === key;
return (
<ViewButton
key={key}
view={key}
isActive={isActive}
onClick={() => setView(key)}
/>
);
})}
);
if (
market?.tradableInstrument.instrument.product.__typename !==
'Perpetual' &&
(key === 'funding' || key === 'fundingPayments')
) {
return null;
}
return (
<button
data-testid={key}
onClick={() => setView(key as TradingView)}
className={className}
key={key}
>
{TradingViews[key as keyof typeof TradingViews].label}
</button>
);
})}
</div>
</div>
);
};
export const NoMarketSplash = () => {
const t = useT();
return <Splash>{t('No market')}</Splash>;
};
const ViewButton = ({
view,
isActive,
onClick,
}: {
view: TradingView;
isActive: boolean;
onClick: () => void;
}) => {
const label = useViewLabel(view);
const className = classNames('py-2 px-4 min-w-[100px] capitalize text-sm', {
'bg-vega-clight-500 dark:bg-vega-cdark-500': isActive,
});
return (
<button data-testid={view} onClick={onClick} className={className}>
{label}
</button>
);
};
const useViewLabel = (view: TradingView) => {
const t = useT();
const labels = {
candles: t('Candles'),
depth: t('Depth'),
liquidity: t('Liquidity'),
funding: t('Funding'),
fundingPayments: t('Funding Payments'),
orderbook: t('Orderbook'),
trades: t('Trades'),
positions: t('Positions'),
activeOrders: t('Active'),
closedOrders: t('Closed'),
rejectedOrders: t('Rejected'),
orders: t('All'),
stopOrders: t('Stop'),
collateral: t('Collateral'),
fills: t('Fills'),
};
return labels[view];
};
@@ -1,9 +1,12 @@
import type { ComponentProps } from 'react';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { DepthChartContainer } from '@vegaprotocol/market-depth';
import {
CandlesChartContainer,
CandlesMenu,
} from '@vegaprotocol/candles-chart';
import { Filter, OpenOrdersMenu } from '@vegaprotocol/orders';
import { NO_MARKET } from './constants';
import { TradesContainer } from '../../components/trades-container';
import { OrderbookContainer } from '../../components/orderbook-container';
import { FillsContainer } from '../../components/fills-container';
@@ -12,60 +15,96 @@ import { AccountsContainer } from '../../components/accounts-container';
import { LiquidityContainer } from '../../components/liquidity-container';
import { FundingContainer } from '../../components/funding-container';
import { FundingPaymentsContainer } from '../../components/funding-payments-container';
import type { OrderContainerProps } from '../../components/orders-container';
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';
type MarketDependantView =
| typeof CandlesChartContainer
| typeof DepthChartContainer
| typeof OrderbookContainer
| typeof TradesContainer;
type MarketDependantViewProps = ComponentProps<MarketDependantView>;
const requiresMarket = (View: MarketDependantView) => {
const WrappedComponent = (props: MarketDependantViewProps) =>
props.marketId ? <View {...props} /> : <Splash>{NO_MARKET}</Splash>;
WrappedComponent.displayName = `RequiresMarket(${View.name})`;
return WrappedComponent;
};
export type TradingView = keyof typeof TradingViews;
export const TradingViews = {
candles: {
component: CandlesChartContainer,
label: 'Candles',
component: requiresMarket(CandlesChartContainer),
menu: CandlesMenu,
},
depth: {
component: DepthChartContainer,
label: 'Depth',
component: requiresMarket(DepthChartContainer),
},
liquidity: {
component: LiquidityContainer,
label: 'Liquidity',
component: requiresMarket(LiquidityContainer),
},
funding: {
component: FundingContainer,
label: 'Funding',
component: requiresMarket(FundingContainer),
},
fundingPayments: {
label: 'Funding Payments',
component: FundingPaymentsContainer,
},
orderbook: {
component: OrderbookContainer,
label: 'Orderbook',
component: requiresMarket(OrderbookContainer),
},
trades: {
component: TradesContainer,
label: 'Trades',
component: requiresMarket(TradesContainer),
},
positions: {
label: 'Positions',
component: PositionsContainer,
menu: PositionsMenu,
},
activeOrders: {
component: () => <OrdersContainer filter={Filter.Open} />,
label: 'Active',
component: (props: OrderContainerProps) => (
<OrdersContainer {...props} filter={Filter.Open} />
),
menu: OpenOrdersMenu,
},
closedOrders: {
component: () => <OrdersContainer filter={Filter.Closed} />,
label: 'Closed',
component: (props: OrderContainerProps) => (
<OrdersContainer {...props} filter={Filter.Closed} />
),
},
rejectedOrders: {
component: () => <OrdersContainer filter={Filter.Rejected} />,
label: 'Rejected',
component: (props: OrderContainerProps) => (
<OrdersContainer {...props} filter={Filter.Rejected} />
),
},
orders: {
label: 'All',
component: OrdersContainer,
menu: OpenOrdersMenu,
},
stopOrders: {
label: 'Stop',
component: StopOrdersContainer,
},
collateral: {
label: 'Collateral',
component: AccountsContainer,
menu: AccountsMenu,
},
fills: { component: FillsContainer },
} as const;
fills: { label: 'Fills', component: FillsContainer },
};
+2 -3
View File
@@ -8,6 +8,7 @@ import type {
import { AgGrid, COL_DEFS } from '@vegaprotocol/datagrid';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { useMemo } from 'react';
import { t } from '@vegaprotocol/i18n';
import type { Asset } from '@vegaprotocol/types';
import type { ProductType } from '@vegaprotocol/types';
import { MarketState, MarketStateMapping } from '@vegaprotocol/types';
@@ -23,7 +24,6 @@ import { SettlementDateCell } from './settlement-date-cell';
import { SettlementPriceCell } from './settlement-price-cell';
import { MarketCodeCell } from './market-code-cell';
import { MarketActionsDropdown } from './market-table-actions';
import { useT } from '../../lib/use-t';
type SettlementAsset = Pick<
Asset,
@@ -127,7 +127,6 @@ const ClosedMarketsDataGrid = ({
rowData: Row[];
error: Error | undefined;
}) => {
const t = useT();
const handleOnSelect = useMarketClickHandler();
const openAssetDialog = useAssetDetailsDialogStore((store) => store.open);
@@ -275,7 +274,7 @@ const ClosedMarketsDataGrid = ({
},
},
];
}, [openAssetDialog, t]);
}, [openAssetDialog]);
return (
<AgGrid
@@ -2,7 +2,7 @@ import compact from 'lodash/compact';
import type { ProductType } from '@vegaprotocol/types';
import { ProductTypeMapping, ProductTypeShortName } from '@vegaprotocol/types';
import { StackedCell } from '@vegaprotocol/datagrid';
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
export interface MarketCodeCellProps {
value: string | undefined; // market code
@@ -14,7 +14,6 @@ export interface MarketCodeCellProps {
}
export const MarketCodeCell = ({ value, data }: MarketCodeCellProps) => {
const t = useT();
if (!value || !data || !data.productType) return null;
const infoSpanClasses =
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import {
TradingDropdownItem,
TradingDropdownCopyItem,
@@ -10,7 +11,6 @@ import { DApp, EXPLORER_MARKET, useLinks } from '@vegaprotocol/environment';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
import { useNavigate } from 'react-router-dom';
import { Links } from '../../lib/links';
import { useT } from '../../lib/use-t';
export const MarketActionsDropdown = ({
marketId,
@@ -23,7 +23,6 @@ export const MarketActionsDropdown = ({
successorMarketID: string | null | undefined;
parentMarketID: string | null | undefined;
}) => {
const t = useT();
const navigate = useNavigate();
const open = useAssetDetailsDialogStore((store) => store.open);
const linkCreator = useLinks(DApp.Explorer);
@@ -1,5 +1,6 @@
import React, { useEffect } from 'react';
import { titlefy } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
LocalStoragePersistTabs as Tabs,
Tab,
@@ -14,10 +15,8 @@ import {
TOKEN_NEW_MARKET_PROPOSAL,
useLinks,
} from '@vegaprotocol/environment';
import { useT } from '../../lib/use-t';
export const MarketsPage = () => {
const t = useT();
const { updateTitle } = usePageTitleStore((store) => ({
updateTitle: store.updateTitle,
}));
@@ -26,8 +25,8 @@ export const MarketsPage = () => {
const externalLink = governanceLink(TOKEN_NEW_MARKET_PROPOSAL);
useEffect(() => {
updateTitle(titlefy([t('Markets')]));
}, [updateTitle, t]);
updateTitle(titlefy(['Markets']));
}, [updateTitle]);
return (
<div className="h-full pt-0.5 pb-3 px-1.5">
@@ -1,5 +1,6 @@
import { Route, Routes, useParams } from 'react-router-dom';
import { MarketState } from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
import { useMarket } from '@vegaprotocol/markets';
import { VegaIconNames } from '@vegaprotocol/ui-toolkit';
import {
@@ -8,10 +9,8 @@ import {
ViewType,
} from '../../components/sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const MarketsSidebar = () => {
const t = useT();
const { marketId } = useParams();
const currentRouteId = useGetCurrentRouteId();
const { data } = useMarket(marketId);
@@ -2,17 +2,16 @@ import { useDataProvider } from '@vegaprotocol/data-provider';
import type { MarketMaybeWithData } from '@vegaprotocol/markets';
import { marketListProvider } from '@vegaprotocol/markets';
import { useEffect } from 'react';
import { t } from '@vegaprotocol/i18n';
import type { CellClickedEvent } from 'ag-grid-community';
import MarketListTable from './market-list-table';
import { useMarketClickHandler } from '../../lib/hooks/use-market-click-handler';
import { Interval } from '@vegaprotocol/types';
import { useYesterday } from '@vegaprotocol/react-helpers';
import { useT } from '../../lib/use-t';
const POLLING_TIME = 2000;
export const OpenMarkets = () => {
const t = useT();
const handleOnSelect = useMarketClickHandler();
const yesterday = useYesterday();
const { data, error, reload } = useDataProvider({
@@ -1,8 +1,8 @@
import { DApp, EXPLORER_ORACLE, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { MarketState } from '@vegaprotocol/types';
import { Link } from '@vegaprotocol/ui-toolkit';
import { getDateTimeFormat } from '@vegaprotocol/utils';
import { useT } from '../../lib/use-t';
import { formatDistanceToNowStrict, isAfter } from 'date-fns';
export interface SettlementDataCellProps {
@@ -18,7 +18,6 @@ export const SettlementDateCell = ({
closeTimestamp,
marketState,
}: SettlementDataCellProps) => {
const t = useT();
const linkCreator = useLinks(DApp.Explorer);
const date = closeTimestamp ? new Date(closeTimestamp) : metaDate;
@@ -32,12 +31,12 @@ export const SettlementDateCell = ({
if (expiryHasPassed) {
if (marketState !== MarketState.STATE_SETTLED) {
text = t('Expected {{distance}} ago', { distance });
text = t('Expected %s ago', distance);
} else {
text = t('{{distance}} ago', { distance });
text = t('%s ago', distance);
}
} else {
text = t('Expected in {{distance}}', { distance });
text = t('Expected in %s', distance);
}
}
@@ -1,10 +1,10 @@
import { DApp, EXPLORER_ORACLE, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import type { DataSourceFilterFragment } from '@vegaprotocol/markets';
import { useOracleSpecBindingData } from '@vegaprotocol/markets';
import { PropertyKeyType } from '@vegaprotocol/types';
import { Link } from '@vegaprotocol/ui-toolkit';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { useT } from '../../lib/use-t';
export interface SettlementPriceCellProps {
oracleSpecId: string | undefined;
@@ -17,7 +17,6 @@ export const SettlementPriceCell = ({
settlementDataSpecBinding,
filter,
}: SettlementPriceCellProps) => {
const t = useT();
const linkCreator = useLinks(DApp.Explorer);
const { property, loading } = useOracleSpecBindingData(
oracleSpecId,
@@ -1,5 +1,6 @@
import { useMemo } from 'react';
import type { ColDef, ValueFormatterParams } from 'ag-grid-community';
import { t } from '@vegaprotocol/i18n';
import type {
VegaICellRendererParams,
VegaValueFormatterParams,
@@ -17,12 +18,10 @@ import type {
import { MarketActionsDropdown } from './market-table-actions';
import { calcCandleVolume, getAsset } from '@vegaprotocol/markets';
import { MarketCodeCell } from './market-code-cell';
import { useT } from '../../lib/use-t';
const { MarketTradingMode, AuctionTrigger } = Schema;
export const useColumnDefs = () => {
const t = useT();
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
return useMemo<ColDef[]>(
() => [
@@ -217,6 +216,6 @@ export const useColumnDefs = () => {
},
},
],
[openAssetDetailsDialog, t]
[openAssetDetailsDialog]
);
};
@@ -1,10 +1,9 @@
import { t } from '@vegaprotocol/i18n';
import { VegaIconNames } from '@vegaprotocol/ui-toolkit';
import { SidebarButton, ViewType } from '../../components/sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const PortfolioSidebar = () => {
const t = useT();
const currentRouteId = useGetCurrentRouteId();
return (
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
import type { ReactNode } from 'react';
import { LayoutPriority } from 'allotment';
import { titlefy } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useIncompleteWithdrawals } from '@vegaprotocol/withdraws';
import { Tab, LocalStoragePersistTabs as Tabs } from '@vegaprotocol/ui-toolkit';
import { usePageTitleStore } from '../../stores';
@@ -24,7 +25,6 @@ import { AccountsMenu } from '../../components/accounts-menu';
import { DepositsMenu } from '../../components/deposits-menu';
import { WithdrawalsMenu } from '../../components/withdrawals-menu';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
const WithdrawalsIndicator = () => {
const { ready } = useIncompleteWithdrawals();
@@ -39,7 +39,6 @@ const WithdrawalsIndicator = () => {
};
export const Portfolio = () => {
const t = useT();
const currentRouteId = useGetCurrentRouteId();
const { getView, setViews } = useSidebar();
const view = getView(currentRouteId);
@@ -50,7 +49,7 @@ export const Portfolio = () => {
useEffect(() => {
updateTitle(titlefy([t('Portfolio')]));
}, [updateTitle, t]);
}, [updateTitle]);
// Make transfer sidebar open by default
useEffect(() => {
@@ -16,13 +16,13 @@ import { useVegaWallet, useVegaWalletDialogStore } from '@vegaprotocol/wallet';
import { useReferral } from './hooks/use-referral';
import { Routes } from '../../lib/links';
import { useTransactionEventSubscription } from '@vegaprotocol/web3';
import { t } from '@vegaprotocol/i18n';
import { Statistics, useStats } from './referral-statistics';
import { useReferralProgram } from './hooks/use-referral-program';
import { useT } from '../../lib/use-t';
const RELOAD_DELAY = 3000;
const validateCode = (value: string, t: ReturnType<typeof useT>) => {
const validateCode = (value: string) => {
const number = +`0x${value}`;
if (!value || value.length !== 64) {
return t('Code must be 64 characters in length');
@@ -33,7 +33,6 @@ const validateCode = (value: string, t: ReturnType<typeof useT>) => {
};
export const ApplyCodeForm = () => {
const t = useT();
const program = useReferralProgram();
const navigate = useNavigate();
const openWalletDialog = useVegaWalletDialogStore(
@@ -60,7 +59,7 @@ export const ApplyCodeForm = () => {
const codeField = watch('code');
const { data: previewData, loading: previewLoading } = useReferral({
code: validateCode(codeField, t) ? codeField : undefined,
code: validateCode(codeField) ? codeField : undefined,
});
useEffect(() => {
@@ -224,7 +223,7 @@ export const ApplyCodeForm = () => {
hasError={Boolean(errors.code)}
{...register('code', {
required: t('You have to provide a code to apply it.'),
validate: (value) => validateCode(value, t),
validate: validateCode,
})}
placeholder="Enter a code"
className="mb-2 bg-vega-clight-900 dark:bg-vega-cdark-700"
@@ -24,14 +24,13 @@ import {
DISCLAIMER_REFERRAL_DOCS_LINK,
} from './constants';
import { useReferral } from './hooks/use-referral';
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
export const CreateCodeContainer = () => {
return <CreateCodeForm />;
};
export const CreateCodeForm = () => {
const t = useT();
const [dialogOpen, setDialogOpen] = useState(false);
const openWalletDialog = useVegaWalletDialogStore(
(store) => store.openVegaWalletDialog
@@ -82,7 +81,6 @@ const CreateCodeDialog = ({
}: {
setDialogOpen: (open: boolean) => void;
}) => {
const t = useT();
const createLink = useLinks(DApp.Governance);
const { isReadOnly, pubKey, sendTx } = useVegaWallet();
const { refetch } = useReferral({ pubKey, role: 'referrer' });
@@ -95,11 +93,6 @@ const CreateCodeDialog = ({
const { stakeAvailable: currentStakeAvailable, requiredStake } =
useStakeAvailable();
const { data: referralSets } = useReferral({
pubKey,
role: 'referrer',
});
const onSubmit = () => {
if (isReadOnly || !pubKey) {
setErr('Not connected');
@@ -177,14 +170,10 @@ const CreateCodeDialog = ({
return (
<div className="flex flex-col gap-4">
<p>
{t('You need at least')}{' '}
{addDecimalsFormatNumber(requiredStake.toString(), 18)}{' '}
{t(
'You need at least {{requiredStake}} VEGA staked to generate a referral code and participate in the referral program.',
{
requiredStake: addDecimalsFormatNumber(
requiredStake.toString(),
18
),
}
'VEGA staked to generate a referral code and participate in the referral program.'
)}
</p>
<TradingAnchorButton
@@ -198,68 +187,6 @@ const CreateCodeDialog = ({
);
}
if (!referralSets) {
return (
<div className="flex flex-col gap-4">
{(status === 'idle' || status === 'loading' || status === 'error') && (
<>
{
<p>
{t(
'There is currently no referral program active, are you sure you want to create a code?'
)}
</p>
}
</>
)}
{status === 'success' && code && (
<div className="flex items-center gap-2">
<div className="flex-1 min-w-0 p-2 text-sm rounded bg-vega-clight-700 dark:bg-vega-cdark-700">
<p className="overflow-hidden whitespace-nowrap text-ellipsis">
{code}
</p>
</div>
<CopyWithTooltip text={code}>
<TradingButton
className="text-sm no-underline"
icon={<VegaIcon name={VegaIconNames.COPY} />}
>
<span>{t('Copy')}</span>
</TradingButton>
</CopyWithTooltip>
</div>
)}
<TradingButton
fill={true}
intent={Intent.Primary}
onClick={() => onSubmit()}
{...getButtonProps()}
></TradingButton>
{status === 'idle' && (
<TradingButton
fill={true}
intent={Intent.Primary}
onClick={() => {
refetch();
setDialogOpen(false);
}}
>
{t('No')}
</TradingButton>
)}
{err && <InputError>{err}</InputError>}
<div className="flex justify-center pt-5 mt-2 text-sm border-t gap-4 text-default border-default">
<ExternalLink href={ABOUT_REFERRAL_DOCS_LINK}>
{t('About the referral program')}
</ExternalLink>
<ExternalLink href={DISCLAIMER_REFERRAL_DOCS_LINK}>
{t('Disclaimer')}
</ExternalLink>
</div>
</div>
);
}
return (
<div className="flex flex-col gap-4">
{(status === 'idle' || status === 'loading' || status === 'error') && (
@@ -3,22 +3,21 @@ import { RainbowButton } from './buttons';
import { AnimatedDudeWithWire } from './graphics/dude';
import { LayoutWithSky } from './layout';
import { Routes } from '../../lib/links';
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
export const ErrorBoundary = () => {
const t = useT();
const error = useRouteError();
const navigate = useNavigate();
const title = isRouteErrorResponse(error)
? `${error.status} ${error.statusText}`
: t('Something went wrong');
: 'Something went wrong';
const code = isRouteErrorResponse(error) ? error.status : 0;
const messages: Record<number, string> = {
0: t('An unknown error occurred.'),
404: t("The page you're looking for doesn't exists."),
0: 'An unknown error occurred.',
404: "The page you're looking for doesn't exists.",
};
return (
@@ -49,7 +48,6 @@ export const ErrorBoundary = () => {
};
export const NotFound = () => {
const t = useT();
const navigate = useNavigate();
return (
@@ -1,66 +1,63 @@
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
import { Table } from './table';
export const HowItWorksTable = () => {
const t = useT();
return (
<Table
className="bg-none bg-vega-clight-800 dark:bg-vega-cdark-800"
noHeader
noCollapse
columns={[{ name: 'number', className: 'pr-0' }, { name: 'step' }]}
data={[
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
1
</span>
),
step: t(
'Referrers generate a code assigned to their key via an on chain transaction'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
2
</span>
),
step: t(
'Anyone with the referral link can apply it to their key(s) of choice via an on chain transaction'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
3
</span>
),
step: t(
'Discounts are applied automatically during trading based on the key(s) used'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
4
</span>
),
step: t(
'Referrers earn commission based on a percentage of the taker fees their referees pay'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
5
</span>
),
step: t(
'The commission is taken from the infrastructure fee, maker fee, and liquidity provider fee, not from the referee'
),
},
]}
></Table>
);
};
export const HowItWorksTable = () => (
<Table
className="bg-none bg-vega-clight-800 dark:bg-vega-cdark-800"
noHeader
noCollapse
columns={[{ name: 'number', className: 'pr-0' }, { name: 'step' }]}
data={[
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
1
</span>
),
step: t(
'Referrers generate a code assigned to their key via an on chain transaction'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
2
</span>
),
step: t(
'Anyone with the referral link can apply it to their key(s) of choice via an on chain transaction'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
3
</span>
),
step: t(
'Discounts are applied automatically during trading based on the key(s) used'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
4
</span>
),
step: t(
'Referrers earn commission based on a percentage of the taker fees their referees pay'
),
},
{
number: (
<span className="text-2xl calt text-vega-clight-100 dark:text-vega-cdark-100">
5
</span>
),
step: t(
'The commission is taken from the infrastructure fee, maker fee, and liquidity provider fee, not from the referee'
),
},
]}
></Table>
);
@@ -1,9 +1,8 @@
import classNames from 'classnames';
import { AnimatedDudeWithWire } from './graphics/dude';
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
export const LandingBanner = () => {
const t = useT();
return (
<div className={classNames('relative mb-20')}>
<div className="">
@@ -28,10 +28,9 @@ import sortBy from 'lodash/sortBy';
import { useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useCurrentEpochInfoQuery } from './hooks/__generated__/Epoch';
import BigNumber from 'bignumber.js';
import { t } from '@vegaprotocol/i18n';
import maxBy from 'lodash/maxBy';
import { DocsLinks } from '@vegaprotocol/environment';
import { useT, ns } from '../../lib/use-t';
import { Trans } from 'react-i18next';
export const ReferralStatistics = () => {
const { pubKey } = useVegaWallet();
@@ -153,7 +152,6 @@ export const Statistics = ({
program: ReturnType<typeof useReferralProgram>;
as: 'referrer' | 'referee';
}) => {
const t = useT();
const {
baseCommissionValue,
runningVolumeValue,
@@ -187,15 +185,10 @@ export const Statistics = ({
const baseCommissionTile = (
<StatTile
title={t('Base commission rate')}
description={t(
'(Combined set volume {{runningVolume}} over last {{epochs}} epochs)',
{
runningVolume: compactNumFormat.format(runningVolumeValue),
epochs: (
details?.windowLength || DEFAULT_AGGREGATION_DAYS
).toString(),
}
)}
description={t('(Combined set volume %s over last %s epochs)', [
compactNumFormat.format(runningVolumeValue),
(details?.windowLength || DEFAULT_AGGREGATION_DAYS).toString(),
])}
>
{baseCommissionValue * 100}%
</StatTile>
@@ -203,9 +196,10 @@ export const Statistics = ({
const stakingMultiplierTile = (
<StatTile
title={t('Staking multiplier')}
description={t('{{amount}} $VEGA staked', {
amount: addDecimalsFormatNumber(stakeAvailable?.toString() || 0, 18),
})}
description={`(${addDecimalsFormatNumber(
stakeAvailable?.toString() || 0,
18
)} $VEGA staked)`}
>
{multiplier || t('None')}
</StatTile>
@@ -238,9 +232,10 @@ export const Statistics = ({
const referrerVolumeTile = (
<StatTile
title={t('My volume (last {{count}} epochs)', {
count: details?.windowLength || DEFAULT_AGGREGATION_DAYS,
})}
title={t(
'My volume (last %s epochs)',
(details?.windowLength || DEFAULT_AGGREGATION_DAYS).toString()
)}
>
{compactNumFormat.format(referrerVolumeValue)}
</StatTile>
@@ -251,9 +246,10 @@ export const Statistics = ({
.reduce((all, r) => all.plus(r), new BigNumber(0));
const totalCommissionTile = (
<StatTile
title={t('Total commission (last {{count}}} epochs)', {
count: details?.windowLength || DEFAULT_AGGREGATION_DAYS,
})}
title={t(
'Total commission (last %s epochs)',
(details?.windowLength || DEFAULT_AGGREGATION_DAYS).toString()
)}
description={<QUSDTooltip />}
>
{getNumberFormat(0).format(Number(totalCommissionValue))}
@@ -294,9 +290,10 @@ export const Statistics = ({
);
const runningVolumeTile = (
<StatTile
title={t('Combined volume (last {{count}} epochs)', {
count: details?.windowLength,
})}
title={t(
'Combined volume (last %s epochs)',
details?.windowLength.toString()
)}
>
{compactNumFormat.format(runningVolumeValue)}
</StatTile>
@@ -384,22 +381,25 @@ export const Statistics = ({
{ name: 'joined', displayName: t('Date Joined') },
{
name: 'volume',
displayName: t('Volume (last {{count}} epochs)', {
count: details?.windowLength || DEFAULT_AGGREGATION_DAYS,
}),
displayName: t(
'Volume (last %s epochs)',
(
details?.windowLength || DEFAULT_AGGREGATION_DAYS
).toString()
),
},
{
name: 'commission',
displayName: (
<Trans
i18nKey="referral-statistics-commission"
defaults="Commission earned in <0>qUSD</0> (last {{count}} epochs)"
values={{
count:
details?.windowLength || DEFAULT_AGGREGATION_DAYS,
}}
ns={ns}
/>
<>
{t('Commission earned in')} <QUSDTooltip />{' '}
{t(
'(last %s epochs)',
(
details?.windowLength || DEFAULT_AGGREGATION_DAYS
).toString()
)}
</>
),
},
]}
@@ -430,27 +430,24 @@ export const Statistics = ({
);
};
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>
export const QUSDTooltip = () => (
<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'
)}
</>
}
underline={true}
>
<span>{t('qUSD')}</span>
</Tooltip>
);
};
</p>
{DocsLinks && (
<ExternalLink href={DocsLinks.QUANTUM}>
{t('Find out more')}
</ExternalLink>
)}
</>
}
underline={true}
>
<span>{t('qUSD')}</span>
</Tooltip>
);
@@ -17,22 +17,18 @@ import classNames from 'classnames';
import { usePageTitleStore } from '../../stores';
import { useEffect } from 'react';
import { titlefy } from '@vegaprotocol/utils';
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
const Nav = () => {
const t = useT();
return (
<div className="flex justify-center border-b border-vega-cdark-500">
<TabLink end to={Routes.REFERRALS}>
{t('I want a code')}
</TabLink>
<TabLink to={Routes.REFERRALS_APPLY_CODE}>{t('I have a code')}</TabLink>
</div>
);
};
const Nav = () => (
<div className="flex justify-center border-b border-vega-cdark-500">
<TabLink end to={Routes.REFERRALS}>
{t('I want a code')}
</TabLink>
<TabLink to={Routes.REFERRALS_APPLY_CODE}>{t('I have a code')}</TabLink>
</div>
);
export const Referrals = () => {
const t = useT();
const { pubKey } = useVegaWallet();
const {
@@ -62,7 +58,7 @@ export const Referrals = () => {
useEffect(() => {
updateTitle(titlefy([t('Referrals')]));
}, [updateTitle, t]);
}, [updateTitle]);
return (
<>
+16 -35
View File
@@ -6,14 +6,8 @@ import { BORDER_COLOR, GRADIENT } from './constants';
import { Tag } from './tag';
import type { ComponentProps, ReactNode } from 'react';
import { ExternalLink } from '@vegaprotocol/ui-toolkit';
import {
DApp,
DocsLinks,
TOKEN_PROPOSALS,
useLinks,
} from '@vegaprotocol/environment';
import { useT, ns } from '../../lib/use-t';
import { Trans } from 'react-i18next';
import { DApp, TOKEN_PROPOSALS, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
const Loading = ({ variant }: { variant: 'large' | 'inline' }) => (
<div
@@ -37,7 +31,6 @@ const StakingTier = ({
referralRewardMultiplier: string;
minimumStakedTokens: string;
}) => {
const t = useT();
const color: Record<number, ComponentProps<typeof Tag>['color']> = {
1: 'green',
2: 'blue',
@@ -69,9 +62,7 @@ const StakingTier = ({
<Tag color={color[tier]}>Multiplier {referralRewardMultiplier}x</Tag>
<h3 className="mt-1 mb-1 text-base">{label}</h3>
<p className="text-sm text-vega-clight-100 dark:text-vega-cdark-100">
{t('Stake a minimum of {{minimumStakedTokens}} $VEGA tokens', {
minimumStakedTokens,
})}
{t('Stake a minimum of')} {minimumStakedTokens} {t('$VEGA tokens')}
</p>
</div>
</div>
@@ -79,7 +70,6 @@ const StakingTier = ({
};
export const TiersContainer = () => {
const t = useT();
const { benefitTiers, stakingTiers, details, loading, error } =
useReferralProgram();
@@ -92,24 +82,13 @@ export const TiersContainer = () => {
if ((!loading && !details) || error) {
return (
<div className="text-base px-5 py-10 text-center">
<Trans
defaults="There are currently no active referral programs. Check the <0>Governance App</0> to see if there are any proposals in progress and vote."
components={[
<ExternalLink href={governanceLink(TOKEN_PROPOSALS)} key="link">
{t('Governance App')}
</ExternalLink>,
]}
ns={ns}
/>
<Trans
defaults="You can propose a new program via the <0>Docs</0>."
components={[
<ExternalLink href={DocsLinks?.REFERRALS} key="link">
{t('Docs')}
</ExternalLink>,
]}
ns={ns}
/>
{t(
"We're sorry but we don't have an active referral programme currently running. You can propose a new programme"
)}{' '}
<ExternalLink href={governanceLink(TOKEN_PROPOSALS)}>
{t('here')}
</ExternalLink>
.
</div>
);
}
@@ -195,7 +174,6 @@ const TiersTable = ({
}>;
windowLength?: number;
}) => {
const t = useT();
return (
<Table
columns={[
@@ -208,9 +186,12 @@ const TiersTable = ({
{ name: 'discount', displayName: t('Referrer trading discount') },
{
name: 'volume',
displayName: t('Min. trading volume (last {{count}} epochs)', {
count: windowLength,
}),
displayName: t(
'Min. trading volume %s',
windowLength
? t('(last %s epochs)', windowLength.toString())
: undefined
),
},
{ name: 'epochs', displayName: t('Min. epochs') },
]}
+2 -5
View File
@@ -7,7 +7,7 @@ import {
import classNames from 'classnames';
import type { HTMLAttributes, ReactNode } from 'react';
import { Button } from './buttons';
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
export const Tile = ({
className,
@@ -62,13 +62,10 @@ export const CodeTile = ({
createdAt?: string;
className?: string;
}) => {
const t = useT();
return (
<StatTile
title={t('Your referral code')}
description={
createdAt ? t('(Created at: {{createdAt}})', { createdAt }) : undefined
}
description={createdAt ? t('(Created at: %s)', createdAt) : undefined}
>
<div className="flex items-center justify-between gap-2">
<Tooltip
@@ -1 +0,0 @@
export { Rewards } from './rewards';
@@ -1,11 +0,0 @@
import { t } from '@vegaprotocol/i18n';
import { RewardsContainer } from '../../components/rewards-container';
export const Rewards = () => {
return (
<div className="container mx-auto p-4">
<h1 className="px-4 pb-4 text-2xl">{t('Rewards')}</h1>
<RewardsContainer />
</div>
);
};
@@ -1,4 +1,5 @@
import { useCallback } from 'react';
import { t } from '@vegaprotocol/i18n';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
import { useVegaWallet } from '@vegaprotocol/wallet';
@@ -12,14 +13,12 @@ import { createDataGridSlice } from '../../stores/datagrid-store-slice';
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';
export const AccountsContainer = ({
pinnedAsset,
}: {
pinnedAsset?: PinnedAsset;
}) => {
const t = useT();
const onMarketClick = useMarketClickHandler(true);
const { pubKey, isReadOnly } = useVegaWallet();
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
@@ -1,10 +1,9 @@
import { t } from '@vegaprotocol/i18n';
import { TradingButton } from '@vegaprotocol/ui-toolkit';
import { ViewType, useSidebar } from '../sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const AccountsMenu = () => {
const t = useT();
const currentRouteId = useGetCurrentRouteId();
const setViews = useSidebar((store) => store.setViews);
@@ -8,13 +8,12 @@ import {
NodeGuard,
useEnvironment,
} from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { VegaWalletProvider } from '@vegaprotocol/wallet';
import type { ReactNode } from 'react';
import { Suspense, type ReactNode } from 'react';
import { Web3Provider } from './web3-provider';
import { useT } from '../../lib/use-t';
export const Bootstrapper = ({ children }: { children: ReactNode }) => {
const t = useT();
const {
error,
VEGA_URL,
@@ -37,45 +36,43 @@ export const Bootstrapper = ({ children }: { children: ReactNode }) => {
}
return (
<NetworkLoader
cache={cacheConfig}
skeleton={<AppLoader />}
failure={
<AppFailure title={t('Could not initialize app')} error={error} />
}
>
<NodeGuard
<Suspense fallback={<AppLoader />}>
<NetworkLoader
cache={cacheConfig}
skeleton={<AppLoader />}
failure={
<NodeFailure
title={t('Node: {{VEGA_URL}} is unsuitable', { VEGA_URL })}
/>
<AppFailure title={t('Could not initialize app')} error={error} />
}
>
<Web3Provider
<NodeGuard
skeleton={<AppLoader />}
failure={
<AppFailure title={t('Could not configure web3 provider')} />
}
failure={<NodeFailure title={t(`Node: ${VEGA_URL} is unsuitable`)} />}
>
<VegaWalletProvider
config={{
network: VEGA_ENV,
vegaUrl: VEGA_URL,
vegaWalletServiceUrl: VEGA_WALLET_URL,
links: {
explorer: VEGA_EXPLORER_URL,
concepts: DocsLinks.VEGA_WALLET_CONCEPTS_URL,
chromeExtensionUrl: CHROME_EXTENSION_URL,
mozillaExtensionUrl: MOZILLA_EXTENSION_URL,
},
}}
<Web3Provider
skeleton={<AppLoader />}
failure={
<AppFailure title={t(`Could not configure web3 provider`)} />
}
>
{children}
</VegaWalletProvider>
</Web3Provider>
</NodeGuard>
</NetworkLoader>
<VegaWalletProvider
config={{
network: VEGA_ENV,
vegaUrl: VEGA_URL,
vegaWalletServiceUrl: VEGA_WALLET_URL,
links: {
explorer: VEGA_EXPLORER_URL,
concepts: DocsLinks.VEGA_WALLET_CONCEPTS_URL,
chromeExtensionUrl: CHROME_EXTENSION_URL,
mozillaExtensionUrl: MOZILLA_EXTENSION_URL,
},
}}
>
{children}
</VegaWalletProvider>
</Web3Provider>
</NodeGuard>
</NetworkLoader>
</Suspense>
);
};
-102
View File
@@ -1,102 +0,0 @@
import { Tooltip } from '@vegaprotocol/ui-toolkit';
import classNames from 'classnames';
import type { HTMLProps, ReactNode } from 'react';
export const Card = ({
children,
title,
className,
loading = false,
highlight = false,
}: {
children: ReactNode;
title: string;
className?: string;
loading?: boolean;
highlight?: boolean;
}) => {
return (
<div
className={classNames(
'bg-vega-clight-800 dark:bg-vega-cdark-800 col-span-full p-0.5 lg:col-auto',
'rounded-lg',
{
'bg-rainbow': highlight,
},
className
)}
>
<div className="bg-vega-clight-800 dark:bg-vega-cdark-800 h-full w-full rounded p-4">
<h2 className="mb-3">{title}</h2>
{loading ? <CardLoader /> : children}
</div>
</div>
);
};
export const CardLoader = () => {
return (
<div className="flex flex-col gap-2">
<div className="bg-vega-clight-600 dark:bg-vega-cdark-600 h-5 w-full" />
<div className="bg-vega-clight-600 dark:bg-vega-cdark-600 h-6 w-3/4" />
</div>
);
};
export const CardStat = ({
value,
text,
highlight,
description,
testId,
}: {
value: ReactNode;
text?: string;
highlight?: boolean;
description?: ReactNode;
testId?: string;
}) => {
const val = (
<span
className={classNames('inline-block text-3xl leading-none', {
'bg-rainbow bg-clip-text text-transparent': highlight,
'cursor-help': description,
})}
data-testid={testId}
>
{value}
</span>
);
return (
<p className="leading-none">
{description ? <Tooltip description={description}>{val}</Tooltip> : val}
{text && (
<small className="text-muted mt-0.5 block text-xs">{text}</small>
)}
</p>
);
};
export const CardTable = (props: HTMLProps<HTMLTableElement>) => {
return (
<table {...props} className="text-muted mt-0.5 w-full text-xs">
<tbody>{props.children}</tbody>
</table>
);
};
export const CardTableTH = (props: HTMLProps<HTMLTableHeaderCellElement>) => {
return (
<th
{...props}
className={classNames('text-left font-normal', props.className)}
/>
);
};
export const CardTableTD = (props: HTMLProps<HTMLTableCellElement>) => {
return (
<td {...props} className={classNames('text-right', props.className)} />
);
};
-1
View File
@@ -1 +0,0 @@
export { Card, CardStat, CardTable, CardTableTH, CardTableTD } from './card';
@@ -1,12 +1,11 @@
import { Splash } from '@vegaprotocol/ui-toolkit';
import { DepositsTable } from '@vegaprotocol/deposits';
import { depositsProvider } from '@vegaprotocol/deposits';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useT } from '../../lib/use-t';
export const DepositsContainer = () => {
const t = useT();
const { pubKey } = useVegaWallet();
const { data, error } = useDataProvider({
dataProvider: depositsProvider,
@@ -1,10 +1,9 @@
import { t } from '@vegaprotocol/i18n';
import { TradingButton } from '@vegaprotocol/ui-toolkit';
import { ViewType, useSidebar } from '../sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const DepositsMenu = () => {
const t = useT();
const currentRouteId = useGetCurrentRouteId();
const setViews = useSidebar((store) => store.setViews);
@@ -0,0 +1,36 @@
import classNames from 'classnames';
import type { ReactNode } from 'react';
export const FeeCard = ({
children,
title,
className,
loading = false,
}: {
children: ReactNode;
title: string;
className?: string;
loading?: boolean;
}) => {
return (
<div
className={classNames(
'p-4 bg-vega-clight-800 dark:bg-vega-cdark-800 col-span-full lg:col-auto',
'rounded-lg',
className
)}
>
<h2 className="mb-3">{title}</h2>
{loading ? <FeeCardLoader /> : children}
</div>
);
};
export const FeeCardLoader = () => {
return (
<div className="flex flex-col gap-2">
<div className="w-full h-5 bg-vega-clight-600 dark:bg-vega-cdark-600" />
<div className="w-3/4 h-6 bg-vega-clight-600 dark:bg-vega-cdark-600" />
</div>
);
};
@@ -1,5 +1,6 @@
import maxBy from 'lodash/maxBy';
import minBy from 'lodash/minBy';
import { t } from '@vegaprotocol/i18n';
import { useVegaWallet } from '@vegaprotocol/wallet';
import {
useNetworkParams,
@@ -8,8 +9,9 @@ import {
import { useMarketList } from '@vegaprotocol/markets';
import { formatNumber, formatNumberRounded } from '@vegaprotocol/utils';
import { useDiscountProgramsQuery, useFeesQuery } from './__generated__/Fees';
import { Card, CardStat, CardTable, CardTableTD, CardTableTH } from '../card';
import { FeeCard } from './fees-card';
import { MarketFees } from './market-fees';
import { Stat } from './stat';
import { useVolumeStats } from './use-volume-stats';
import { useReferralStats } from './use-referral-stats';
import { formatPercentage, getAdjustedFee } from './utils';
@@ -23,10 +25,8 @@ import {
VegaIconNames,
truncateMiddle,
} from '@vegaprotocol/ui-toolkit';
import { useT } from '../../lib/use-t';
export const FeesContainer = () => {
const t = useT();
const { pubKey } = useVegaWallet();
const { params, loading: paramsLoading } = useNetworkParams([
NetworkParams.market_fee_factors_makerFee,
@@ -87,7 +87,7 @@ export const FeesContainer = () => {
<div className="grid auto-rows-min grid-cols-4 gap-3">
{isConnected && (
<>
<Card
<FeeCard
title={t('My trading fees')}
className="sm:col-span-2"
loading={loading}
@@ -98,8 +98,8 @@ export const FeesContainer = () => {
referralDiscount={referralDiscount}
volumeDiscount={volumeDiscount}
/>
</Card>
<Card
</FeeCard>
<FeeCard
title={t('Total discount')}
className="sm:col-span-2"
loading={loading}
@@ -110,8 +110,8 @@ export const FeesContainer = () => {
isReferralProgramRunning={isReferralProgramRunning}
isVolumeDiscountProgramRunning={isVolumeDiscountProgramRunning}
/>
</Card>
<Card
</FeeCard>
<FeeCard
title={t('My current volume')}
className="sm:col-span-2"
loading={loading}
@@ -124,12 +124,12 @@ export const FeesContainer = () => {
windowLength={volumeDiscountWindowLength}
/>
) : (
<p className="text-muted pt-3 text-sm">
<p className="pt-3 text-sm text-muted">
{t('No volume discount program active')}
</p>
)}
</Card>
<Card
</FeeCard>
<FeeCard
title={t('Referral benefits')}
className="sm:col-span-2"
loading={loading}
@@ -143,14 +143,14 @@ export const FeesContainer = () => {
epochs={referralDiscountWindowLength}
/>
) : (
<p className="text-muted pt-3 text-sm">
<p className="pt-3 text-sm text-muted">
{t('No referral program active')}
</p>
)}
</Card>
</FeeCard>
</>
)}
<Card
<FeeCard
title={t('Volume discount')}
className="lg:col-span-full xl:col-span-2"
loading={loading}
@@ -161,8 +161,8 @@ export const FeesContainer = () => {
lastEpochVolume={volumeInWindow}
windowLength={volumeDiscountWindowLength}
/>
</Card>
<Card
</FeeCard>
<FeeCard
title={t('Referral discount')}
className="lg:col-span-full xl:col-span-2"
loading={loading}
@@ -173,8 +173,8 @@ export const FeesContainer = () => {
epochsInSet={epochsInSet}
referralVolumeInWindow={referralVolumeInWindow}
/>
</Card>
<Card
</FeeCard>
<FeeCard
title={t('Fees by market')}
className="lg:col-span-full"
loading={marketsLoading}
@@ -184,7 +184,7 @@ export const FeesContainer = () => {
referralDiscount={referralDiscount}
volumeDiscount={volumeDiscount}
/>
</Card>
</FeeCard>
</div>
);
};
@@ -203,7 +203,6 @@ export const TradingFees = ({
referralDiscount: number;
volumeDiscount: number;
}) => {
const t = useT();
const referralDiscountBigNum = new BigNumber(referralDiscount);
const volumeDiscountBigNum = new BigNumber(volumeDiscount);
@@ -245,8 +244,8 @@ export const TradingFees = ({
}
return (
<div className="pt-4">
<div className="leading-none">
<div>
<div className="pt-6 leading-none">
<p className="block text-3xl leading-none" data-testid="adjusted-fees">
{minAdjustedTotal !== undefined && maxAdjustedTotal !== undefined
? `${formatPercentage(minAdjustedTotal)}%-${formatPercentage(
@@ -254,43 +253,47 @@ export const TradingFees = ({
)}%`
: `${formatPercentage(adjustedTotal)}%`}
</p>
<CardTable>
<tr className="text-default">
<CardTableTH>{t('Total fee before discount')}</CardTableTH>
<CardTableTD>
{minTotal !== undefined && maxTotal !== undefined
? `${formatPercentage(minTotal.toNumber())}%-${formatPercentage(
maxTotal.toNumber()
)}%`
: `${formatPercentage(total.toNumber())}%`}
</CardTableTD>
</tr>
<tr>
<CardTableTH>{t('Infrastructure')}</CardTableTH>
<CardTableTD>
{formatPercentage(
Number(params.market_fee_factors_infrastructureFee)
)}
%
</CardTableTD>
</tr>
<tr>
<CardTableTH>{t('Maker')}</CardTableTH>
<CardTableTD>
{formatPercentage(Number(params.market_fee_factors_makerFee))}%
</CardTableTD>
</tr>
{minLiq && maxLiq && (
<table className="w-full mt-0.5 text-xs text-muted">
<tbody>
<tr>
<CardTableTH>{t('Liquidity')}</CardTableTH>
<CardTableTD>
{formatPercentage(Number(minLiq.fees.factors.liquidityFee))}%
{'-'}
{formatPercentage(Number(maxLiq.fees.factors.liquidityFee))}%
</CardTableTD>
<th className="font-normal text-left text-default">
{t('Total fee before discount')}
</th>
<td className="text-right text-default">
{minTotal !== undefined && maxTotal !== undefined
? `${formatPercentage(
minTotal.toNumber()
)}%-${formatPercentage(maxTotal.toNumber())}%`
: `${formatPercentage(total.toNumber())}%`}
</td>
</tr>
)}
</CardTable>
<tr>
<th className="font-normal text-left">{t('Infrastructure')}</th>
<td className="text-right">
{formatPercentage(
Number(params.market_fee_factors_infrastructureFee)
)}
%
</td>
</tr>
<tr>
<th className="font-normal text-left ">{t('Maker')}</th>
<td className="text-right">
{formatPercentage(Number(params.market_fee_factors_makerFee))}%
</td>
</tr>
{minLiq && maxLiq && (
<tr>
<th className="font-normal text-left ">{t('Liquidity')}</th>
<td className="text-right">
{formatPercentage(Number(minLiq.fees.factors.liquidityFee))}%
{'-'}
{formatPercentage(Number(maxLiq.fees.factors.liquidityFee))}%
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
@@ -307,20 +310,19 @@ export const CurrentVolume = ({
windowLengthVolume: number;
windowLength: number;
}) => {
const t = useT();
const nextTier = tiers[tierIndex + 1];
const requiredForNextTier = nextTier
? Number(nextTier.minimumRunningNotionalTakerVolume) - windowLengthVolume
: 0;
return (
<div className="flex flex-col gap-3 pt-4">
<CardStat
<div>
<Stat
value={formatNumberRounded(new BigNumber(windowLengthVolume))}
text={t('Past {{count}} epochs', { count: windowLength })}
text={t('Past %s epochs', windowLength.toString())}
/>
{requiredForNextTier > 0 && (
<CardStat
<Stat
value={formatNumber(requiredForNextTier)}
text={t('Required for next tier')}
/>
@@ -338,17 +340,17 @@ const ReferralBenefits = ({
setRunningNotionalTakerVolume: number;
epochs: number;
}) => {
const t = useT();
return (
<div className="flex flex-col gap-3 pt-4">
<CardStat
<div>
<Stat
// all sets volume (not just current party)
value={formatNumber(setRunningNotionalTakerVolume)}
text={t('Combined running notional over the {{count}} epochs', {
count: epochs,
})}
text={t(
'Combined running notional over the %s epochs',
epochs.toString()
)}
/>
<CardStat value={epochsInSet} text={t('epochs in referral set')} />
<Stat value={epochsInSet} text={t('epochs in referral set')} />
</div>
);
};
@@ -364,7 +366,6 @@ const TotalDiscount = ({
isReferralProgramRunning: boolean;
isVolumeDiscountProgramRunning: boolean;
}) => {
const t = useT();
const totalDiscount = 1 - (1 - volumeDiscount) * (1 - referralDiscount);
const totalDiscountDescription = t(
'The total discount is calculated according to the following formula: '
@@ -376,8 +377,8 @@ const TotalDiscount = ({
);
return (
<div className="pt-4">
<CardStat
<div>
<Stat
description={
<>
{totalDiscountDescription}
@@ -387,36 +388,38 @@ const TotalDiscount = ({
value={formatPercentage(totalDiscount) + '%'}
highlight={true}
/>
<CardTable>
<tr>
<CardTableTH>{t('Volume discount')}</CardTableTH>
<CardTableTD>
{formatPercentage(volumeDiscount)}%
{!isVolumeDiscountProgramRunning && (
<Tooltip description={t('No active volume discount programme')}>
<span className="cursor-help">
{' '}
<VegaIcon name={VegaIconNames.INFO} size={12} />
</span>
</Tooltip>
)}
</CardTableTD>
</tr>
<tr>
<CardTableTH>{t('Referral discount')}</CardTableTH>
<CardTableTD>
{formatPercentage(referralDiscount)}%
{!isReferralProgramRunning && (
<Tooltip description={t('No active referral programme')}>
<span className="cursor-help">
{' '}
<VegaIcon name={VegaIconNames.INFO} size={12} />
</span>
</Tooltip>
)}
</CardTableTD>
</tr>
</CardTable>
<table className="w-full mt-0.5 text-xs text-muted">
<tbody>
<tr>
<th className="font-normal text-left">{t('Volume discount')}</th>
<td className="text-right">
{formatPercentage(volumeDiscount)}%
{!isVolumeDiscountProgramRunning && (
<Tooltip description={t('No active volume discount programme')}>
<span className="cursor-help">
{' '}
<VegaIcon name={VegaIconNames.INFO} size={12} />
</span>
</Tooltip>
)}
</td>
</tr>
<tr>
<th className="font-normal text-left ">{t('Referral discount')}</th>
<td className="text-right">
{formatPercentage(referralDiscount)}%
{!isReferralProgramRunning && (
<Tooltip description={t('No active referral programme')}>
<span className="cursor-help">
{' '}
<VegaIcon name={VegaIconNames.INFO} size={12} />
</span>
</Tooltip>
)}
</td>
</tr>
</tbody>
</table>
</div>
);
};
@@ -435,10 +438,9 @@ const VolumeTiers = ({
lastEpochVolume: number;
windowLength: number;
}) => {
const t = useT();
if (!tiers.length) {
return (
<p className="text-muted text-sm">
<p className="text-sm text-muted">
{t('No volume discount program active')}
</p>
);
@@ -452,9 +454,7 @@ const VolumeTiers = ({
<Th>{t('Tier')}</Th>
<Th>{t('Discount')}</Th>
<Th>{t('Min. trading volume')}</Th>
<Th>
{t('My volume (last {{count}} epochs)', { count: windowLength })}
</Th>
<Th>{t('My volume (last %s epochs)', windowLength.toString())}</Th>
<Th />
</tr>
</THead>
@@ -499,11 +499,9 @@ const ReferralTiers = ({
epochsInSet: number;
referralVolumeInWindow: number;
}) => {
const t = useT();
if (!tiers.length) {
return (
<p className="text-muted text-sm">{t('No referral program active')}</p>
<p className="text-sm text-muted">{t('No referral program active')}</p>
);
}
@@ -558,43 +556,37 @@ const ReferralTiers = ({
};
const YourTier = () => {
const t = useT();
return (
<span className="bg-rainbow whitespace-nowrap rounded-xl px-4 py-1.5 text-white">
<span className="px-4 py-1.5 rounded-xl bg-rainbow whitespace-nowrap text-white">
{t('Your tier')}
</span>
);
};
const ReferrerInfo = ({ code }: { code?: string }) => {
const t = useT();
return (
<div className="text-vega-clight-200 dark:vega-cdark-200 pt-3 text-sm">
<p className="mb-1">
{t('Connected key is owner of the referral set')}
{code && (
<>
{' '}
<span className="bg-rainbow bg-clip-text text-transparent">
{truncateMiddle(code)}
</span>
</>
)}
{'. '}
{t('As owner, it is eligible for commission not fee discounts.')}
</p>
<p>
{t('See')}{' '}
<Link
className="text-black underline dark:text-white"
to={Links.REFERRALS()}
>
{t('Referrals')}
</Link>{' '}
{t('for more information.')}
</p>
</div>
);
};
const ReferrerInfo = ({ code }: { code?: string }) => (
<div className="pt-3 text-sm text-vega-clight-200 dark:vega-cdark-200">
<p className="mb-1">
{t('Connected key is owner of the referral set')}
{code && (
<>
{' '}
<span className="text-transparent bg-rainbow bg-clip-text">
{truncateMiddle(code)}
</span>
</>
)}
{'. '}
{t('As owner, it is eligible for commission not fee discounts.')}
</p>
<p>
{t('See')}{' '}
<Link
className="underline text-black dark:text-white"
to={Links.REFERRALS()}
>
{t('Referrals')}
</Link>{' '}
{t('for more information.')}
</p>
</div>
);
@@ -1,45 +1,38 @@
import compact from 'lodash/compact';
import type { MarketMaybeWithDataAndCandles } from '@vegaprotocol/markets';
import { AgGrid } from '@vegaprotocol/datagrid';
import { t } from '@vegaprotocol/i18n';
import { formatPercentage, getAdjustedFee } from './utils';
import { MarketCodeCell } from '../../client-pages/markets/market-code-cell';
import BigNumber from 'bignumber.js';
import { useNavigateWithMeta } from '../../lib/hooks/use-market-click-handler';
import { Links } from '../../lib/links';
import { useT } from '../../lib/use-t';
import { useMemo } from 'react';
const useFeesTableColumnDefs = () => {
const t = useT();
return useMemo(
() => [
{ field: 'code', cellRenderer: 'MarketCodeCell' },
{
field: 'feeAfterDiscount',
headerName: t('Total fee after discount'),
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'infraFee',
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'makerFee',
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'liquidityFee',
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'totalFee',
headerName: t('Total fee before discount'),
valueFormatter: ({ value }: { value: number }) => value + '%',
},
],
[t]
);
};
const feesTableColumnDefs = [
{ field: 'code', cellRenderer: 'MarketCodeCell' },
{
field: 'feeAfterDiscount',
headerName: t('Total fee after discount'),
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'infraFee',
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'makerFee',
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'liquidityFee',
valueFormatter: ({ value }: { value: number }) => value + '%',
},
{
field: 'totalFee',
headerName: t('Total fee before discount'),
valueFormatter: ({ value }: { value: number }) => value + '%',
},
];
const feesTableDefaultColDef = {
flex: 1,
@@ -90,7 +83,7 @@ export const MarketFees = ({
return (
<div className="border rounded-sm border-default">
<AgGrid
columnDefs={useFeesTableColumnDefs()}
columnDefs={feesTableColumnDefs}
rowData={rows}
getRowId={({ data }) => data.id}
defaultColDef={feesTableDefaultColDef}
@@ -0,0 +1,34 @@
import { Tooltip } from '@vegaprotocol/ui-toolkit';
import classNames from 'classnames';
import type { ReactNode } from 'react';
export const Stat = ({
value,
text,
highlight,
description,
}: {
value: string | number;
text?: string;
highlight?: boolean;
description?: ReactNode;
}) => {
const val = (
<span
className={classNames('inline-block text-3xl leading-none', {
'text-transparent bg-rainbow bg-clip-text': highlight,
'cursor-help': description,
})}
>
{value}
</span>
);
return (
<p className="pt-3 leading-none first:pt-6">
{description ? <Tooltip description={description}>{val}</Tooltip> : val}
{text && (
<small className="block mt-0.5 text-xs text-muted">{text}</small>
)}
</p>
);
};
@@ -3,14 +3,13 @@ import { FillsManager } from '@vegaprotocol/fills';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { useDataGridEvents } from '@vegaprotocol/datagrid';
import { t } from '@vegaprotocol/i18n';
import { Splash } from '@vegaprotocol/ui-toolkit';
import type { DataGridSlice } from '../../stores/datagrid-store-slice';
import { createDataGridSlice } from '../../stores/datagrid-store-slice';
import { useMarketClickHandler } from '../../lib/hooks/use-market-click-handler';
import { useT } from '../../lib/use-t';
export const FillsContainer = () => {
const t = useT();
const onMarketClick = useMarketClickHandler(true);
const { pubKey } = useVegaWallet();
@@ -6,9 +6,9 @@ import 'pennant/dist/style.css';
import { useFundingPeriodsQuery } from '@vegaprotocol/markets';
import { LineChart } from 'pennant';
import { useMemo } from 'react';
import { t } from '@vegaprotocol/i18n';
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { useT } from '../../lib/use-t';
const calculateStartDate = (range: string): string | undefined => {
const now = new Date();
@@ -41,7 +41,6 @@ const DateRange = {
};
export const FundingContainer = ({ marketId }: { marketId: string }) => {
const t = useT();
const { theme } = useThemeSwitcher();
const variables = useMemo(
() => ({
@@ -74,7 +73,7 @@ export const FundingContainer = ({ marketId }: { marketId: string }) => {
cols: ['Date', t('Funding rate')],
rows: sortBy(rows, 'endTime').map((d) => [d.endTime, d.fundingRate]),
};
}, [data?.fundingPeriods.edges, t]);
}, [data?.fundingPeriods.edges]);
if (!data || !values?.rows.length) {
return <Splash> {t('No funding history data')}</Splash>;
}
@@ -3,18 +3,17 @@ import { FundingPaymentsManager } from '@vegaprotocol/funding-payments';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { useDataGridEvents } from '@vegaprotocol/datagrid';
import { t } from '@vegaprotocol/i18n';
import { Splash } from '@vegaprotocol/ui-toolkit';
import type { DataGridSlice } from '../../stores/datagrid-store-slice';
import { createDataGridSlice } from '../../stores/datagrid-store-slice';
import { useMarketClickHandler } from '../../lib/hooks/use-market-click-handler';
import { useT } from '../../lib/use-t';
export const FundingPaymentsContainer = ({
marketId,
}: {
marketId?: string;
}) => {
const t = useT();
const onMarketClick = useMarketClickHandler(true);
const { pubKey } = useVegaWallet();
@@ -1,13 +1,12 @@
import { t } from '@vegaprotocol/i18n';
import { LedgerExportForm } from '@vegaprotocol/ledger';
import { Loader, Splash } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useEnvironment } from '@vegaprotocol/environment';
import type { PartyAssetFieldsFragment } from '@vegaprotocol/assets';
import { usePartyAssetsQuery } from '@vegaprotocol/assets';
import { useT } from '../../lib/use-t';
export const LedgerContainer = () => {
const t = useT();
const VEGA_URL = useEnvironment((store) => store.VEGA_URL);
const { pubKey } = useVegaWallet();
const { data, loading } = usePartyAssetsQuery({
@@ -1,5 +1,6 @@
import { useDataProvider } from '@vegaprotocol/data-provider';
import { useDataGridEvents } from '@vegaprotocol/datagrid';
import { t } from '@vegaprotocol/i18n';
import {
lpAggregatedDataProvider,
type Filter,
@@ -16,7 +17,6 @@ import { createDataGridSlice } from '../../stores/datagrid-store-slice';
import { useEffect } from 'react';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { useT } from '../../lib/use-t';
export const LiquidityContainer = ({
marketId,
@@ -25,7 +25,6 @@ export const LiquidityContainer = ({
marketId: string | undefined;
filter?: Filter;
}) => {
const t = useT();
const gridStore = useLiquidityStore((store) => store.gridStore);
const updateGridStore = useLiquidityStore((store) => store.updateGridStore);
@@ -9,6 +9,7 @@ import {
addDecimalsFormatNumber,
formatNumberPercentage,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
CopyWithTooltip,
ExternalLink,
@@ -23,10 +24,8 @@ import {
usePaidFeesQuery,
} from '@vegaprotocol/liquidity';
import { useParams } from 'react-router-dom';
import { useT } from '../../lib/use-t';
export const LiquidityHeader = () => {
const t = useT();
const { marketId } = useParams();
const { data: market } = useMarket(marketId);
const { data: marketData } = useStaticMarketData(marketId);
@@ -61,9 +60,10 @@ export const LiquidityHeader = () => {
marketId && (
<HeaderTitle>
{market.tradableInstrument.instrument.code &&
t('{{instrumentCode}} liquidity provision', {
instrumentCode: market.tradableInstrument.instrument.code,
})}
t(
'%s liquidity provision',
market.tradableInstrument.instrument.code
)}
</HeaderTitle>
)
}
@@ -102,8 +102,8 @@ export const LiquidityHeader = () => {
<HeaderStat
heading={t('Fees paid')}
description={t(
'The amount of fees paid to liquidity providers across the whole market during the last epoch {{epoch}}.',
{ epoch: feesObject?.node.epoch.toString() || '-' }
'The amount of fees paid to liquidity providers across the whole market during the last epoch %s.',
feesObject?.node.epoch.toString() || '-'
)}
testId="fees-paid"
>
@@ -21,10 +21,10 @@ import {
addDecimalsFormatNumberQuantum,
formatNumberPercentage,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { DocsLinks } from '@vegaprotocol/environment';
import { Link } from 'react-router-dom';
import { Links } from '../../lib/links';
import { useT } from '../../lib/use-t';
interface Props {
marketId?: string;
@@ -39,7 +39,6 @@ export const MarketLiquiditySupplied = ({
noUpdate = false,
quantum,
}: Props) => {
const t = useT();
const [market, setMarket] = useState<MarketData>();
const { params } = useNetworkParams([
NetworkParams.market_liquidity_stakeToCcyVolume,
@@ -132,9 +132,7 @@ describe('MarketSuccessorBanner', () => {
wrapper: MockedProvider,
});
expect(
screen.getByText('has a 24h trading volume of 101.367', {
exact: false,
})
screen.getByText('has a 24h trading volume of 101.367')
).toBeInTheDocument();
});
@@ -17,9 +17,8 @@ import {
getMarketExpiryDate,
isNumeric,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import * as Types from '@vegaprotocol/types';
import { useT, ns } from '../../lib/use-t';
import { Trans } from 'react-i18next';
const getExpiryDate = (tags: string[], close?: string): Date | null => {
const expiryDate = getMarketExpiryDate(tags);
@@ -31,7 +30,6 @@ export const MarketSuccessorBanner = ({
}: {
market: Market | null;
}) => {
const t = useT();
const { data: marketState } = useMarketState(market?.id);
const isSettled = marketState === Types.MarketState.STATE_SETTLED;
const { data: successorData, loading } = useSuccessorMarket(market?.id);
@@ -83,8 +81,8 @@ export const MarketSuccessorBanner = ({
<div className="mt-1">
{duration && (
<span>
{t('This market expires in {{duration}}.', {
duration: formatDuration(duration, {
{t('This market expires in %s.', [
formatDuration(duration, {
format: [
'years',
'months',
@@ -94,46 +92,22 @@ export const MarketSuccessorBanner = ({
'minutes',
],
}),
})}
])}
</span>
)}
{successorData && (
<>
{' '}
{successorVolume ? (
<Trans
defaults="The successor market <0>{{instrumentName}}</0> has a 24h trading volume of {{successorVolume}}"
values={{
successorVolume,
instrumentName:
successorData?.tradableInstrument.instrument.name,
}}
components={[
<ExternalLink
href={`/#/markets/${successorData?.id}`}
key="link"
>
successor market name
</ExternalLink>,
]}
/>
) : (
<Trans
defaults="The successor market is <0>{{instrumentName}}</0>"
values={{
instrumentName:
successorData?.tradableInstrument.instrument.name,
}}
components={[
<ExternalLink
href={`/#/markets/${successorData?.id}`}
key="link"
>
successor market name
</ExternalLink>,
]}
ns={ns}
/>
{t('The successor market')}
{!successorVolume ? ' is ' : ' '}
<ExternalLink href={`/#/markets/${successorData?.id}`}>
{successorData?.tradableInstrument.instrument.name}
</ExternalLink>
{successorVolume && (
<span>
{' '}
{t('has a 24h trading volume of %s', [successorVolume])}
</span>
)}
</>
)}
@@ -9,17 +9,16 @@ import {
Intent,
NotificationBanner,
} from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
import { DApp, TOKEN_PROPOSAL, useLinks } from '@vegaprotocol/environment';
import * as Types from '@vegaprotocol/types';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { useT } from '../../lib/use-t';
export const MarketSuccessorProposalBanner = ({
marketId,
}: {
marketId?: string;
}) => {
const t = useT();
const { data: proposals } = useDataProvider({
dataProvider: marketViewProposalsDataProvider,
skip: !marketId,
@@ -58,13 +57,9 @@ export const MarketSuccessorProposalBanner = ({
: t('Successors to this market have been proposed')}
</div>
<div>
{t(
'checkOutProposalsAndVote',
'Check out the terms of the proposals and vote:',
{
count: successors.length,
}
)}{' '}
{successors.length === 1
? t('Check out the terms of the proposal and vote:')
: t('Check out the terms of the proposals and vote:')}{' '}
{successors.map((item, i) => {
const externalLink = tokenLink(
TOKEN_PROPOSAL.replace(':id', item.id || '')
@@ -8,6 +8,7 @@ import {
} from '@vegaprotocol/ui-toolkit';
import type { MarketViewProposalFieldsFragment } from '@vegaprotocol/proposals';
import { marketViewProposalsDataProvider } from '@vegaprotocol/proposals';
import { t } from '@vegaprotocol/i18n';
import * as Types from '@vegaprotocol/types';
import type { Market } from '@vegaprotocol/markets';
import { getQuoteName } from '@vegaprotocol/markets';
@@ -20,7 +21,6 @@ import {
useLinks,
} from '@vegaprotocol/environment';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { useT } from '../../lib/use-t';
const filterProposals = (
data: MarketViewProposalFieldsFragment[] | null,
@@ -68,7 +68,6 @@ export const MarketTerminationBanner = ({
}: {
market: Market | null;
}) => {
const t = useT();
const [visible, setVisible] = useState(true);
const skip = !market || !visible;
const { data: passedProposalsData } = useDataProvider({
@@ -114,22 +113,19 @@ export const MarketTerminationBanner = ({
content = (
<>
<div className="uppercase mb-1">
{t('Trading on Market {{name}} will stop on {{date}}', {
name,
date,
})}
{t('Trading on Market %s will stop on %s', [name, date])}
</div>
<div>
{t(
'You will no longer be able to hold a position on this market when it closes in {{duration}}.',
{ duration }
'You will no longer be able to hold a position on this market when it closes in %s.',
[duration]
)}{' '}
{price &&
assetSymbol &&
t('The final price will be {{price}} {{assetSymbol}}.', {
price: addDecimalsFormatNumber(price, market.decimalPlaces),
t('The final price will be %s %s.', [
addDecimalsFormatNumber(price, market.decimalPlaces),
assetSymbol,
})}
])}
</div>
</>
);
@@ -138,8 +134,8 @@ export const MarketTerminationBanner = ({
<>
<div className="uppercase mb-1">
{t(
'Trading on Market {{name}} may stop. There are open proposals to close this market',
{ name }
'Trading on Market %s may stop. There are open proposals to close this market',
[name]
)}
</div>
<div>
@@ -155,17 +151,17 @@ export const MarketTerminationBanner = ({
<>
<div className="uppercase mb-1">
{t(
'Trading on Market {{name}} may stop on {{date}}. There is open proposal to close this market.',
{ name, date }
'Trading on Market %s may stop on %s. There is open proposal to close this market.',
[name, date]
)}
</div>
<div>
{price &&
assetSymbol &&
t('Proposed final price is {{price}} {{assetSymbol}}.', {
price: addDecimalsFormatNumber(price, market.decimalPlaces),
t('Proposed final price is %s %s.', [
addDecimalsFormatNumber(price, market.decimalPlaces),
assetSymbol,
})}
])}
</div>
<div>
<ExternalLink href={proposalLink}>{t('View proposal')}</ExternalLink>
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import {
TradingDropdown,
TradingDropdownCheckboxItem,
@@ -6,7 +7,6 @@ import {
TradingDropdownTrigger,
} from '@vegaprotocol/ui-toolkit';
import { MarketSelectorButton } from './market-selector-button';
import { useT } from '../../lib/use-t';
type Assets = Array<{ id: string; symbol: string }>;
@@ -19,7 +19,6 @@ export const AssetDropdown = ({
checkedAssets: string[];
onSelect: (id: string, checked: boolean) => void;
}) => {
const t = useT();
if (!assets?.length) {
return null;
}
@@ -30,7 +29,7 @@ export const AssetDropdown = ({
trigger={
<TradingDropdownTrigger data-testid="asset-trigger">
<MarketSelectorButton>
{triggerText({ assets, checkedAssets }, t)}
{triggerText({ assets, checkedAssets })}
</MarketSelectorButton>
</TradingDropdownTrigger>
}
@@ -59,16 +58,13 @@ export const AssetDropdown = ({
);
};
const triggerText = (
{
assets,
checkedAssets,
}: {
assets: Assets;
checkedAssets: string[];
},
t: ReturnType<typeof useT>
) => {
const triggerText = ({
assets,
checkedAssets,
}: {
assets: Assets;
checkedAssets: string[];
}) => {
let text = t('Assets');
if (checkedAssets.length === 1) {
@@ -76,9 +72,7 @@ const triggerText = (
const asset = assets.find((a) => a.id === assetId);
text = asset ? asset.symbol : t('Asset (1)');
} else if (checkedAssets.length > 1) {
text = t('{{checkedAssets}} Assets', {
checkedAssets: checkedAssets.length,
});
text = t(`${checkedAssets.length} Assets`);
}
return text;
@@ -11,8 +11,8 @@ import {
MarketTradingMode,
MarketTradingModeMapping,
} from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
import { MarketProductPill } from '@vegaprotocol/datagrid';
import { useT } from '../../lib/use-t';
export const MarketSelectorItem = ({
market,
@@ -52,7 +52,6 @@ const MarketData = ({
market: MarketMaybeWithDataAndCandles;
allProducts: boolean;
}) => {
const t = useT();
const { data } = useMarketDataUpdateSubscription({
variables: {
marketId: market.id,
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import uniqBy from 'lodash/uniqBy';
import {
getAsset,
@@ -20,7 +21,6 @@ import type { SortType } from './sort-dropdown';
import { Sort, SortDropdown } from './sort-dropdown';
import { MarketSelectorItem } from './market-selector-item';
import classNames from 'classnames';
import { useT } from '../../lib/use-t';
export type Filter = {
searchTerm: string;
@@ -40,7 +40,6 @@ export const MarketSelector = ({
currentMarketId?: string;
onSelect: (marketId: string) => void;
}) => {
const t = useT();
const [filter, setFilter] = useState<Filter>({
searchTerm: '',
product: Product.All,
@@ -159,7 +158,6 @@ const MarketList = ({
noItems: string;
allProducts: boolean;
}) => {
const t = useT();
const itemSize = 45;
const listRef = useRef<HTMLDivElement | null>(null);
const rect = listRef.current?.getBoundingClientRect();
@@ -1,8 +1,8 @@
import classNames from 'classnames';
import { Link } from 'react-router-dom';
import { t } from '@vegaprotocol/i18n';
import { VegaIcon, VegaIconNames } from '@vegaprotocol/ui-toolkit';
import { Links } from '../../lib/links';
import { useT } from '../../lib/use-t';
// Make sure these match the available __typename properties on product
export const Product = {
@@ -14,6 +14,15 @@ export const Product = {
export type ProductType = keyof typeof Product;
const ProductTypeMapping: {
[key in ProductType]: string;
} = {
[Product.All]: 'All',
[Product.Future]: 'Futures',
[Product.Spot]: 'Spot',
[Product.Perpetual]: 'Perpetuals',
};
export const ProductSelector = ({
product,
onSelect,
@@ -21,15 +30,6 @@ export const ProductSelector = ({
product: ProductType;
onSelect: (product: ProductType) => void;
}) => {
const t = useT();
const ProductTypeMapping: {
[key in ProductType]: string;
} = {
[Product.All]: t('All'),
[Product.Future]: t('Futures'),
[Product.Spot]: t('Spot'),
[Product.Perpetual]: t('Perpetuals'),
};
return (
<div className="flex mb-2">
{Object.keys(Product).map((t) => {
@@ -1,6 +1,7 @@
import throttle from 'lodash/throttle';
import type { MarketData, Market } from '@vegaprotocol/markets';
import { marketDataProvider } from '@vegaprotocol/markets';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import * as Schema from '@vegaprotocol/types';
import { HeaderStat } from '../header';
@@ -8,10 +9,8 @@ import { useCallback, useRef, useState } from 'react';
import * as constants from '../constants';
import { DocsLinks } from '@vegaprotocol/environment';
import { ExternalLink } from '@vegaprotocol/ui-toolkit';
import { useT } from '../../lib/use-t';
export const MarketState = ({ market }: { market: Market | null }) => {
const t = useT();
const [marketState, setMarketState] = useState<Schema.MarketState | null>(
null
);
@@ -42,7 +41,7 @@ export const MarketState = ({ market }: { market: Market | null }) => {
return (
<HeaderStat
heading={t('Status')}
description={useGetMarketStateTooltip(marketState)}
description={getMarketStateTooltip(marketState)}
testId="market-state"
>
{marketState ? Schema.MarketStateMapping[marketState] : '-'}
@@ -50,8 +49,7 @@ export const MarketState = ({ market }: { market: Market | null }) => {
);
};
const useGetMarketStateTooltip = (state: Schema.MarketState | null) => {
const t = useT();
const getMarketStateTooltip = (state: Schema.MarketState | null) => {
if (state === Schema.MarketState.STATE_ACTIVE) {
return t('Enactment date reached and usual auction exit checks pass');
}
@@ -98,7 +96,7 @@ const useGetMarketStateTooltip = (state: Schema.MarketState | null) => {
return (
<p>
{t(
'This market has been suspended via a governance vote and can be resumed or terminated by further votes.'
`This market has been suspended via a governance vote and can be resumed or terminated by further votes.`
)}
{DocsLinks && (
<ExternalLink href={DocsLinks.MARKET_LIFECYCLE} className="ml-1">
@@ -1,11 +1,11 @@
import type { RefObject } from 'react';
import { t } from '@vegaprotocol/i18n';
import { TradingModeTooltip } from '@vegaprotocol/deal-ticket';
import { useInView } from 'react-intersection-observer';
import * as Schema from '@vegaprotocol/types';
import { HeaderStat } from '../header';
import { Tooltip } from '@vegaprotocol/ui-toolkit';
import { useStaticMarketData } from '@vegaprotocol/markets';
import { useT } from '../../lib/use-t';
const getTradingModeLabel = (
marketTradingMode?: Schema.MarketTradingMode,
@@ -36,7 +36,6 @@ export const HeaderStatMarketTradingMode = ({
initialTradingMode,
initialTrigger,
}: HeaderStatMarketTradingModeProps) => {
const t = useT();
const { data } = useStaticMarketData(marketId);
const marketTradingMode = data?.marketTradingMode ?? initialTradingMode;
const trigger = data?.trigger ?? initialTrigger;
@@ -1,15 +1,14 @@
import { useCallback, useRef, useState } from 'react';
import throttle from 'lodash/throttle';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import type { MarketData } from '@vegaprotocol/markets';
import { marketDataProvider, marketProvider } from '@vegaprotocol/markets';
import { HeaderStat } from '../header';
import * as constants from '../constants';
import { useT } from '../../lib/use-t';
export const MarketVolume = ({ marketId }: { marketId: string }) => {
const t = useT();
const [marketVolume, setMarketVolume] = useState<string>('-');
const variables = { marketId };
const { data } = useDataProvider({
@@ -1,16 +1,15 @@
import { VegaIcon, VegaIconNames } from '@vegaprotocol/ui-toolkit';
import { MarketSelector } from '../market-selector';
import { useMarket, useMarketList } from '@vegaprotocol/markets';
import { t } from '@vegaprotocol/i18n';
import { useParams } from 'react-router-dom';
import * as PopoverPrimitive from '@radix-ui/react-popover';
import { useState } from 'react';
import { useT } from '../../lib/use-t';
/**
* This is only rendered for the mobile navigation
*/
export const NavHeader = () => {
const t = useT();
const { marketId } = useParams();
const { data } = useMarket(marketId);
const [open, setOpen] = useState(false);
@@ -68,7 +68,6 @@ describe('Navbar', () => {
['/portfolio', 'Portfolio'],
['/referrals', 'Referrals'],
['/fees', 'Fees'],
['/rewards', 'Rewards'],
[expect.stringContaining('governance'), 'Governance'],
];
@@ -103,7 +102,6 @@ describe('Navbar', () => {
['/portfolio', 'Portfolio'],
['/referrals', 'Referrals'],
['/fees', 'Fees'],
['/rewards', 'Rewards'],
[expect.stringContaining('governance'), 'Governance'],
];
const links = menu.getAllByRole('link');
+29 -28
View File
@@ -7,8 +7,8 @@ import {
DApp,
useLinks,
FLAGS,
useEnvNameMapping,
} from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { useGlobalStore } from '../../stores';
import { VegaWalletConnectButton } from '../vega-wallet-connect-button';
import { VegaIconNames, VegaIcon, VLogo } from '@vegaprotocol/ui-toolkit';
@@ -22,7 +22,6 @@ import { VegaWalletMenu } from '../vega-wallet';
import { useVegaWallet, useVegaWalletDialogStore } from '@vegaprotocol/wallet';
import { WalletIcon } from '../icons/wallet';
import { ProtocolUpgradeCountdown } from '@vegaprotocol/proposals';
import { useT } from '../../lib/use-t';
type MenuState = 'wallet' | 'nav' | null;
type Theme = 'system' | 'yellow';
@@ -34,7 +33,6 @@ export const Navbar = ({
children?: ReactNode;
theme?: Theme;
}) => {
const t = useT();
// menu state for small screens
const [menu, setMenu] = useState<MenuState>(null);
@@ -75,7 +73,7 @@ export const Navbar = ({
</div>
{/* Right section */}
<div className="ml-auto flex items-center justify-end gap-2">
<div className="flex items-center justify-end ml-auto gap-2">
<ProtocolUpgradeCountdown />
<NavbarMobileButton
onClick={() => {
@@ -109,18 +107,18 @@ export const Navbar = ({
onOpenChange={(open) => setMenu((x) => (open ? x : null))}
>
<D.Overlay
className="fixed inset-0 z-20 bg-black/50 dark:bg-black/80 lg:hidden"
className="fixed inset-0 z-20 lg:hidden dark:bg-black/80 bg-black/50"
data-testid="navbar-menu-overlay"
/>
<D.Content
className={classNames(
'lg:hidden',
'border-default bg-vega-clight-700 dark:bg-vega-cdark-700 fixed right-0 top-0 z-20 h-screen w-3/4 border-l',
'fixed top-0 right-0 z-20 w-3/4 h-screen border-l border-default bg-vega-clight-700 dark:bg-vega-cdark-700',
navTextClasses
)}
data-testid="navbar-menu-content"
>
<div className="flex h-10 items-center justify-end p-1">
<div className="flex items-center justify-end h-10 p-1">
<NavbarMobileButton onClick={() => setMenu(null)}>
<span className="sr-only">{t('Close menu')}</span>
<VegaIcon name={VegaIconNames.CROSS} size={24} />
@@ -140,13 +138,11 @@ export const Navbar = ({
* of the navigation
*/
const NavbarMenu = ({ onClick }: { onClick: () => void }) => {
const t = useT();
const envNameMapping = useEnvNameMapping();
const { VEGA_ENV, VEGA_NETWORKS, GITHUB_FEEDBACK_URL } = useEnvironment();
const marketId = useGlobalStore((store) => store.marketId);
return (
<div className="gap-3 lg:flex lg:h-full">
<div className="lg:flex lg:h-full gap-3">
<NavbarList>
<NavbarItem>
<NavbarTrigger data-testid="navbar-network-switcher-trigger">
@@ -196,11 +192,6 @@ const NavbarMenu = ({ onClick }: { onClick: () => void }) => {
{t('Fees')}
</NavbarLink>
</NavbarItem>
<NavbarItem>
<NavbarLink to={Links.REWARDS()} onClick={onClick}>
{t('Rewards')}
</NavbarLink>
</NavbarItem>
<NavbarItem>
<NavbarLinkExternal to={useLinks(DApp.Governance)()}>
{t('Governance')}
@@ -250,8 +241,8 @@ const NavbarTrigger = ({
onPointerMove={preventHover}
onPointerLeave={preventHover}
className={classNames(
'w-full lg:h-full lg:w-auto',
'flex items-center justify-between gap-2 px-6 py-2 lg:justify-center lg:p-0',
'w-full lg:w-auto lg:h-full',
'flex items-center justify-between lg:justify-center gap-2 px-6 py-2 lg:p-0',
'text-lg lg:text-sm',
'hover:text-vega-clight-100 dark:hover:text-vega-cdark-100'
)}
@@ -282,8 +273,8 @@ const NavbarLink = ({
to={to}
end={end}
className={classNames(
'block flex-col justify-center lg:flex lg:h-full',
'px-6 py-2 text-lg lg:p-0 lg:text-sm',
'block lg:flex lg:h-full flex-col justify-center',
'px-6 py-2 lg:p-0 text-lg lg:text-sm',
'hover:text-vega-clight-100 dark:hover:text-vega-cdark-100'
)}
onClick={onClick}
@@ -306,7 +297,7 @@ const NavbarLink = ({
</span>
<span
className={classNames(
'absolute bottom-0 left-0 hidden h-0 w-full lg:block',
'hidden lg:block absolute left-0 bottom-0 w-full h-0',
borderClasses
)}
/>
@@ -327,7 +318,7 @@ const NavbarSubItem = (props: LiHTMLAttributes<HTMLElement>) => {
};
const NavbarList = (props: N.NavigationMenuListProps) => {
return <N.List {...props} className="gap-6 lg:flex lg:h-full" />;
return <N.List {...props} className="lg:flex lg:h-full gap-6" />;
};
/**
@@ -338,10 +329,10 @@ const NavbarContent = (props: N.NavigationMenuContentProps) => {
<N.Content
{...props}
className={classNames(
'navbar-content group',
'z-20 pl-2 lg:absolute lg:mt-2 lg:min-w-[290px] lg:pl-0',
'group navbar-content',
'lg:absolute lg:mt-2 pl-2 lg:pl-0 z-20 lg:min-w-[290px]',
'lg:bg-vega-clight-700 lg:dark:bg-vega-cdark-700',
'border-vega-clight-500 dark:border-vega-cdark-500 lg:rounded lg:border'
'lg:border border-vega-clight-500 dark:border-vega-cdark-500 lg:rounded'
)}
onPointerEnter={preventHover}
onPointerLeave={preventHover}
@@ -366,8 +357,8 @@ const NavbarLinkExternal = ({
<NavLink
to={to}
className={classNames(
'flex items-center gap-2 lg:h-full',
'px-6 py-2 text-lg lg:p-0 lg:text-sm',
'flex gap-2 lg:h-full items-center',
'px-6 py-2 lg:p-0 text-lg lg:text-sm',
'hover:text-vega-clight-100 dark:hover:text-vega-cdark-100'
)}
onClick={onClick}
@@ -395,7 +386,7 @@ const BurgerIcon = () => (
const NavbarListDivider = () => {
return (
<div className="px-6 py-2 lg:px-0" role="separator">
<div className="bg-vega-clight-500 dark:bg-vega-cdark-500 h-px w-full lg:h-full lg:w-px" />
<div className="w-full h-px lg:h-full lg:w-px bg-vega-clight-500 dark:bg-vega-cdark-500" />
</div>
);
};
@@ -408,7 +399,7 @@ const NavbarMobileButton = (props: ButtonHTMLAttributes<HTMLButtonElement>) => {
<button
{...props}
className={classNames(
'flex h-8 w-8 items-center rounded p-1 lg:hidden ',
'w-8 h-8 lg:hidden flex items-center p-1 rounded ',
'hover:bg-vega-clight-500 dark:hover:bg-vega-cdark-500',
'hover:text-vega-clight-50 dark:hover:text-vega-cdark-50'
)}
@@ -416,6 +407,16 @@ const NavbarMobileButton = (props: ButtonHTMLAttributes<HTMLButtonElement>) => {
);
};
const envNameMapping: Record<Networks, string> = {
[Networks.VALIDATOR_TESTNET]: t('VALIDATOR_TESTNET'),
[Networks.CUSTOM]: t('Custom'),
[Networks.DEVNET]: t('Devnet'),
[Networks.STAGNET1]: t('Stagnet'),
[Networks.TESTNET]: t('Fairground testnet'),
[Networks.MAINNET_MIRROR]: t('Mirror'),
[Networks.MAINNET]: t('Mainnet'),
};
// https://github.com/radix-ui/primitives/issues/1630
// eslint-disable-next-line
const preventHover = (e: any) => {
@@ -3,12 +3,11 @@ import {
useNodeHealth,
useNodeSwitcherStore,
} from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { Indicator, ExternalLink } from '@vegaprotocol/ui-toolkit';
import { Tooltip } from '../../components/tooltip';
import { useT } from '../../lib/use-t';
export const NodeHealthContainer = () => {
const t = useT();
const { VEGA_URL, VEGA_INCIDENT_URL } = useEnvironment();
const setNodeSwitcher = useNodeSwitcherStore((store) => store.setDialogOpen);
const { text, intent, datanodeBlockHeight } = useNodeHealth();
@@ -58,7 +57,6 @@ interface NodeUrlProps {
}
export const NodeUrl = ({ url }: NodeUrlProps) => {
const t = useT();
const urlObj = new URL(url);
const nodeUrl = urlObj.hostname;
return <span title={t('Connected node')}>{nodeUrl}</span>;
@@ -1,5 +1,6 @@
import { useDataGridEvents } from '@vegaprotocol/datagrid';
import { Filter, OrderListManager } from '@vegaprotocol/orders';
import { t } from '@vegaprotocol/i18n';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useNavigateWithMeta } from '../../lib/hooks/use-market-click-handler';
@@ -8,12 +9,8 @@ import { persist } from 'zustand/middleware';
import type { DataGridStore } from '../../stores/datagrid-store-slice';
import { OrderStatus } from '@vegaprotocol/types';
import { Links } from '../../lib/links';
import { useT } from '../../lib/use-t';
const resolveNoRowsMessage = (
filter: Filter | undefined,
t: ReturnType<typeof useT>
) => {
const resolveNoRowsMessage = (filter?: Filter) => {
switch (filter) {
case Filter.Open:
return t('No open orders');
@@ -45,7 +42,6 @@ export interface OrderContainerProps {
const AUTO_SIZE_COLUMNS = ['instrument-code'];
export const OrdersContainer = ({ filter }: OrderContainerProps) => {
const t = useT();
const { pubKey, isReadOnly } = useVegaWallet();
const navigate = useNavigateWithMeta();
const { gridState, updateGridState } = useOrderListGridState(filter);
@@ -60,7 +56,7 @@ export const OrdersContainer = ({ filter }: OrderContainerProps) => {
if (!pubKey) {
return <Splash>{t('Please connect Vega wallet')}</Splash>;
}
const noRowsMessage = resolveNoRowsMessage(filter, t);
const noRowsMessage = resolveNoRowsMessage(filter);
return (
<OrderListManager
@@ -1,4 +1,5 @@
import { useDataGridEvents } from '@vegaprotocol/datagrid';
import { t } from '@vegaprotocol/i18n';
import { PositionsManager } from '@vegaprotocol/positions';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
@@ -8,12 +9,10 @@ import type { StateCreator } from 'zustand';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { useMarketClickHandler } from '../../lib/hooks/use-market-click-handler';
import { useT } from '../../lib/use-t';
const AUTO_SIZE_COLUMNS = ['marketCode'];
export const PositionsContainer = ({ allKeys }: { allKeys?: boolean }) => {
const t = useT();
const onMarketClick = useMarketClickHandler(true);
const { pubKey, pubKeys, isReadOnly } = useVegaWallet();
@@ -1,9 +1,8 @@
import { t } from '@vegaprotocol/i18n';
import { TradingButton } from '@vegaprotocol/ui-toolkit';
import { usePositionsStore } from '../positions-container';
import { useT } from '../../lib/use-t';
export const PositionsMenu = () => {
const t = useT();
const showClosed = usePositionsStore((store) => store.showClosedMarkets);
const toggle = usePositionsStore((store) => store.toggleClosedMarkets);
return (
@@ -1,94 +0,0 @@
query RewardsPage($partyId: ID!) {
party(id: $partyId) {
id
vestingStats {
# AKA hoarder reward multiplier
rewardBonusMultiplier
}
activityStreak {
# vesting multiplier
rewardVestingMultiplier
# AKA streak multiplier
rewardDistributionMultiplier
}
vestingBalancesSummary {
epoch
vestingBalances {
asset {
id
symbol
decimals
quantum
}
balance
}
lockedBalances {
asset {
id
symbol
decimals
quantum
}
balance
untilEpoch
}
}
}
}
query RewardsHistory(
$partyId: ID!
$epochRewardSummariesPagination: Pagination
$partyRewardsPagination: Pagination
$fromEpoch: Int
$toEpoch: Int
) {
epochRewardSummaries(
filter: { fromEpoch: $fromEpoch, toEpoch: $toEpoch }
pagination: $epochRewardSummariesPagination
) {
edges {
node {
epoch
assetId
amount
rewardType
}
}
}
party(id: $partyId) {
id
rewardsConnection(
fromEpoch: $fromEpoch
toEpoch: $toEpoch
pagination: $partyRewardsPagination
) {
edges {
node {
amount
percentageOfTotal
receivedAt
rewardType
asset {
id
symbol
name
decimals
}
party {
id
}
epoch {
id
}
}
}
}
}
}
query RewardsEpoch {
epoch {
id
}
}
@@ -1,205 +0,0 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type RewardsPageQueryVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
}>;
export type RewardsPageQuery = { __typename?: 'Query', party?: { __typename?: 'Party', id: string, vestingStats?: { __typename?: 'PartyVestingStats', rewardBonusMultiplier: string } | null, activityStreak?: { __typename?: 'PartyActivityStreak', rewardVestingMultiplier: string, rewardDistributionMultiplier: string } | null, vestingBalancesSummary: { __typename?: 'PartyVestingBalancesSummary', epoch?: number | null, vestingBalances?: Array<{ __typename?: 'PartyVestingBalance', balance: string, asset: { __typename?: 'Asset', id: string, symbol: string, decimals: number, quantum: string } }> | null, lockedBalances?: Array<{ __typename?: 'PartyLockedBalance', balance: string, untilEpoch: number, asset: { __typename?: 'Asset', id: string, symbol: string, decimals: number, quantum: string } }> | null } } | null };
export type RewardsHistoryQueryVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
epochRewardSummariesPagination?: Types.InputMaybe<Types.Pagination>;
partyRewardsPagination?: Types.InputMaybe<Types.Pagination>;
fromEpoch?: Types.InputMaybe<Types.Scalars['Int']>;
toEpoch?: Types.InputMaybe<Types.Scalars['Int']>;
}>;
export type RewardsHistoryQuery = { __typename?: 'Query', epochRewardSummaries?: { __typename?: 'EpochRewardSummaryConnection', edges?: Array<{ __typename?: 'EpochRewardSummaryEdge', node: { __typename?: 'EpochRewardSummary', epoch: number, assetId: string, amount: string, rewardType: Types.AccountType } } | null> | null } | null, party?: { __typename?: 'Party', id: string, rewardsConnection?: { __typename?: 'RewardsConnection', edges?: Array<{ __typename?: 'RewardEdge', node: { __typename?: 'Reward', amount: string, percentageOfTotal: string, receivedAt: any, rewardType: Types.AccountType, asset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, party: { __typename?: 'Party', id: string }, epoch: { __typename?: 'Epoch', id: string } } } | null> | null } | null } | null };
export type RewardsEpochQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type RewardsEpochQuery = { __typename?: 'Query', epoch: { __typename?: 'Epoch', id: string } };
export const RewardsPageDocument = gql`
query RewardsPage($partyId: ID!) {
party(id: $partyId) {
id
vestingStats {
rewardBonusMultiplier
}
activityStreak {
rewardVestingMultiplier
rewardDistributionMultiplier
}
vestingBalancesSummary {
epoch
vestingBalances {
asset {
id
symbol
decimals
quantum
}
balance
}
lockedBalances {
asset {
id
symbol
decimals
quantum
}
balance
untilEpoch
}
}
}
}
`;
/**
* __useRewardsPageQuery__
*
* To run a query within a React component, call `useRewardsPageQuery` and pass it any options that fit your needs.
* When your component renders, `useRewardsPageQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useRewardsPageQuery({
* variables: {
* partyId: // value for 'partyId'
* },
* });
*/
export function useRewardsPageQuery(baseOptions: Apollo.QueryHookOptions<RewardsPageQuery, RewardsPageQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<RewardsPageQuery, RewardsPageQueryVariables>(RewardsPageDocument, options);
}
export function useRewardsPageLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<RewardsPageQuery, RewardsPageQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<RewardsPageQuery, RewardsPageQueryVariables>(RewardsPageDocument, options);
}
export type RewardsPageQueryHookResult = ReturnType<typeof useRewardsPageQuery>;
export type RewardsPageLazyQueryHookResult = ReturnType<typeof useRewardsPageLazyQuery>;
export type RewardsPageQueryResult = Apollo.QueryResult<RewardsPageQuery, RewardsPageQueryVariables>;
export const RewardsHistoryDocument = gql`
query RewardsHistory($partyId: ID!, $epochRewardSummariesPagination: Pagination, $partyRewardsPagination: Pagination, $fromEpoch: Int, $toEpoch: Int) {
epochRewardSummaries(
filter: {fromEpoch: $fromEpoch, toEpoch: $toEpoch}
pagination: $epochRewardSummariesPagination
) {
edges {
node {
epoch
assetId
amount
rewardType
}
}
}
party(id: $partyId) {
id
rewardsConnection(
fromEpoch: $fromEpoch
toEpoch: $toEpoch
pagination: $partyRewardsPagination
) {
edges {
node {
amount
percentageOfTotal
receivedAt
rewardType
asset {
id
symbol
name
decimals
}
party {
id
}
epoch {
id
}
}
}
}
}
}
`;
/**
* __useRewardsHistoryQuery__
*
* To run a query within a React component, call `useRewardsHistoryQuery` and pass it any options that fit your needs.
* When your component renders, `useRewardsHistoryQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useRewardsHistoryQuery({
* variables: {
* partyId: // value for 'partyId'
* epochRewardSummariesPagination: // value for 'epochRewardSummariesPagination'
* partyRewardsPagination: // value for 'partyRewardsPagination'
* fromEpoch: // value for 'fromEpoch'
* toEpoch: // value for 'toEpoch'
* },
* });
*/
export function useRewardsHistoryQuery(baseOptions: Apollo.QueryHookOptions<RewardsHistoryQuery, RewardsHistoryQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<RewardsHistoryQuery, RewardsHistoryQueryVariables>(RewardsHistoryDocument, options);
}
export function useRewardsHistoryLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<RewardsHistoryQuery, RewardsHistoryQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<RewardsHistoryQuery, RewardsHistoryQueryVariables>(RewardsHistoryDocument, options);
}
export type RewardsHistoryQueryHookResult = ReturnType<typeof useRewardsHistoryQuery>;
export type RewardsHistoryLazyQueryHookResult = ReturnType<typeof useRewardsHistoryLazyQuery>;
export type RewardsHistoryQueryResult = Apollo.QueryResult<RewardsHistoryQuery, RewardsHistoryQueryVariables>;
export const RewardsEpochDocument = gql`
query RewardsEpoch {
epoch {
id
}
}
`;
/**
* __useRewardsEpochQuery__
*
* To run a query within a React component, call `useRewardsEpochQuery` and pass it any options that fit your needs.
* When your component renders, `useRewardsEpochQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useRewardsEpochQuery({
* variables: {
* },
* });
*/
export function useRewardsEpochQuery(baseOptions?: Apollo.QueryHookOptions<RewardsEpochQuery, RewardsEpochQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<RewardsEpochQuery, RewardsEpochQueryVariables>(RewardsEpochDocument, options);
}
export function useRewardsEpochLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<RewardsEpochQuery, RewardsEpochQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<RewardsEpochQuery, RewardsEpochQueryVariables>(RewardsEpochDocument, options);
}
export type RewardsEpochQueryHookResult = ReturnType<typeof useRewardsEpochQuery>;
export type RewardsEpochLazyQueryHookResult = ReturnType<typeof useRewardsEpochLazyQuery>;
export type RewardsEpochQueryResult = Apollo.QueryResult<RewardsEpochQuery, RewardsEpochQueryVariables>;
@@ -1 +0,0 @@
export { RewardsContainer } from './rewards-container';
@@ -1,215 +0,0 @@
import { render, screen } from '@testing-library/react';
import type { Account } from '@vegaprotocol/accounts';
import { AccountType, AssetStatus } from '@vegaprotocol/types';
import { MemoryRouter } from 'react-router-dom';
import {
RewardPot,
Vesting,
type RewardPotProps,
Multipliers,
} from './rewards-container';
const rewardAsset = {
id: 'asset-1',
symbol: 'ASSET 1',
name: 'Asset 1',
decimals: 2,
quantum: '1',
status: AssetStatus.STATUS_ENABLED,
source: {
__typename: 'ERC20' as const,
contractAddress: '0x123',
lifetimeLimit: '100',
withdrawThreshold: '100',
},
};
describe('RewardPot', () => {
const renderComponent = (props: RewardPotProps) => {
return render(
<MemoryRouter>
<RewardPot {...props} />
</MemoryRouter>
);
};
it('Shows no rewards message if no accounts or vesting balances provided', () => {
renderComponent({
pubKey: 'pubkey',
assetId: rewardAsset.id,
accounts: [],
vestingBalancesSummary: {
lockedBalances: [],
vestingBalances: [],
},
});
expect(screen.getByText(/No rewards/)).toBeInTheDocument();
});
it('Calculates all the rewards', () => {
const asset2 = {
id: 'asset-2',
symbol: 'ASSET 2',
name: 'Asset 2',
decimals: 0,
quantum: '1000000',
status: AssetStatus.STATUS_ENABLED,
source: {
__typename: 'ERC20' as const,
contractAddress: '0x123',
lifetimeLimit: '100',
withdrawThreshold: '100',
},
};
const accounts: Account[] = [
{
type: AccountType.ACCOUNT_TYPE_GENERAL,
balance: '100',
asset: rewardAsset,
},
{
type: AccountType.ACCOUNT_TYPE_VESTED_REWARDS,
balance: '100',
asset: rewardAsset,
},
{
type: AccountType.ACCOUNT_TYPE_VESTED_REWARDS,
balance: '50',
asset: rewardAsset,
},
{
type: AccountType.ACCOUNT_TYPE_VESTED_REWARDS,
balance: '500000',
asset: asset2,
},
{
type: AccountType.ACCOUNT_TYPE_VESTING_REWARDS, // should be ignored as its vesting
balance: '100',
asset: rewardAsset,
},
{
type: AccountType.ACCOUNT_TYPE_VESTING_REWARDS, // should be ignored
balance: '2000000',
asset: asset2,
},
];
const props = {
pubKey: 'pubkey',
assetId: rewardAsset.id,
accounts: accounts,
vestingBalancesSummary: {
epoch: 1,
lockedBalances: [
{
balance: '150',
asset: rewardAsset,
untilEpoch: 1,
},
{
balance: '100',
asset: rewardAsset,
untilEpoch: 1,
},
{
balance: '100',
asset: asset2, // should be ignored
untilEpoch: 1,
},
],
vestingBalances: [
{
balance: '250',
asset: rewardAsset,
},
{
balance: '200',
asset: rewardAsset,
},
{
balance: '100',
asset: asset2, // should be ignored
},
],
},
};
renderComponent(props);
expect(screen.getByTestId('total-rewards')).toHaveTextContent(
`7.00 ${rewardAsset.symbol}`
);
expect(screen.getByText(/Locked/).nextElementSibling).toHaveTextContent(
'2.50'
);
expect(screen.getByText(/Vesting/).nextElementSibling).toHaveTextContent(
'4.50'
);
expect(
screen.getByText(/Available to withdraw/).nextElementSibling
).toHaveTextContent('1.50');
});
});
describe('Vesting', () => {
it('renders vesting rates', () => {
render(<Vesting baseRate={'0.25'} pubKey="pubKey" multiplier="2" />);
expect(screen.getByTestId('vesting-rate')).toHaveTextContent('50%');
expect(screen.getByText('Base rate').nextElementSibling).toHaveTextContent(
'25%'
);
expect(
screen.getByText('Vesting multiplier').nextSibling
).toHaveTextContent('2x');
});
it('doesnt use multiplier if not connected', () => {
render(<Vesting baseRate={'0.25'} pubKey={null} multiplier={undefined} />);
expect(screen.getByTestId('vesting-rate')).toHaveTextContent('25%');
expect(screen.getByText('Base rate').nextElementSibling).toHaveTextContent(
'25%'
);
expect(screen.queryByText('Vesting multiplier')).not.toBeInTheDocument();
});
});
describe('Multipliers', () => {
it('shows combined multipliers', () => {
render(
<Multipliers pubKey="pubkey" streakMultiplier="3" hoarderMultiplier="2" />
);
expect(screen.getByTestId('combined-multipliers')).toHaveTextContent('6x');
expect(
screen.getByText('Streak reward multiplier').nextElementSibling
).toHaveTextContent('3x');
expect(
screen.getByText('Hoarder reward multiplier').nextElementSibling
).toHaveTextContent('2x');
});
it('shows not connected state', () => {
render(
<Multipliers pubKey={null} streakMultiplier="3" hoarderMultiplier="2" />
);
expect(
screen.queryByTestId('combined-multipliers')
).not.toBeInTheDocument();
expect(
screen.queryByText('Streak reward multiplier')
).not.toBeInTheDocument();
expect(
screen.queryByText('Hoarder reward multiplier')
).not.toBeInTheDocument();
expect(screen.getByText('Not connected')).toBeInTheDocument();
});
});
@@ -1,375 +0,0 @@
import groupBy from 'lodash/groupBy';
import type { Account } from '@vegaprotocol/accounts';
import { useAccounts } from '@vegaprotocol/accounts';
import { t } from '@vegaprotocol/i18n';
import {
NetworkParams,
useNetworkParams,
} from '@vegaprotocol/network-parameters';
import { AccountType } from '@vegaprotocol/types';
import { useVegaWallet } from '@vegaprotocol/wallet';
import BigNumber from 'bignumber.js';
import {
Card,
CardStat,
CardTable,
CardTableTD,
CardTableTH,
} from '../card/card';
import {
type RewardsPageQuery,
useRewardsPageQuery,
useRewardsEpochQuery,
} from './__generated__/Rewards';
import {
TradingButton,
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { formatPercentage } from '../fees-container/utils';
import { addDecimalsFormatNumberQuantum } from '@vegaprotocol/utils';
import { ViewType, useSidebar } from '../sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { RewardsHistoryContainer } from './rewards-history';
export const RewardsContainer = () => {
const { pubKey } = useVegaWallet();
const { params, loading: paramsLoading } = useNetworkParams([
NetworkParams.reward_asset,
NetworkParams.rewards_activityStreak_benefitTiers,
NetworkParams.rewards_vesting_baseRate,
]);
const { data: accounts, loading: accountsLoading } = useAccounts(pubKey);
const { data: epochData } = useRewardsEpochQuery();
// No need to specify the fromEpoch as it will by default give you the last
const { data: rewardsData, loading: rewardsLoading } = useRewardsPageQuery({
variables: {
partyId: pubKey || '',
},
});
if (!epochData?.epoch) return null;
const loading = paramsLoading || accountsLoading || rewardsLoading;
const rewardAccounts = accounts
? accounts.filter((a) =>
[
AccountType.ACCOUNT_TYPE_VESTED_REWARDS,
AccountType.ACCOUNT_TYPE_VESTING_REWARDS,
].includes(a.type)
)
: [];
const rewardAssetsMap = groupBy(
rewardAccounts.filter((a) => a.asset.id !== params.reward_asset),
'asset.id'
);
return (
<div className="grid auto-rows-min grid-cols-6 gap-3">
{/* Always show reward information for vega */}
<Card
key={params.reward_asset}
title={t('Vega Reward pot')}
className="lg:col-span-3 xl:col-span-2"
loading={loading}
highlight={true}
>
<RewardPot
pubKey={pubKey}
accounts={accounts}
assetId={params.reward_asset}
vestingBalancesSummary={rewardsData?.party?.vestingBalancesSummary}
/>
</Card>
<Card
title={t('Vesting')}
className="lg:col-span-3 xl:col-span-2"
loading={loading}
>
<Vesting
pubKey={pubKey}
baseRate={params.rewards_vesting_baseRate}
multiplier={
rewardsData?.party?.activityStreak?.rewardVestingMultiplier
}
/>
</Card>
<Card
title={t('Rewards multipliers')}
className="lg:col-span-3 xl:col-span-2"
loading={loading}
highlight={true}
>
<Multipliers
pubKey={pubKey}
hoarderMultiplier={
rewardsData?.party?.vestingStats?.rewardBonusMultiplier
}
streakMultiplier={
rewardsData?.party?.activityStreak?.rewardDistributionMultiplier
}
/>
</Card>
{/* Show all other reward pots, most of the time users will not have other rewards */}
{Object.keys(rewardAssetsMap).map((assetId) => {
const asset = rewardAssetsMap[assetId][0].asset;
return (
<Card
key={assetId}
title={t('%s Reward pot', asset.symbol)}
className="lg:col-span-3 xl:col-span-2"
loading={loading}
>
<RewardPot
pubKey={pubKey}
accounts={accounts}
assetId={assetId}
vestingBalancesSummary={
rewardsData?.party?.vestingBalancesSummary
}
/>
</Card>
);
})}
<Card
title={t('Rewards history')}
className="lg:col-span-full"
loading={rewardsLoading}
>
<RewardsHistoryContainer
epoch={Number(epochData?.epoch.id)}
pubKey={pubKey}
/>
</Card>
</div>
);
};
type VestingBalances = NonNullable<
RewardsPageQuery['party']
>['vestingBalancesSummary'];
export type RewardPotProps = {
pubKey: string | null;
accounts: Account[] | null;
assetId: string; // VEGA
vestingBalancesSummary: VestingBalances | undefined;
};
export const RewardPot = ({
pubKey,
accounts,
assetId,
vestingBalancesSummary,
}: RewardPotProps) => {
// TODO: Opening the sidebar for the first time works, but then clicking on redeem
// for a different asset does not update the form
const currentRouteId = useGetCurrentRouteId();
const setViews = useSidebar((store) => store.setViews);
// All vested rewards accounts
const availableRewardAssetAccounts = accounts
? accounts.filter((a) => {
return (
a.asset.id === assetId &&
a.type === AccountType.ACCOUNT_TYPE_VESTED_REWARDS
);
})
: [];
// Sum of all vested reward account balances
const totalVestedRewardsByRewardAsset = BigNumber.sum.apply(
null,
availableRewardAssetAccounts.length
? availableRewardAssetAccounts.map((a) => a.balance)
: [0]
);
const lockedEntries = vestingBalancesSummary?.lockedBalances?.filter(
(b) => b.asset.id === assetId
);
const lockedBalances = lockedEntries?.length
? lockedEntries.map((e) => e.balance)
: [0];
const totalLocked = BigNumber.sum.apply(null, lockedBalances);
const vestingEntries = vestingBalancesSummary?.vestingBalances?.filter(
(b) => b.asset.id === assetId
);
const vestingBalances = vestingEntries?.length
? vestingEntries.map((e) => e.balance)
: [0];
const totalVesting = BigNumber.sum.apply(null, vestingBalances);
const totalRewards = totalLocked.plus(totalVesting);
let rewardAsset = undefined;
if (availableRewardAssetAccounts.length) {
rewardAsset = availableRewardAssetAccounts[0].asset;
} else if (lockedEntries?.length) {
rewardAsset = lockedEntries[0].asset;
} else if (vestingEntries?.length) {
rewardAsset = vestingEntries[0].asset;
}
if (!pubKey) {
return (
<div className="pt-4">
<p className="text-muted text-sm">{t('Not connected')}</p>
</div>
);
}
return (
<div className="pt-4">
{rewardAsset ? (
<>
<CardStat
value={`${addDecimalsFormatNumberQuantum(
totalRewards.toString(),
rewardAsset.decimals,
rewardAsset.quantum
)} ${rewardAsset.symbol}`}
testId="total-rewards"
/>
<div className="flex flex-col gap-4">
<CardTable>
<tr>
<CardTableTH className="flex items-center gap-1">
{t(`Locked ${rewardAsset.symbol}`)}
<VegaIcon name={VegaIconNames.LOCK} size={12} />
</CardTableTH>
<CardTableTD>
{addDecimalsFormatNumberQuantum(
totalLocked.toString(),
rewardAsset.decimals,
rewardAsset.quantum
)}
</CardTableTD>
</tr>
<tr>
<CardTableTH>{t(`Vesting ${rewardAsset.symbol}`)}</CardTableTH>
<CardTableTD>
{addDecimalsFormatNumberQuantum(
totalVesting.toString(),
rewardAsset.decimals,
rewardAsset.quantum
)}
</CardTableTD>
</tr>
<tr>
<CardTableTH>
{t('Available to withdraw this epoch')}
</CardTableTH>
<CardTableTD>
{addDecimalsFormatNumberQuantum(
totalVestedRewardsByRewardAsset.toString(),
rewardAsset.decimals,
rewardAsset.quantum
)}
</CardTableTD>
</tr>
</CardTable>
{totalVestedRewardsByRewardAsset.isGreaterThan(0) && (
<div>
<TradingButton
onClick={() =>
setViews(
{ type: ViewType.Transfer, assetId },
currentRouteId
)
}
size="small"
>
{t('Redeem rewards')}
</TradingButton>
</div>
)}
</div>
</>
) : (
<p className="text-muted text-sm">{t('No rewards')}</p>
)}
</div>
);
};
export const Vesting = ({
pubKey,
baseRate,
multiplier = '1',
}: {
pubKey: string | null;
baseRate: string;
multiplier?: string;
}) => {
const rate = new BigNumber(baseRate).times(multiplier);
const rateFormatted = formatPercentage(Number(rate));
const baseRateFormatted = formatPercentage(Number(baseRate));
return (
<div className="pt-4">
<CardStat value={rateFormatted + '%'} testId="vesting-rate" />
<CardTable>
<tr>
<CardTableTH>{t('Base rate')}</CardTableTH>
<CardTableTD>{baseRateFormatted}%</CardTableTD>
</tr>
{pubKey && (
<tr>
<CardTableTH>{t('Vesting multiplier')}</CardTableTH>
<CardTableTD>{multiplier}x</CardTableTD>
</tr>
)}
</CardTable>
</div>
);
};
export const Multipliers = ({
pubKey,
streakMultiplier = '1',
hoarderMultiplier = '1',
}: {
pubKey: string | null;
streakMultiplier?: string;
hoarderMultiplier?: string;
}) => {
const combinedMultiplier = new BigNumber(streakMultiplier).times(
hoarderMultiplier
);
if (!pubKey) {
return (
<div className="pt-4">
<p className="text-muted text-sm">{t('Not connected')}</p>
</div>
);
}
return (
<div className="pt-4">
<CardStat
value={combinedMultiplier.toString() + 'x'}
testId="combined-multipliers"
highlight={true}
/>
<CardTable>
<tr>
<CardTableTH>{t('Streak reward multiplier')}</CardTableTH>
<CardTableTD>{streakMultiplier}x</CardTableTD>
</tr>
<tr>
<CardTableTH>{t('Hoarder reward multiplier')}</CardTableTH>
<CardTableTD>{hoarderMultiplier}x</CardTableTD>
</tr>
</CardTable>
</div>
);
};
@@ -1,194 +0,0 @@
import groupBy from 'lodash/groupBy';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { RewardHistoryTable } from './rewards-history';
import { AccountType, AssetStatus } from '@vegaprotocol/types';
import { type AssetFieldsFragment } from '@vegaprotocol/assets';
const assets: Record<string, AssetFieldsFragment> = {
asset1: {
id: 'asset1',
name: 'Asset 1',
status: AssetStatus.STATUS_ENABLED,
symbol: 'A ASSET',
decimals: 0,
quantum: '1',
// @ts-ignore not needed
source: {},
},
asset2: {
id: 'asset2',
name: 'Asset 2',
status: AssetStatus.STATUS_ENABLED,
symbol: 'B ASSET',
decimals: 0,
quantum: '1',
// @ts-ignore not needed
source: {},
},
};
const rewardSummaries = [
{
node: {
epoch: 9,
assetId: assets.asset1.id,
amount: '60',
rewardType: AccountType.ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES,
},
},
{
node: {
epoch: 8,
assetId: assets.asset1.id,
amount: '20',
rewardType: AccountType.ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES,
},
},
{
node: {
epoch: 8,
assetId: assets.asset1.id,
amount: '20',
rewardType: AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION,
},
},
{
node: {
epoch: 7,
assetId: assets.asset2.id,
amount: '300',
rewardType: AccountType.ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS,
},
},
];
const getCell = (cells: HTMLElement[], colId: string) => {
return within(
cells.find((c) => c.getAttribute('col-id') === colId) as HTMLElement
);
};
describe('RewarsHistoryTable', () => {
const props = {
epochRewardSummaries: {
edges: rewardSummaries,
},
partyRewards: {
edges: [],
},
assets,
pubKey: 'pubkey',
epoch: 10,
epochVariables: {
from: 1,
to: 10,
},
onEpochChange: jest.fn(),
loading: false,
};
it('Renders table with accounts summed up by asset', () => {
render(<RewardHistoryTable {...props} />);
const container = within(
document.querySelector('.ag-center-cols-container') as HTMLElement
);
const rows = container.getAllByRole('row');
expect(rows).toHaveLength(
Object.keys(groupBy(rewardSummaries, 'node.assetId')).length
);
let row = within(rows[0]);
let cells = row.getAllByRole('gridcell');
let assetCell = getCell(cells, 'asset.symbol');
expect(assetCell.getByTestId('stack-cell-primary')).toHaveTextContent(
assets.asset2.symbol
);
expect(assetCell.getByTestId('stack-cell-secondary')).toHaveTextContent(
assets.asset2.name
);
const marketCreationCell = getCell(cells, 'marketCreation');
expect(
marketCreationCell.getByTestId('stack-cell-primary')
).toHaveTextContent('300');
expect(
marketCreationCell.getByTestId('stack-cell-secondary')
).toHaveTextContent('100.00%');
let totalCell = getCell(cells, 'total');
expect(totalCell.getByText('300.00')).toBeInTheDocument();
row = within(rows[1]);
cells = row.getAllByRole('gridcell');
assetCell = getCell(cells, 'asset.symbol');
expect(assetCell.getByTestId('stack-cell-primary')).toHaveTextContent(
assets.asset1.symbol
);
expect(assetCell.getByTestId('stack-cell-secondary')).toHaveTextContent(
assets.asset1.name
);
// check cells are summed and percentage of totals are shown
const priceTakingCell = getCell(cells, 'priceTaking');
expect(priceTakingCell.getByTestId('stack-cell-primary')).toHaveTextContent(
'80'
);
expect(
priceTakingCell.getByTestId('stack-cell-secondary')
).toHaveTextContent('80.00%');
const avgPositionCell = getCell(cells, 'averagePosition');
expect(avgPositionCell.getByTestId('stack-cell-primary')).toHaveTextContent(
'20'
);
expect(
avgPositionCell.getByTestId('stack-cell-secondary')
).toHaveTextContent('20.00%');
totalCell = getCell(cells, 'total');
expect(totalCell.getByText('100.00')).toBeInTheDocument();
});
it('changes epochs using pagination', async () => {
const epochVariables = {
from: 3,
to: 4,
};
const onEpochChange = jest.fn();
render(
<RewardHistoryTable
{...props}
epoch={5}
epochVariables={epochVariables}
onEpochChange={onEpochChange}
/>
);
const fromInput = screen.getByLabelText('From epoch');
const toInput = screen.getByLabelText('to');
expect(fromInput).toHaveValue(epochVariables.from);
expect(toInput).toHaveValue(epochVariables.to);
const buttons = within(screen.getByTestId('fromEpoch')).getAllByRole(
'button'
);
const fromInc = buttons[0];
const decInc = buttons[1];
await userEvent.click(fromInc);
expect(onEpochChange).toHaveBeenCalledWith({ from: 4, to: 4 });
await userEvent.click(decInc);
expect(onEpochChange).toHaveBeenCalledWith({ from: 2, to: 4 });
onEpochChange.mockClear();
await userEvent.type(fromInput, '1');
// no state control so typing will just append to whats there
expect(onEpochChange).toHaveBeenCalledWith({ from: 31, to: 4 });
});
});
@@ -1,391 +0,0 @@
import debounce from 'lodash/debounce';
import { useMemo, useState } from 'react';
import BigNumber from 'bignumber.js';
import type { ColDef, ValueFormatterFunc } from 'ag-grid-community';
import {
useAssetsMapProvider,
type AssetFieldsFragment,
} from '@vegaprotocol/assets';
import {
addDecimalsFormatNumberQuantum,
formatNumberPercentage,
} from '@vegaprotocol/utils';
import { AgGrid, StackedCell } from '@vegaprotocol/datagrid';
import {
TradingButton,
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
import {
useRewardsHistoryQuery,
type RewardsHistoryQuery,
} from './__generated__/Rewards';
import { useRewardsRowData } from './use-reward-row-data';
export const RewardsHistoryContainer = ({
epoch,
pubKey,
}: {
pubKey: string | null;
epoch: number;
}) => {
const [epochVariables, setEpochVariables] = useState(() => ({
from: epoch - 1,
to: epoch,
}));
const { data: assets } = useAssetsMapProvider();
// No need to specify the fromEpoch as it will by default give you the last
const { refetch, data, loading } = useRewardsHistoryQuery({
variables: {
partyId: pubKey || '',
fromEpoch: epochVariables.from,
toEpoch: epochVariables.to,
},
});
const debouncedRefetch = useMemo(
() => debounce((variables) => refetch(variables), 800),
[refetch]
);
const handleEpochChange = (incoming: { from: number; to: number }) => {
if (!Number.isInteger(incoming.from) || !Number.isInteger(incoming.to)) {
return;
}
if (incoming.from > incoming.to) {
return;
}
// Must be at least the first epoch
if (incoming.from < 0 || incoming.to < 0) {
return;
}
if (incoming.from > epoch || incoming.to > epoch) {
return;
}
setEpochVariables({
from: incoming.from,
to: Math.min(incoming.to, epoch),
});
debouncedRefetch({
partyId: pubKey || '',
fromEpoch: incoming.from,
toEpoch: incoming.to,
});
};
return (
<RewardHistoryTable
pubKey={pubKey}
epochRewardSummaries={data?.epochRewardSummaries}
partyRewards={data?.party?.rewardsConnection}
onEpochChange={handleEpochChange}
epoch={epoch}
epochVariables={epochVariables}
assets={assets}
loading={loading}
/>
);
};
const defaultColDef = {
flex: 1,
resizable: true,
sortable: true,
};
interface RewardRow {
asset: AssetFieldsFragment;
staking: number;
priceTaking: number;
priceMaking: number;
liquidityProvision: number;
marketCreation: number;
averagePosition: number;
relativeReturns: number;
returnsVolatility: number;
validatorRanking: number;
total: number;
}
export type PartyRewardsConnection = NonNullable<
RewardsHistoryQuery['party']
>['rewardsConnection'];
export const RewardHistoryTable = ({
epochRewardSummaries,
partyRewards,
assets,
pubKey,
epochVariables,
epoch,
onEpochChange,
loading,
}: {
epochRewardSummaries: RewardsHistoryQuery['epochRewardSummaries'];
partyRewards: PartyRewardsConnection;
assets: Record<string, AssetFieldsFragment> | null;
pubKey: string | null;
epoch: number;
epochVariables: {
from: number;
to: number;
};
onEpochChange: (epochVariables: { from: number; to: number }) => void;
loading: boolean;
}) => {
const [isParty, setIsParty] = useState(false);
const rowData = useRewardsRowData({
epochRewardSummaries,
partyRewards,
assets,
partyId: isParty ? pubKey : null,
});
const columnDefs = useMemo<ColDef<RewardRow>[]>(() => {
const rewardValueFormatter: ValueFormatterFunc<RewardRow> = ({
data,
value,
}) => {
if (!value || !data) {
return '-';
}
return addDecimalsFormatNumberQuantum(
value,
data.asset.decimals,
data.asset.quantum
);
};
const rewardCellRenderer = ({
data,
value,
valueFormatted,
}: {
data: RewardRow;
value: number;
valueFormatted: string;
}) => {
if (!value || value <= 0 || !data) {
return <span className="text-muted">-</span>;
}
const pctOfTotal = new BigNumber(value).dividedBy(data.total).times(100);
return (
<StackedCell
primary={valueFormatted}
secondary={formatNumberPercentage(pctOfTotal, 2)}
/>
);
};
const colDefs: ColDef[] = [
{
field: 'asset.symbol',
cellRenderer: ({ value, data }: { value: string; data: RewardRow }) => {
if (!value || !data) return <span>-</span>;
return <StackedCell primary={value} secondary={data.asset.name} />;
},
sort: 'desc',
},
{
field: 'staking',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'priceTaking',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'priceMaking',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'liquidityProvision',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'marketCreation',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'averagePosition',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'relativeReturns',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'returnsVolatility',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'validatorRanking',
valueFormatter: rewardValueFormatter,
cellRenderer: rewardCellRenderer,
},
{
field: 'total',
type: 'rightAligned',
valueFormatter: rewardValueFormatter,
},
];
return colDefs;
}, []);
return (
<div>
<div className="mb-2 flex items-center justify-between gap-2">
<h4 className="text-muted flex items-center gap-2 text-sm">
<label htmlFor="fromEpoch">{t('From epoch')}</label>
<EpochInput
id="fromEpoch"
value={epochVariables.from}
max={epochVariables.to}
onChange={(value) =>
onEpochChange({
from: value,
to: epochVariables.to,
})
}
onIncrement={() =>
onEpochChange({
from: epochVariables.from + 1,
to: epochVariables.to,
})
}
onDecrement={() =>
onEpochChange({
from: epochVariables.from - 1,
to: epochVariables.to,
})
}
/>
<label htmlFor="toEpoch">{t('to')}</label>
<EpochInput
id="toEpoch"
value={epochVariables.to}
max={epoch}
onChange={(value) =>
onEpochChange({
from: epochVariables.from,
to: value,
})
}
onIncrement={() =>
onEpochChange({
from: epochVariables.from,
to: epochVariables.to + 1,
})
}
onDecrement={() =>
onEpochChange({
from: epochVariables.from,
to: epochVariables.to - 1,
})
}
/>
</h4>
<div className="flex gap-0.5">
<TradingButton
onClick={() => setIsParty(false)}
size="extra-small"
minimal={isParty}
>
{t('Total distributed')}
</TradingButton>
<TradingButton
onClick={() => setIsParty(true)}
size="extra-small"
disabled={!pubKey}
minimal={!isParty}
>
{t('Earned by me')}
</TradingButton>
</div>
</div>
<AgGrid
columnDefs={columnDefs}
defaultColDef={defaultColDef}
rowData={rowData}
rowHeight={45}
domLayout="autoHeight"
// Show loading message without wiping out the current rows
overlayNoRowsTemplate={loading ? t('Loading...') : t('No rows')}
/>
</div>
);
};
const EpochInput = ({
id,
value,
max,
min = 1,
step = 1,
onChange,
onIncrement,
onDecrement,
}: {
id: string;
value: number;
max?: number;
min?: number;
step?: number;
onChange: (value: number) => void;
onIncrement: () => void;
onDecrement: () => void;
}) => {
return (
<span className="flex gap-0.5" data-testid={id}>
<span className="bg-vega-clight-600 dark:bg-vega-cdark-600 relative rounded-l-sm">
<span className="px-2 opacity-0">{value}</span>
<input
onChange={(e) => onChange(Number(e.target.value))}
value={value}
className="dark:focus:bg-vega-cdark-700 absolute left-0 top-0 h-full w-full appearance-none bg-transparent px-2 focus:outline-none"
type="number"
step={step}
min={min}
max={max}
id={id}
name={id}
/>
</span>
<span className="flex flex-col gap-0.5 overflow-hidden rounded-r-sm">
<button
onClick={onIncrement}
className="bg-vega-clight-600 dark:bg-vega-cdark-600 flex flex-1 items-center px-1"
>
<VegaIcon name={VegaIconNames.CHEVRON_UP} size={12} />
</button>
<button
onClick={onDecrement}
className="bg-vega-clight-600 dark:bg-vega-cdark-600 flex flex-1 items-center px-1"
>
<VegaIcon name={VegaIconNames.CHEVRON_DOWN} size={12} />
</button>
</span>
</span>
);
};
@@ -1,109 +0,0 @@
import groupBy from 'lodash/groupBy';
import { AccountType } from '@vegaprotocol/types';
import BigNumber from 'bignumber.js';
import { removePaginationWrapper } from '@vegaprotocol/utils';
import { type Asset } from '@vegaprotocol/assets';
import { type PartyRewardsConnection } from './rewards-history';
import { type RewardsHistoryQuery } from './__generated__/Rewards';
const REWARD_ACCOUNT_TYPES = [
AccountType.ACCOUNT_TYPE_GLOBAL_REWARD,
AccountType.ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES,
AccountType.ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES,
AccountType.ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES,
AccountType.ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS,
AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION,
AccountType.ACCOUNT_TYPE_REWARD_RELATIVE_RETURN,
AccountType.ACCOUNT_TYPE_REWARD_RETURN_VOLATILITY,
AccountType.ACCOUNT_TYPE_REWARD_VALIDATOR_RANKING,
];
const getRewards = (
rewards: Array<{
rewardType: AccountType;
assetId: string;
amount: string;
}>,
assets: Record<string, Asset> | null
) => {
const assetMap = groupBy(
rewards.filter((r) => REWARD_ACCOUNT_TYPES.includes(r.rewardType)),
'assetId'
);
return Object.keys(assetMap).map((assetId) => {
const r = assetMap[assetId];
const asset = assets ? assets[assetId] : undefined;
const totals = new Map<AccountType, number>();
REWARD_ACCOUNT_TYPES.forEach((type) => {
const amountsByType = r
.filter((a) => a.rewardType === type)
.map((a) => a.amount);
const typeTotal = BigNumber.sum.apply(
null,
amountsByType.length ? amountsByType : [0]
);
totals.set(type, typeTotal.toNumber());
});
const total = BigNumber.sum.apply(
null,
Array.from(totals).map((entry) => entry[1])
);
return {
asset,
staking: totals.get(AccountType.ACCOUNT_TYPE_GLOBAL_REWARD),
priceTaking: totals.get(AccountType.ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES),
priceMaking: totals.get(
AccountType.ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES
),
liquidityProvision: totals.get(
AccountType.ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES
),
marketCreation: totals.get(
AccountType.ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS
),
averagePosition: totals.get(
AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION
),
relativeReturns: totals.get(
AccountType.ACCOUNT_TYPE_REWARD_RELATIVE_RETURN
),
returnsVolatility: totals.get(
AccountType.ACCOUNT_TYPE_REWARD_RETURN_VOLATILITY
),
validatorRanking: totals.get(
AccountType.ACCOUNT_TYPE_REWARD_VALIDATOR_RANKING
),
total: total.toNumber(),
};
});
};
export const useRewardsRowData = ({
partyRewards,
epochRewardSummaries,
assets,
partyId,
}: {
partyRewards: PartyRewardsConnection;
epochRewardSummaries: RewardsHistoryQuery['epochRewardSummaries'];
assets: Record<string, Asset> | null;
partyId: string | null;
}) => {
if (partyId) {
const rewards = removePaginationWrapper(partyRewards?.edges).map((r) => ({
rewardType: r.rewardType,
assetId: r.asset.id,
amount: r.amount,
}));
return getRewards(rewards, assets);
}
const rewards = removePaginationWrapper(epochRewardSummaries?.edges);
return getRewards(rewards, assets);
};
@@ -1,12 +1,11 @@
import { t } from '@vegaprotocol/i18n';
import { Switch, ToastPositionSetter } from '@vegaprotocol/ui-toolkit';
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
import { useTelemetryApproval } from '../../lib/hooks/use-telemetry-approval';
import type { ReactNode } from 'react';
import classNames from 'classnames';
import { useT } from '../../lib/use-t';
export const Settings = () => {
const t = useT();
const { theme, setTheme } = useThemeSwitcher();
const [isApproved, setIsApproved] = useTelemetryApproval();
return (
+1 -3
View File
@@ -6,6 +6,7 @@ import { create } from 'zustand';
import { TransferContainer } from '@vegaprotocol/accounts';
import { DealTicketContainer } from '@vegaprotocol/deal-ticket';
import { DepositContainer } from '@vegaprotocol/deposits';
import { t } from '@vegaprotocol/i18n';
import { MarketInfoAccordionContainer } from '@vegaprotocol/markets';
import { TinyScroll, VegaIcon, VegaIconNames } from '@vegaprotocol/ui-toolkit';
import { NodeHealthContainer } from '../node-health';
@@ -15,7 +16,6 @@ import { WithdrawContainer } from '../withdraw-container';
import { GetStarted } from '../welcome-dialog';
import { useVegaWallet, useViewAsDialog } from '@vegaprotocol/wallet';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export enum ViewType {
Order = 'Order',
@@ -51,7 +51,6 @@ type SidebarView =
};
export const Sidebar = ({ options }: { options?: ReactNode }) => {
const t = useT();
const currentRouteId = useGetCurrentRouteId();
const navClasses = 'flex lg:flex-col items-center gap-2 lg:gap-4 p-1';
const setViewAsDialogOpen = useViewAsDialog((state) => state.setOpen);
@@ -151,7 +150,6 @@ export const SidebarDivider = () => {
};
export const SidebarContent = () => {
const t = useT();
const params = useParams();
const currentRouteId = useGetCurrentRouteId();
@@ -1,4 +1,5 @@
import { useDataGridEvents } from '@vegaprotocol/datagrid';
import { t } from '@vegaprotocol/i18n';
import { StopOrdersManager } from '@vegaprotocol/orders';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
@@ -7,10 +8,8 @@ import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { DataGridSlice } from '../../stores/datagrid-store-slice';
import { createDataGridSlice } from '../../stores/datagrid-store-slice';
import { useT } from '../../lib/use-t';
export const StopOrdersContainer = () => {
const t = useT();
const { pubKey, isReadOnly } = useVegaWallet();
const onMarketClick = useMarketClickHandler(true);
@@ -4,7 +4,7 @@ import {
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { useT } from '../../lib/use-t';
import { t } from '@vegaprotocol/i18n';
interface Props {
telemetryValue: string;
@@ -15,7 +15,6 @@ export const TelemetryApproval = ({
telemetryValue,
setTelemetryValue,
}: Props) => {
const t = useT();
return (
<div className="flex flex-col">
<div className="mr-4" role="form">
@@ -3,13 +3,12 @@ import { Intent, useToasts } from '@vegaprotocol/ui-toolkit';
import { useTelemetryApproval } from '../../lib/hooks/use-telemetry-approval';
import { useCallback, useEffect } from 'react';
import { TelemetryApproval } from './telemetry-approval';
import { t } from '@vegaprotocol/i18n';
import { useOnboardingStore } from '../welcome-dialog/use-get-onboarding-step';
import { useT } from '../../lib/use-t';
const TELEMETRY_APPROVAL_TOAST_ID = 'telemetry_toast_id';
export const Telemetry = () => {
const t = useT();
const onboardingDissmissed = useOnboardingStore((store) => store.dismissed);
const [telemetryValue, setTelemetryValue, isTelemetryNeeded, closeTelemetry] =
useTelemetryApproval();
@@ -64,7 +63,6 @@ export const Telemetry = () => {
hasToast,
onApprovalClose,
setTelemetryApprovalAndClose,
t,
]);
return null;
@@ -2,6 +2,7 @@ import { useMemo, useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { isBrowserWalletInstalled } from '@vegaprotocol/wallet';
import { truncateByChars } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
VegaIcon,
VegaIconNames,
@@ -22,10 +23,8 @@ import { useCopyTimeout } from '@vegaprotocol/react-helpers';
import { ViewType, useSidebar } from '../sidebar';
import classNames from 'classnames';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const VegaWalletConnectButton = () => {
const t = useT();
const [dropdownOpen, setDropdownOpen] = useState(false);
const openVegaWalletDialog = useVegaWalletDialogStore(
(store) => store.openVegaWalletDialog
@@ -130,7 +129,6 @@ export const VegaWalletConnectButton = () => {
};
const KeypairItem = ({ pk, active }: { pk: PubKey; active: boolean }) => {
const t = useT();
const [copied, setCopied] = useCopyTimeout();
return (
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import { useCopyTimeout } from '@vegaprotocol/react-helpers';
import {
TradingButton as Button,
@@ -10,14 +11,12 @@ import { useCallback, useMemo } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { ViewType, useSidebar } from '../sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { useT } from '../../lib/use-t';
export const VegaWalletMenu = ({
setMenu,
}: {
setMenu: (open: 'nav' | 'wallet' | null) => void;
}) => {
const t = useT();
const { pubKey, pubKeys, selectPubKey, disconnect } = useVegaWallet();
const currentRouteId = useGetCurrentRouteId();
const setViews = useSidebar((store) => store.setViews);
@@ -77,7 +76,6 @@ const KeypairListItem = ({
isActive: boolean;
onSelectItem: (pk: string) => void;
}) => {
const t = useT();
const [copied, setCopied] = useCopyTimeout();
return (
@@ -1,4 +1,5 @@
import classNames from 'classnames';
import { t } from '@vegaprotocol/i18n';
import {
ExternalLink,
Intent,
@@ -17,15 +18,12 @@ import {
import { Links, Routes } from '../../lib/links';
import { useGlobalStore } from '../../stores';
import { useSidebar, ViewType } from '../sidebar';
import { useT } from '../../lib/use-t';
import { Trans } from 'react-i18next';
interface Props {
lead?: string;
}
const GetStartedButton = ({ step }: { step: OnboardingStep }) => {
const t = useT();
const dismiss = useOnboardingStore((store) => store.dismiss);
const setDialogOpen = useOnboardingStore((store) => store.setDialogOpen);
const marketId = useGlobalStore((store) => store.marketId);
@@ -80,7 +78,6 @@ const GetStartedButton = ({ step }: { step: OnboardingStep }) => {
};
export const GetStartedCheckList = () => {
const t = useT();
const { pubKey } = useVegaWallet();
const currentStep = useGetOnboardingStep();
return (
@@ -107,7 +104,6 @@ export const GetStartedCheckList = () => {
};
export const GetStarted = ({ lead }: Props) => {
const t = useT();
const { pubKey } = useVegaWallet();
const { VEGA_ENV, VEGA_NETWORKS } = useEnvironment();
const openVegaWalletDialog = useVegaWalletDialogStore(
@@ -136,26 +132,18 @@ export const GetStarted = ({ lead }: Props) => {
</div>
{VEGA_ENV === Networks.MAINNET && (
<p className="text-sm">
<Trans
defaults="Experiment for free with virtual assets on <0>Fairground Testnet</0>"
components={[
<ExternalLink href={VEGA_NETWORKS.TESTNET} key="link">
Fairground Testnet
</ExternalLink>,
]}
/>
{t('Experiment for free with virtual assets on')}{' '}
<ExternalLink href={VEGA_NETWORKS.TESTNET}>
{t('Fairground Testnet')}
</ExternalLink>
</p>
)}
{VEGA_ENV === Networks.TESTNET && (
<p className="text-sm">
<Trans
defaults="Ready to trade with real funds? <0>Switch to Mainnet</0>"
components={[
<ExternalLink href={VEGA_NETWORKS.MAINNET} key="link">
Switch to Mainnet
</ExternalLink>,
]}
/>
{t('Ready to trade with real funds?')}{' '}
<ExternalLink href={VEGA_NETWORKS.MAINNET}>
{t('Switch to Mainnet')}
</ExternalLink>
</p>
)}
</div>
@@ -166,14 +154,11 @@ export const GetStarted = ({ lead }: Props) => {
return (
<div className={wrapperClasses}>
<p className="mb-1 text-sm">
<Trans
defaults="You need a <0>Vega wallet</0> to start trading in this market."
components={[
<ExternalLink href="https://vega.xyz/wallet" key="link">
Vega wallet
</ExternalLink>,
]}
/>
You need a{' '}
<ExternalLink href="https://vega.xyz/wallet">
Vega wallet
</ExternalLink>{' '}
to start trading in this market.
</p>
<TradingButton
onClick={openVegaWalletDialog}
@@ -1,4 +1,5 @@
import { useMemo } from 'react';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { proposalsDataProvider } from '@vegaprotocol/proposals';
import take from 'lodash/take';
@@ -11,10 +12,8 @@ import {
TOKEN_PROPOSALS,
useLinks,
} from '@vegaprotocol/environment';
import { useT } from '../../lib/use-t';
export const ProposedMarkets = () => {
const t = useT();
const variables = useMemo(() => {
return {
proposalType: Types.ProposalType.TYPE_NEW_MARKET,
@@ -76,6 +75,6 @@ export const ProposedMarkets = () => {
)}
</div>
),
[newMarkets, tokenLink, t]
[newMarkets, tokenLink]
);
};
@@ -1,20 +1,9 @@
import { t } from '@vegaprotocol/i18n';
import { VegaIcon, VegaIconNames } from '@vegaprotocol/ui-toolkit';
import { Link } from 'react-router-dom';
import { Links } from '../../lib/links';
import { useT } from '../../lib/use-t';
import { Trans } from 'react-i18next';
const DisclaimerLink = ({ children }: { children?: string[] }) => (
<Link className="underline" to={Links.DISCLAIMER()} target="_blank">
<span className="flex items-center gap-1">
<span>{children}</span>
<VegaIcon name={VegaIconNames.OPEN_EXTERNAL} />
</span>
</Link>
);
export const RiskMessage = () => {
const t = useT();
return (
<>
<div className="p-6 mb-6 bg-vega-light-100 dark:bg-vega-dark-100">
@@ -35,10 +24,15 @@ export const RiskMessage = () => {
</ul>
</div>
<p className="mb-8">
<Trans
defaults="By using the Vega Console, you acknowledge that you have read and understood the <0>Vega Console Disclaimer</0>"
components={[<DisclaimerLink key="link" />]}
/>
{t(
'By using the Vega Console, you acknowledge that you have read and understood the'
)}{' '}
<Link className="underline" to={Links.DISCLAIMER()} target="_blank">
<span className="flex items-center gap-1">
<span>{t('Vega Console Disclaimer')}</span>
<VegaIcon name={VegaIconNames.OPEN_EXTERNAL} />
</span>
</Link>
</p>
</>
);
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import { GetStarted } from './get-started';
import { TradingAnchorButton } from '@vegaprotocol/ui-toolkit';
import { Links } from '../../lib/links';
@@ -5,10 +6,8 @@ import { Networks, useEnvironment } from '@vegaprotocol/environment';
import type { ReactNode } from 'react';
import { useTopTradedMarkets } from '../../lib/hooks/use-top-traded-markets';
import { useOnboardingStore } from './use-get-onboarding-step';
import { useT } from '../../lib/use-t';
export const WelcomeDialogContent = () => {
const t = useT();
const { VEGA_ENV } = useEnvironment();
const setOnboardingDialog = useOnboardingStore(
(store) => store.setDialogOpen
@@ -1,14 +1,13 @@
import { Dialog, Intent } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
import { useEnvironment } from '@vegaprotocol/environment';
import { WelcomeDialogContent } from './welcome-dialog-content';
import { useOnboardingStore } from './use-get-onboarding-step';
import { VegaConnectDialog } from '@vegaprotocol/wallet';
import { Connectors } from '../../lib/vega-connectors';
import { RiskMessage } from './risk-message';
import { useT } from '../../lib/use-t';
export const WelcomeDialog = () => {
const t = useT();
const { VEGA_ENV } = useEnvironment();
const dismissed = useOnboardingStore((store) => store.dismissed);
const dialogOpen = useOnboardingStore((store) => store.dialogOpen);
@@ -5,11 +5,10 @@ import {
useIncompleteWithdrawals,
} from '@vegaprotocol/withdraws';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { useT } from '../../lib/use-t';
export const WithdrawalsContainer = () => {
const t = useT();
const { pubKey } = useVegaWallet();
const { data, error } = useDataProvider({
dataProvider: withdrawalProvider,

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