Compare commits

...
17 changed files with 167 additions and 85 deletions
+3
View File
@@ -1,5 +1,8 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Auto-format all files
yarn nx format:write
# Lint all staged files
yarn lint-staged
+3 -3
View File
@@ -1,8 +1,8 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Lint all staged files
yarn nx format:check
# Lint all staged files - this brings more value as pre-commit
# yarn nx format:check
# Test all projects with changes
yarn nx affected -t test --exclude trading
# yarn nx affected -t test --exclude trading
+2 -3
View File
@@ -22,10 +22,9 @@ NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
NX_SUCCESSOR_MARKETS=true
NX_STOP_ORDERS=true
NX_ICEBERG_ORDERS=true
# NX_PRODUCT_PERPETUALS
NX_METAMASK_SNAPS=true
NX_REFERRALS=false
NX_REFERRALS=true
# NX_DISABLE_CLOSE_POSITION=false
NX_TENDERMINT_URL=https://be.vega.community
NX_TENDERMINT_WEBSOCKET_URL=wss://be.vega.community/websocket
NX_DISABLE_CLOSE_POSITION=true
-1
View File
@@ -23,7 +23,6 @@ NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
NX_SUCCESSOR_MARKETS=true
NX_STOP_ORDERS=true
NX_ICEBERG_ORDERS=true
# NX_PRODUCT_PERPETUALS
NX_METAMASK_SNAPS=true
NX_REFERRALS=true
@@ -18,13 +18,35 @@ import { Routes } from '../../lib/links';
import { useTransactionEventSubscription } from '@vegaprotocol/web3';
import { Statistics, useStats } from './referral-statistics';
import { useReferralProgram } from './hooks/use-referral-program';
import { useT } from '../../lib/use-t';
import { ns, useT } from '../../lib/use-t';
import { useFundsAvailable } from './hooks/use-funds-available';
import { ViewType, useSidebar } from '../../components/sidebar';
import { useGetCurrentRouteId } from '../../lib/hooks/use-get-current-route-id';
import { QUSDTooltip } from './qusd-tooltip';
import { Trans } from 'react-i18next';
const RELOAD_DELAY = 3000;
const SPAM_PROTECTION_ERR = 'SPAM_PROTECTION_ERR';
const SpamProtectionErr = ({
requiredFunds,
}: {
requiredFunds?: string | number | bigint;
}) => {
if (!requiredFunds) return null;
// eslint-disable-next-line react/jsx-no-undef
return (
<Trans
defaults="To protect the network from spam, you must have at least {{requiredFunds}} <0>qUSD</0> of any asset on the network to proceed."
values={{
requiredFunds,
}}
components={[<QUSDTooltip key="qusd" />]}
ns={ns}
/>
);
};
const validateCode = (value: string, t: ReturnType<typeof useT>) => {
const number = +`0x${value}`;
if (!value || value.length !== 64) {
@@ -76,7 +98,6 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
setValue,
setError,
watch,
clearErrors,
} = useForm();
const [params] = useSearchParams();
@@ -90,30 +111,11 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
*/
const validateFundsAvailable = useCallback(() => {
if (requiredFunds && !isEligible) {
const err = t(
'Require minimum of {{requiredFunds}} to join a referral set to protect the network from spam.',
{ replace: { requiredFunds } }
);
const err = SPAM_PROTECTION_ERR;
return err;
}
return true;
}, [isEligible, requiredFunds, t]);
useEffect(() => {
if (codeField) {
const err = validateFundsAvailable();
if (err !== true) {
setStatus('no-funds');
setError('code', {
type: 'required',
message: err,
});
} else {
setStatus(null);
clearErrors('code');
}
}
}, [clearErrors, codeField, isEligible, setError, validateFundsAvailable]);
}, [isEligible, requiredFunds]);
/**
* Validates the set a user tries to apply to.
@@ -138,6 +140,15 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
if (code) setValue('code', code);
}, [params, setValue]);
useEffect(() => {
const err = validateFundsAvailable();
if (err !== true) {
setStatus('no-funds');
} else {
setStatus(null);
}
}, [isEligible, validateFundsAvailable]);
const onSubmit = ({ code }: FieldValues) => {
if (isReadOnly || !pubKey || !code || code.length === 0) {
return;
@@ -321,10 +332,26 @@ export const ApplyCodeForm = ({ onSuccess }: { onSuccess?: () => void }) => {
</label>
<RainbowButton variant="border" {...getButtonProps()} />
</form>
{errors.code && (
<InputError className="overflow-auto break-words">
{errors.code.message?.toString()}
{status === 'no-funds' ? (
<InputError intent="warning" className="overflow-auto break-words">
<span>
<SpamProtectionErr requiredFunds={requiredFunds?.toString()} />
</span>
</InputError>
) : (
errors.code && (
<InputError intent="warning" className="overflow-auto break-words">
{errors.code.message === SPAM_PROTECTION_ERR ? (
<span>
<SpamProtectionErr
requiredFunds={requiredFunds?.toString()}
/>
</span>
) : (
errors.code.message?.toString()
)}
</InputError>
)
)}
</div>
{validateCode(codeField, t) === true && previewLoading && !previewData ? (
@@ -1,7 +1,7 @@
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useFundsAvailableQuery } from './__generated__/FundsAvailable';
import compact from 'lodash/compact';
import sum from 'lodash/sum';
import BigNumber from 'bignumber.js';
/**
* Gets the funds for given public key and required min for
@@ -24,14 +24,16 @@ export const useFundsAvailable = (pubKey?: string) => {
? compact(data.party?.accountsConnection?.edges?.map((e) => e?.node))
: undefined;
const requiredFunds = data
? BigInt(data.networkParameter?.value || '0')
? BigNumber(data.networkParameter?.value || '0')
: undefined;
const sumOfFunds = sum(
fundsAvailable?.filter((fa) => fa.balance).map((fa) => BigInt(fa.balance))
);
const sumOfFunds =
fundsAvailable
?.filter((fa) => fa.balance)
.reduce((sum, fa) => sum.plus(BigNumber(fa.balance)), BigNumber(0)) ||
BigNumber(0);
if (requiredFunds && sumOfFunds >= requiredFunds) {
if (requiredFunds && sumOfFunds.isGreaterThanOrEqualTo(requiredFunds)) {
stopPolling();
}
@@ -41,6 +43,6 @@ export const useFundsAvailable = (pubKey?: string) => {
isEligible:
fundsAvailable != null &&
requiredFunds != null &&
sumOfFunds >= requiredFunds,
sumOfFunds.isGreaterThanOrEqualTo(requiredFunds),
};
};
@@ -15,7 +15,7 @@ export const LandingBanner = () => {
</div>
<div className="pt-20 sm:w-[50%]">
<h1 className="text-6xl font-alpha calt mb-10">
{t('Vega community referral program')}
{t('Vega community referrals')}
</h1>
<p className="text-lg mb-1">
{t(
@@ -0,0 +1,28 @@
import { DocsLinks } from '@vegaprotocol/environment';
import { ExternalLink, Tooltip } from '@vegaprotocol/ui-toolkit';
import { useT } from '../../lib/use-t';
export const QUSDTooltip = () => {
const t = useT();
return (
<Tooltip
description={
<>
<p className="mb-1">
{t(
'qUSD provides a rough USD equivalent of balances across all assets using the value of "Quantum" for that asset'
)}
</p>
{DocsLinks && (
<ExternalLink href={DocsLinks.QUANTUM}>
{t('Find out more')}
</ExternalLink>
)}
</>
}
underline={true}
>
<span>{t('qUSD')}</span>
</Tooltip>
);
};
@@ -4,8 +4,6 @@ import {
VegaIcon,
VegaIconNames,
truncateMiddle,
ExternalLink,
Tooltip,
} from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
@@ -28,10 +26,10 @@ import sortBy from 'lodash/sortBy';
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useCurrentEpochInfoQuery } from './hooks/__generated__/Epoch';
import BigNumber from 'bignumber.js';
import { DocsLinks } from '@vegaprotocol/environment';
import { useT, ns } from '../../lib/use-t';
import { Trans } from 'react-i18next';
import { ApplyCodeForm, ApplyCodeFormContainer } from './apply-code-form';
import { QUSDTooltip } from './qusd-tooltip';
export const ReferralStatistics = () => {
const { pubKey } = useVegaWallet();
@@ -121,7 +119,7 @@ export const useStats = ({
: 1;
const finalCommissionValue = isNaN(multiplier)
? baseCommissionValue
: multiplier * baseCommissionValue;
: new BigNumber(multiplier).times(baseCommissionValue).toNumber();
const discountFactorValue = refereeStats?.discountFactor
? Number(refereeStats.discountFactor)
@@ -242,19 +240,23 @@ export const Statistics = ({
{multiplier || t('None')}
</StatTile>
);
const baseCommissionFormatted = BigNumber(baseCommissionValue)
.times(100)
.toString();
const finalCommissionFormatted = new BigNumber(finalCommissionValue)
.times(100)
.toString();
const finalCommissionTile = (
<StatTile
title={t('Final commission rate')}
description={
!isNaN(multiplier)
? `(${baseCommissionValue * 100}% ⨉ ${multiplier} = ${
finalCommissionValue * 100
}%)`
? `(${baseCommissionFormatted}% ⨉ ${multiplier} = ${finalCommissionFormatted}%)`
: undefined
}
overrideWithNoProgram={!details}
>
{finalCommissionValue * 100}%
{finalCommissionFormatted}%
</StatTile>
);
const numberOfTradersValue = data.referees.length;
@@ -515,28 +517,3 @@ export const RefereesTable = ({
</>
);
};
export const QUSDTooltip = () => {
const t = useT();
return (
<Tooltip
description={
<>
<p className="mb-1">
{t(
'qUSD provides a rough USD equivalent of balances across all assets using the value of "Quantum" for that asset'
)}
</p>
{DocsLinks && (
<ExternalLink href={DocsLinks.QUANTUM}>
{t('Find out more')}
</ExternalLink>
)}
</>
}
underline={true}
>
<span>{t('qUSD')}</span>
</Tooltip>
);
};
@@ -159,11 +159,11 @@ export const TiersContainer = () => {
return (
<>
<h2 className="text-3xl mt-10">{t('Current Program Details')}</h2>
<h2 className="text-3xl mt-10">{t('Current program details')}</h2>
{details?.id && (
<p>
<Trans
defaults="As a result of <0>{{proposal}}</0> the program below is currently active on the Vega network."
defaults="As a result of governance proposal <0>{{proposal}}</0> the program below is currently active on the Vega network."
values={{ proposal: truncateMiddle(details.id) }}
components={[
<ExternalLink
@@ -10,6 +10,7 @@ import { positionsDataProvider } from '@vegaprotocol/positions';
import { useGlobalStore } from '../../stores';
const ONBOARDING_STORAGE_KEY = 'vega_onboarding';
export const useOnboardingStore = create<{
dialogOpen: boolean;
walletDialogOpen: boolean;
@@ -20,7 +21,7 @@ export const useOnboardingStore = create<{
}>()(
persist(
(set) => ({
dialogOpen: true,
dialogOpen: false,
walletDialogOpen: false,
dismissed: false,
dismiss: () => set({ dismissed: true }),
@@ -1,18 +1,29 @@
import { useEffect } from 'react';
import { matchPath, useLocation } from 'react-router-dom';
import { Dialog, Intent } from '@vegaprotocol/ui-toolkit';
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';
import { Routes } from '../../lib/links';
import { RiskMessage } from './risk-message';
import { WelcomeDialogContent } from './welcome-dialog-content';
import { useOnboardingStore } from './use-get-onboarding-step';
import { ensureSuffix } from '@vegaprotocol/utils';
/**
* A list of paths on which the welcome dialog should be omitted.
*/
const OMIT_ON_LIST = [ensureSuffix(Routes.REFERRALS, '/*')];
export const WelcomeDialog = () => {
const { pathname } = useLocation();
const t = useT();
const { VEGA_ENV } = useEnvironment();
const dismissed = useOnboardingStore((store) => store.dismissed);
const dialogOpen = useOnboardingStore((store) => store.dialogOpen);
const dismiss = useOnboardingStore((store) => store.dismiss);
const setDialogOpen = useOnboardingStore((store) => store.setDialogOpen);
const walletDialogOpen = useOnboardingStore(
(store) => store.walletDialogOpen
);
@@ -20,6 +31,16 @@ export const WelcomeDialog = () => {
(store) => store.setWalletDialogOpen
);
useEffect(() => {
const shouldOmit = OMIT_ON_LIST.map((path) =>
matchPath(path, pathname)
).some((m) => !!m);
if (dismissed || shouldOmit) return;
setDialogOpen(true);
}, [dismissed, pathname, setDialogOpen]);
const content = walletDialogOpen ? (
<VegaConnectDialog
connectors={Connectors}
@@ -31,7 +52,12 @@ export const WelcomeDialog = () => {
<WelcomeDialogContent />
);
const onClose = walletDialogOpen ? () => setWalletDialogOpen(false) : dismiss;
const onClose = walletDialogOpen
? () => setWalletDialogOpen(false)
: () => {
setDialogOpen(false);
dismiss();
};
const title = walletDialogOpen ? null : (
<span className="font-alpha calt" data-testid="welcome-title">
@@ -59,7 +59,7 @@ def test_market_selector_filter(continuous_market, page: Page):
page.get_by_test_id("search-term").fill("btc")
expect(page.locator('[data-testid="market-selector-list"] a')).to_have_count(1)
expect(page.locator('[data-testid="market-selector-list"] a').nth(0)).to_have_text(
"BTC:DAI_2023107.50 tDAI1"
"BTC:DAI_2023107.50 tDAI0.00"
)
page.get_by_test_id("search-term").clear()
@@ -84,5 +84,5 @@ def test_market_selector_filter(continuous_market, page: Page):
page.get_by_role("menuitemcheckbox").nth(0).get_by_text("tDAI").click()
expect(page.locator('[data-testid="market-selector-list"] a')).to_have_count(1)
expect(page.locator('[data-testid="market-selector-list"] a').nth(0)).to_have_text(
"BTC:DAI_2023107.50 tDAI1"
"BTC:DAI_2023107.50 tDAI0.00"
)
@@ -137,6 +137,6 @@ def test_perps_market_terminated(page: Page, vega: VegaService):
expect(page.get_by_test_id("market-trading-mode")).to_have_text("Trading modeNo trading")
expect(page.get_by_test_id("market-state")).to_have_text("StatusClosed")
expect(page.get_by_test_id("liquidity-supplied")).to_have_text("Liquidity supplied 0.00 (0.00%)")
expect(page.get_by_test_id("market-funding")).to_have_text("Funding Rate / Countdown-Unknown")
expect(page.get_by_test_id("index-price")).to_have_text("Index Price-")
expect(page.get_by_test_id("market-funding")).to_contain_text("Funding Rate / Countdown")
expect(page.get_by_test_id("index-price")).to_contain_text("Index Price")
expect(page.get_by_test_id("deal-ticket-error-message-summary")).to_have_text("This market is closed and not accepting orders")
+1
View File
@@ -279,6 +279,7 @@
"This timestamp is user curated metadata and does not drive any on-chain functionality.": "This timestamp is user curated metadata and does not drive any on-chain functionality.",
"Tier": "Tier",
"to": "to",
"To protect the network from spam, you must have at least {{requiredFunds}} qUSD of any asset on the network to proceed.": "To protect the network from spam, you must have at least {{requiredFunds}} qUSD of any asset on the network to proceed.",
"Toast location": "Toast location",
"Total discount": "Total discount",
"Total distributed": "Total distributed",
+13
View File
@@ -4,6 +4,7 @@ import {
shorten,
titlefy,
stripFullStops,
ensureSuffix,
} from './strings';
describe('truncateByChars', () => {
@@ -88,3 +89,15 @@ describe('stripFullStops', () => {
});
});
});
describe('ensureSuffix', () => {
it.each([
['', 'abc', 'abc'],
['abc', '', 'abc'],
['def', 'abc', 'abcdef'],
['ąę', 'ae', 'aeąę'],
['🥪', '🍞+🔪=', '🍞+🔪=🥪'],
])('ensures "%s" at the end of "%s": "%s"', (suffix, input, expected) => {
expect(ensureSuffix(input, suffix)).toEqual(expected);
});
});
+6
View File
@@ -33,3 +33,9 @@ export function titlefy(words: (string | null | undefined)[]) {
export function stripFullStops(input: string) {
return input.replace(/\./g, '');
}
export function ensureSuffix(input: string, suffix: string) {
const maybeSuffix = input.substring(input.length - suffix.length);
if (maybeSuffix === suffix) return input;
return input + suffix;
}