Compare commits

...
30 changed files with 720 additions and 544 deletions
+13 -13
View File
@@ -48,8 +48,8 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.get('@markets').then((markets) => {
cy.wrap(markets[0]).as('market');
});
cy.setOnBoardingViewed();
cy.visit('/#/portfolio');
cy.connectVegaWallet();
});
it('can deposit', function () {
@@ -70,6 +70,8 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.getByTestId('deposit-button').click();
connectEthereumWallet('Unknown');
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.getByTestId('approve-default').should(
'contain.text',
`Before you can make a deposit of your chosen asset, ${btcSymbol}, you need to approve its use in your Ethereum wallet`
@@ -120,7 +122,7 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.get('[data-testid="pathname-/portfolio"]').should('exist');
cy.getByTestId(collateralTab).click();
cy.getByTestId('open-transfer').click();
cy.getByTestId('open-transfer').eq(1).click();
cy.getByTestId('transfer-form').should('be.visible');
cy.getByTestId('transfer-form').find('[name="toAddress"]').select(1);
cy.get('select option')
@@ -147,7 +149,8 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
// 0003-WTXN-011
cy.getByTestId('Withdrawals').click();
cy.getByTestId('withdraw-dialog-button').click();
selectAsset(0);
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.get(amountField).focus();
cy.get(amountField).clear().type('1');
cy.getByTestId('submit-withdrawal').click();
@@ -180,24 +183,21 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
cy.get('@markets').then((markets) => {
cy.wrap(markets[0]).as('market');
});
cy.setOnBoardingViewed();
cy.setVegaWallet();
});
it('shows node health', function () {
// 0006-NETW-010
const regex = /^Operational\d+$/;
const market = this.market;
cy.visit(`/#/markets/${market.id}`);
cy.getByTestId('node-health-trigger').realHover();
cy.getByTestId('node-health')
.children()
.first()
.should('contain.text', 'Operational')
.then(($el) => {
const blockHeight = parseInt($el.text());
// block height will increase over the course of the test run so best
// we can do here is check that its showing something sensible
expect(blockHeight).to.be.greaterThan(0);
});
.invoke('text')
.should('match', regex);
cy.getByTestId('node-health')
.children()
.eq(1)
@@ -239,7 +239,6 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
.should('contain.text', order.size);
cy.getByTestId(openOrdersTab).click();
cy.getByTestId('edit', txTimeout).should('contain.text', 'Edit');
cy.getByTestId('tab-open-orders').within(() => {
cy.get('.ag-center-cols-container')
.children()
@@ -280,8 +279,7 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
cy.visit(`/#/markets/${market.id}`);
cy.getByTestId(toastCloseBtn, txTimeout).click();
cy.getByTestId(openOrdersTab).click();
cy.getByTestId('edit', txTimeout).should('be.visible');
cy.getByTestId('edit').first().should('be.visible').click();
cy.getByTestId('edit').first().click();
cy.getByTestId('dialog-title').should('contain.text', 'Edit order');
cy.get('#limitPrice').focus().clear().type(newPrice);
cy.getByTestId('edit-order').find('[type="submit"]').click();
@@ -350,6 +348,7 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
cy.getByTestId('withdraw-dialog-button').click();
connectEthereumWallet('Unknown');
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.get(amountField).clear().type('1');
cy.getByTestId('submit-withdrawal').click();
cy.getByTestId(toastContent, txTimeout).should(
@@ -437,6 +436,7 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
cy.getByTestId('deposit-button').click();
connectEthereumWallet('Unknown');
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.contains('Deposits of tBTC not approved').should('not.exist');
cy.contains('Use maximum').should('be.visible');
cy.get(amountField).clear().type('20000000');
@@ -1,131 +0,0 @@
import { connectEthereumWallet } from '../support/ethereum-wallet';
import { selectAsset } from '../support/helpers';
const formFieldError = 'input-error-text';
const toAddressField = 'input[name="to"]';
const amountField = 'input[name="amount"]';
const useMaximumAmount = 'use-maximum';
const submitWithdrawBtn = 'submit-withdrawal';
const ethAddressValue = Cypress.env('ETHEREUM_WALLET_ADDRESS');
const ASSET_SEPOLIA_TBTC = 2;
const ASSET_EURO = 1;
describe('withdraw form validation', { tags: '@smoke' }, () => {
before(() => {
cy.mockWeb3Provider();
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/portfolio');
cy.getByTestId('Withdrawals').click();
cy.getByTestId('Withdraw').click(); // sidebar item
// It also requires connection Ethereum wallet
connectEthereumWallet('MetaMask');
cy.wait('@Accounts');
cy.wait('@Assets');
});
it('empty fields', () => {
cy.getByTestId(submitWithdrawBtn).click();
cy.getByTestId(formFieldError).should('contain.text', 'Required');
// only 2 despite 3 fields because the ethereum address will be auto populated
cy.getByTestId(formFieldError).should('have.length', 2);
// Test for Ethereum address
cy.get(toAddressField).should('have.value', ethAddressValue);
});
it('min amount', () => {
// 1002-WITH-010
selectAsset(ASSET_SEPOLIA_TBTC);
cy.get(amountField).clear().type('0');
cy.getByTestId(submitWithdrawBtn).click();
cy.get('[data-testid="input-error-text"]').should(
'contain.text',
'Value is below minimum'
);
});
it('max amount', () => {
// 1002-WITH-005
// 1002-WITH-008
selectAsset(ASSET_EURO); // Will be above maximum because the vega wallet doesn't have any collateral
cy.get(amountField).clear().type('1001', { delay: 100 });
cy.getByTestId(submitWithdrawBtn).click();
cy.get('[data-testid="input-error-text"]').should(
'contain.text',
'Insufficient amount in account'
);
});
it('can set amount using use maximum button', () => {
// 1002-WITH-004
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId(useMaximumAmount).click();
cy.get(amountField).should('have.value', '1000.00001');
});
});
describe(
'withdraw actions',
{ tags: '@regression', testIsolation: true },
() => {
// this is extremely ugly hack, but setting it properly in contract is too much effort for such simple validation
// 1002-WITH-018
const withdrawalThreshold =
Cypress.env('VEGA_ENV') === 'CUSTOM' ? '0.00' : '100.00';
before(() => {
cy.mockWeb3Provider();
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/portfolio');
cy.wait('@Accounts');
cy.wait('@Assets');
cy.getByTestId('Withdrawals').click();
cy.getByTestId('Withdraw').click();
// It also requires connection Ethereum wallet
connectEthereumWallet('MetaMask');
cy.mockVegaWalletTransaction();
});
it('triggers transaction when submitted', () => {
// 1002-WITH-002
// 1002-WITH-003
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId('BALANCE_AVAILABLE_label').should(
'contain.text',
'Balance available'
);
cy.getByTestId('BALANCE_AVAILABLE_value').should(
'have.text',
'1,000.00001'
);
cy.getByTestId('WITHDRAWAL_THRESHOLD_label').should(
'contain.text',
'Delayed withdrawal threshold'
);
cy.getByTestId('WITHDRAWAL_THRESHOLD_value').should(
'contain.text',
withdrawalThreshold
);
cy.getByTestId('DELAY_TIME_label').should('contain.text', 'Delay time');
cy.getByTestId('DELAY_TIME_value').should('have.text', 'None');
cy.get(amountField).clear().type('10');
cy.getByTestId(submitWithdrawBtn).click();
cy.getByTestId('toast').should('contain.text', 'Awaiting confirmation');
});
}
);
@@ -8,22 +8,17 @@ export const LandingBanner = () => {
<div className="">
<div
aria-hidden
className="absolute top-64 right-[220px] md:right-[340px] max-sm:hidden"
className="absolute top-20 right-[120px] md:right-[240px] max-sm:hidden"
>
<AnimatedDudeWithWire />
</div>
<div className="pt-32 sm:w-[50%]">
<div className="pt-20 sm:w-[50%]">
<h1 className="text-6xl font-alpha calt mb-10">
{t('Earn commission & stake rewards')}
</h1>
<p className="text-lg mb-10">
{t(
'Invite friends and earn commission in the form of Vega rewards from the trading fees they pay. Stake those rewards to earn multipliers on future rewards.'
)}
</p>
<p className="text-lg">
{t(
'Any friends that join using the code will receive discounts off trading fees.'
'Invite friends and earn rewards from the trading fees they pay. Stake those rewards to earn multipliers on future rewards.'
)}
</p>
</div>
@@ -2,6 +2,7 @@ import classNames from 'classnames';
import type { HTMLAttributes } from 'react';
import { SKY_BACKGROUND } from './constants';
import { Outlet } from 'react-router-dom';
import { TinyScroll } from '@vegaprotocol/ui-toolkit';
export const Layout = ({
className,
@@ -28,8 +29,10 @@ export const LayoutWithSky = ({
...props
}: HTMLAttributes<HTMLDivElement>) => {
return (
<div className={classNames('h-full overflow-auto', SKY_BACKGROUND)}>
<TinyScroll
className={classNames('max-h-full overflow-auto', SKY_BACKGROUND)}
>
<Layout className={className} {...props} />
</div>
</TinyScroll>
);
};
@@ -27,7 +27,7 @@ export const LayoutWithSidebar = ({
<div className={gridClasses}>
<div className="col-span-full">{header}</div>
<main
className={classNames('col-start-1 col-end-1', {
className={classNames('col-start-1 col-end-1 overflow-hidden', {
'lg:col-end-3': !sidebarOpen,
'hidden lg:block lg:col-end-2': sidebarOpen,
})}
+6 -2
View File
@@ -55,10 +55,14 @@ export const routerConfig: RouteObject[] = compact([
FLAGS.REFERRALS
? {
path: AppRoutes.REFERRALS,
element: <LayoutWithSky />,
element: <LayoutWithSidebar sidebar={<PortfolioSidebar />} />,
children: [
{
element: <Referrals />,
element: (
<LayoutWithSky>
<Referrals />
</LayoutWithSky>
),
children: [
{
index: true,
+2 -2
View File
@@ -1,5 +1,5 @@
import { ToastsContainer, useToasts } from '@vegaprotocol/ui-toolkit';
import { useUpdateNetworkParametersToasts } from '@vegaprotocol/proposals';
import { useProposalToasts } from '@vegaprotocol/proposals';
import { useVegaTransactionToasts } from '@vegaprotocol/web3';
import { useEthereumTransactionToasts } from '@vegaprotocol/web3';
import { useEthereumWithdrawApprovalsToasts } from '@vegaprotocol/web3';
@@ -7,7 +7,7 @@ import { useReadyToWithdrawalToasts } from '@vegaprotocol/withdraws';
import { Links } from '../lib/links';
export const ToastsManager = () => {
useUpdateNetworkParametersToasts();
useProposalToasts();
useVegaTransactionToasts();
useEthereumTransactionToasts();
useEthereumWithdrawApprovalsToasts();
Binary file not shown.

Before

Width:  |  Height:  |  Size: 947 KiB

After

Width:  |  Height:  |  Size: 419 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 947 KiB

After

Width:  |  Height:  |  Size: 419 KiB

+4 -3
View File
@@ -33,7 +33,7 @@ import BigNumber from 'bignumber.js';
import classNames from 'classnames';
import { AccountsActionsDropdown } from './accounts-actions-dropdown';
const colorClass = (percentageUsed: number, neutral = false) => {
const colorClass = (percentageUsed: number) => {
return classNames('text-right', {
'text-vega-orange': percentageUsed >= 75 && percentageUsed < 90,
'text-vega-red': percentageUsed >= 90,
@@ -210,7 +210,7 @@ export const AccountTable = ({
},
cellClass: ({ data }) => {
const percentageUsed = percentageValue(data?.used, data?.total);
return colorClass(percentageUsed, true);
return colorClass(percentageUsed);
},
valueFormatter: ({
value,
@@ -270,7 +270,8 @@ export const AccountTable = ({
onClickDeposit && onClickDeposit(assetId);
}}
>
<VegaIcon name={VegaIconNames.DEPOSIT} /> {t('Deposit')}
<VegaIcon name={VegaIconNames.DEPOSIT} size={14} />{' '}
{t('Deposit')}
</TradingButton>
</CenteredGridCellWrapper>
);
@@ -259,11 +259,9 @@ export const DealTicketMarginDetails = ({
? liquidationEstimateWorstCaseIncludingBuyOrders
: liquidationEstimateWorstCaseIncludingSellOrders;
// The estimate order query API gives us the liquidation price in formatted by asset decimals.
// We need to calculate it with asset decimals, but display it with market decimals precision until the API changes.
liquidationPriceEstimate = formatValue(
liquidationEstimateWorstCase.toString(),
assetDecimals,
market.decimalPlaces,
undefined,
market.decimalPlaces
);
@@ -276,7 +274,7 @@ export const DealTicketMarginDetails = ({
? liquidationEstimateBestCase
: liquidationEstimateWorstCase
).toString(),
assetDecimals,
market.decimalPlaces,
undefined,
market.decimalPlaces
);
@@ -308,7 +306,7 @@ export const DealTicketMarginDetails = ({
key={'value-dropdown'}
className="flex items-center justify-between w-full gap-2"
>
<div className="flex items-center gap-1 text-left">
<div className="flex items-center text-left gap-1">
<Tooltip description={MARGIN_DIFF_TOOLTIP_TEXT(assetSymbol)}>
<span className="text-muted">{t('Margin required')}</span>
</Tooltip>
@@ -24,6 +24,7 @@ import {
Tooltip,
TradingButton as Button,
Pill,
ExternalLink,
} from '@vegaprotocol/ui-toolkit';
import { useOpenVolume } from '@vegaprotocol/positions';
@@ -77,6 +78,7 @@ import { DealTicketSizeIceberg } from './deal-ticket-size-iceberg';
import noop from 'lodash/noop';
import { isNonPersistentOrder } from '../../utils/time-in-force-persistance';
import { KeyValue } from './key-value';
import { DocsLinks } from '@vegaprotocol/environment';
export const REDUCE_ONLY_TOOLTIP =
'"Reduce only" will ensure that this order will not increase the size of an open position. When the order is matched, it will only trade enough volume to bring your open volume towards 0 but never change the direction of your position. If applied to a limit order that is not instantly filled, the order will be stopped.';
@@ -273,7 +275,9 @@ export const DealTicket = ({
const assetSymbol = getAsset(market).symbol;
const assetUnit = getQuoteName(market);
const baseQuote = getBaseQuoteUnit(
market.tradableInstrument.instrument.metadata.tags
);
const summaryError = useMemo(() => {
if (!pubKey) {
@@ -412,7 +416,7 @@ export const DealTicket = ({
id="order-size"
className="w-full"
type="number"
appendElement={assetUnit && <Pill size="xs">{assetUnit}</Pill>}
appendElement={baseQuote && <Pill size="xs">{baseQuote}</Pill>}
step={sizeStep}
min={sizeStep}
data-testid="order-size"
@@ -548,15 +552,20 @@ export const DealTicket = ({
render={({ field }) => (
<Tooltip
description={
<span>
{disablePostOnlyCheckbox
? t(
'"Post only" can not be used on "Fill or Kill" or "Immediate or Cancel" orders.'
)
: t(
'"Post only" will ensure the order is not filled immediately but is placed on the order book as a passive order. When the order is processed it is either stopped (if it would not be filled immediately), or placed in the order book as a passive order until the price taker matches with it.'
)}
</span>
<>
<span>
{disablePostOnlyCheckbox
? t(
'"Post only" can not be used on "Fill or Kill" or "Immediate or Cancel" orders.'
)
: t(
'"Post only" will ensure the order is not filled immediately but is placed on the order book as a passive order. When the order is processed it is either stopped (if it would not be filled immediately), or placed in the order book as a passive order until the price taker matches with it.'
)}
</span>{' '}
<ExternalLink href={DocsLinks?.POST_REDUCE_ONLY}>
{t('Find out more')}
</ExternalLink>
</>
}
>
<div>
@@ -580,13 +589,18 @@ export const DealTicket = ({
render={({ field }) => (
<Tooltip
description={
<span>
{disableReduceOnlyCheckbox
? t(
'"Reduce only" can be used only with non-persistent orders, such as "Fill or Kill" or "Immediate or Cancel".'
)
: t(REDUCE_ONLY_TOOLTIP)}
</span>
<>
<span>
{disableReduceOnlyCheckbox
? t(
'"Reduce only" can be used only with non-persistent orders, such as "Fill or Kill" or "Immediate or Cancel".'
)
: t(REDUCE_ONLY_TOOLTIP)}
</span>{' '}
<ExternalLink href={DocsLinks?.POST_REDUCE_ONLY}>
{t('Find out more')}
</ExternalLink>
</>
}
>
<div>
@@ -618,7 +632,10 @@ export const DealTicket = ({
{t(`Trade only a fraction of the order size at once.
After the peak size of the order has traded, the size is reset. This is repeated until the order is cancelled, expires, or its full volume trades away.
For example, an iceberg order with a size of 1000 and a peak size of 100 will effectively be split into 10 orders with a size of 100 each.
Note that the full volume of the order is not hidden and is still reflected in the order book.`)}
Note that the full volume of the order is not hidden and is still reflected in the order book.`)}{' '}
<ExternalLink href={DocsLinks?.ICEBERG_ORDERS}>
{t('Find out more')}
</ExternalLink>{' '}
</p>
}
>
@@ -668,7 +685,7 @@ export const DealTicket = ({
subLabel={`${formatValue(
normalizedOrder.size,
market.positionDecimalPlaces
)} ${assetUnit} @ ${
)} ${baseQuote} @ ${
type === Schema.OrderType.TYPE_MARKET
? 'market'
: `${formatValue(
+2
View File
@@ -82,6 +82,8 @@ export const DocsLinks = VEGA_DOCS_URL
VALIDATOR_SCORES_REWARDS: `${VEGA_DOCS_URL}/concepts/vega-chain/validator-scores-and-rewards`,
MARKET_LIFECYCLE: `${VEGA_DOCS_URL}/concepts/trading-on-vega/market-lifecycle`,
ETH_DATA_SOURCES: `${VEGA_DOCS_URL}/concepts/trading-on-vega/data-sources#ethereum-data-sources`,
ICEBERG_ORDERS: `${VEGA_DOCS_URL}/concepts/trading-on-vega/orders#iceberg-order`,
POST_REDUCE_ONLY: `${VEGA_DOCS_URL}/concepts/trading-on-vega/orders#conditional-order-parameters`,
}
: undefined;
+5
View File
@@ -49,6 +49,11 @@ query EstimatePosition(
openVolume: $openVolume
orders: $orders
collateralAvailable: $collateralAvailable
# Everywhere in the codebase we expect price values of the underlying to have the right
# number of digits for formatting with market.decimalPlaces. By default the estimatePosition
# query will return a full value requiring formatting using asset.decimals. For consistency
# we can set this variable to true so that we can format with market.decimalPlaces
scaleLiquidationPriceToMarketDecimals: true
) {
margin {
worstCase {
+1
View File
@@ -130,6 +130,7 @@ export const EstimatePositionDocument = gql`
openVolume: $openVolume
orders: $orders
collateralAvailable: $collateralAvailable
scaleLiquidationPriceToMarketDecimals: true
) {
margin {
worstCase {
@@ -0,0 +1,85 @@
import { MockedProvider } from '@apollo/client/testing';
import type { MockedResponse } from '@apollo/client/testing';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { EstimatePositionDocument } from './__generated__/Positions';
import type { EstimatePositionQuery } from './__generated__/Positions';
import { LiquidationPrice } from './liquidation-price';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
describe('LiquidationPrice', () => {
const props = {
marketId: 'market-id',
openVolume: '100',
collateralAvailable: '1000',
decimalPlaces: 2,
};
const worstCaseOpenVolume = '200';
const bestCaseOpenVolume = '100';
const mock: MockedResponse<EstimatePositionQuery> = {
request: {
query: EstimatePositionDocument,
variables: {
marketId: props.marketId,
openVolume: props.openVolume,
collateralAvailable: props.collateralAvailable,
},
},
result: {
data: {
estimatePosition: {
margin: {
worstCase: {
maintenanceLevel: '100',
searchLevel: '100',
initialLevel: '100',
collateralReleaseLevel: '100',
},
bestCase: {
maintenanceLevel: '100',
searchLevel: '100',
initialLevel: '100',
collateralReleaseLevel: '100',
},
},
liquidation: {
worstCase: {
open_volume_only: worstCaseOpenVolume,
including_buy_orders: '100',
including_sell_orders: '100',
},
bestCase: {
open_volume_only: bestCaseOpenVolume,
including_buy_orders: '100',
including_sell_orders: '100',
},
},
},
},
},
};
it('correctly formats best and worst case values for the tooltip', async () => {
render(
<MockedProvider mocks={[mock]}>
<LiquidationPrice {...props} />
</MockedProvider>
);
expect(screen.getByText('-')).toBeInTheDocument();
const el = await screen.findByTestId('liquidation-price');
expect(el).toHaveTextContent(
addDecimalsFormatNumber(worstCaseOpenVolume, props.decimalPlaces)
);
await userEvent.hover(el);
const tooltip = within(await screen.findByRole('tooltip'));
expect(
tooltip.getByText('Worst case').nextElementSibling
).toHaveTextContent(
addDecimalsFormatNumber(worstCaseOpenVolume, props.decimalPlaces)
);
expect(tooltip.getByText('Best case').nextElementSibling).toHaveTextContent(
addDecimalsFormatNumber(bestCaseOpenVolume, props.decimalPlaces)
);
});
});
+4 -22
View File
@@ -8,20 +8,12 @@ export const LiquidationPrice = ({
openVolume,
collateralAvailable,
decimalPlaces,
formatDecimals,
}: {
marketId: string;
openVolume: string;
collateralAvailable: string;
decimalPlaces: number;
formatDecimals: number;
}) => {
// NOTE!
//
// The estimate order query API gives us the liquidation price unformatted but expecting to be converted
// using asset decimal placse.
//
// We need to convert it with asset decimals, but display it formatted with market decimals precision until the API changes.
const { data: currentData, previousData } = useEstimatePositionQuery({
variables: {
marketId,
@@ -38,21 +30,11 @@ export const LiquidationPrice = ({
return <span>-</span>;
}
let bestCase = '-';
let worstCase = '-';
let bestCase = data.estimatePosition.liquidation.bestCase.open_volume_only;
let worstCase = data.estimatePosition.liquidation.worstCase.open_volume_only;
bestCase =
data.estimatePosition?.liquidation?.bestCase.open_volume_only.replace(
/\..*/,
''
);
worstCase =
data.estimatePosition?.liquidation?.worstCase.open_volume_only.replace(
/\..*/,
''
);
worstCase = addDecimalsFormatNumber(worstCase, decimalPlaces, formatDecimals);
bestCase = addDecimalsFormatNumber(bestCase, decimalPlaces, formatDecimals);
worstCase = addDecimalsFormatNumber(worstCase, decimalPlaces, decimalPlaces);
bestCase = addDecimalsFormatNumber(bestCase, decimalPlaces, decimalPlaces);
return (
<Tooltip
+1 -5
View File
@@ -339,16 +339,12 @@ export const PositionsTable = ({
if (!data) {
return '-';
}
// The estimate order query API gives us the liquidation price unformatted but expecting
// conversion using asset decimals. We need to convert it with asset decimals, but format
// it with market decimals precision until the API changes.
return (
<LiquidationPrice
marketId={data.marketId}
openVolume={data.openVolume}
collateralAvailable={data.totalBalance}
decimalPlaces={data.assetDecimals}
formatDecimals={data.marketDecimalPlaces}
decimalPlaces={data.marketDecimalPlaces}
/>
);
},
@@ -12,10 +12,15 @@ subscription ProposalEvent($partyId: ID!) {
}
}
fragment UpdateNetworkParameterProposal on Proposal {
fragment OnProposalFragment on Proposal {
id
state
datetime
rationale {
title
description
}
rejectionReason
terms {
enactmentDatetime
change {
@@ -26,9 +31,9 @@ fragment UpdateNetworkParameterProposal on Proposal {
}
}
subscription OnUpdateNetworkParameters {
subscription OnProposal {
proposals {
...UpdateNetworkParameterProposal
...OnProposalFragment
}
}
@@ -13,12 +13,12 @@ export type ProposalEventSubscriptionVariables = Types.Exact<{
export type ProposalEventSubscription = { __typename?: 'Subscription', proposals: { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null } };
export type UpdateNetworkParameterProposalFragment = { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'NewSpotMarket' } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateMarketState' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } | { __typename?: 'UpdateReferralProgram' } | { __typename?: 'UpdateSpotMarket' } | { __typename?: 'UpdateVolumeDiscountProgram' } } };
export type OnProposalFragmentFragment = { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'NewSpotMarket' } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateMarketState' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } | { __typename?: 'UpdateReferralProgram' } | { __typename?: 'UpdateSpotMarket' } | { __typename?: 'UpdateVolumeDiscountProgram' } } };
export type OnUpdateNetworkParametersSubscriptionVariables = Types.Exact<{ [key: string]: never; }>;
export type OnProposalSubscriptionVariables = Types.Exact<{ [key: string]: never; }>;
export type OnUpdateNetworkParametersSubscription = { __typename?: 'Subscription', proposals: { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'NewSpotMarket' } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateMarketState' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } | { __typename?: 'UpdateReferralProgram' } | { __typename?: 'UpdateSpotMarket' } | { __typename?: 'UpdateVolumeDiscountProgram' } } } };
export type OnProposalSubscription = { __typename?: 'Subscription', proposals: { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'NewSpotMarket' } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateMarketState' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } | { __typename?: 'UpdateReferralProgram' } | { __typename?: 'UpdateSpotMarket' } | { __typename?: 'UpdateVolumeDiscountProgram' } } } };
export type ProposalOfMarketQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
@@ -64,11 +64,16 @@ export const ProposalEventFieldsFragmentDoc = gql`
errorDetails
}
`;
export const UpdateNetworkParameterProposalFragmentDoc = gql`
fragment UpdateNetworkParameterProposal on Proposal {
export const OnProposalFragmentFragmentDoc = gql`
fragment OnProposalFragment on Proposal {
id
state
datetime
rationale {
title
description
}
rejectionReason
terms {
enactmentDatetime
change {
@@ -109,35 +114,35 @@ export function useProposalEventSubscription(baseOptions: Apollo.SubscriptionHoo
}
export type ProposalEventSubscriptionHookResult = ReturnType<typeof useProposalEventSubscription>;
export type ProposalEventSubscriptionResult = Apollo.SubscriptionResult<ProposalEventSubscription>;
export const OnUpdateNetworkParametersDocument = gql`
subscription OnUpdateNetworkParameters {
export const OnProposalDocument = gql`
subscription OnProposal {
proposals {
...UpdateNetworkParameterProposal
...OnProposalFragment
}
}
${UpdateNetworkParameterProposalFragmentDoc}`;
${OnProposalFragmentFragmentDoc}`;
/**
* __useOnUpdateNetworkParametersSubscription__
* __useOnProposalSubscription__
*
* To run a query within a React component, call `useOnUpdateNetworkParametersSubscription` and pass it any options that fit your needs.
* When your component renders, `useOnUpdateNetworkParametersSubscription` returns an object from Apollo Client that contains loading, error, and data properties
* To run a query within a React component, call `useOnProposalSubscription` and pass it any options that fit your needs.
* When your component renders, `useOnProposalSubscription` 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 subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useOnUpdateNetworkParametersSubscription({
* const { data, loading, error } = useOnProposalSubscription({
* variables: {
* },
* });
*/
export function useOnUpdateNetworkParametersSubscription(baseOptions?: Apollo.SubscriptionHookOptions<OnUpdateNetworkParametersSubscription, OnUpdateNetworkParametersSubscriptionVariables>) {
export function useOnProposalSubscription(baseOptions?: Apollo.SubscriptionHookOptions<OnProposalSubscription, OnProposalSubscriptionVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useSubscription<OnUpdateNetworkParametersSubscription, OnUpdateNetworkParametersSubscriptionVariables>(OnUpdateNetworkParametersDocument, options);
return Apollo.useSubscription<OnProposalSubscription, OnProposalSubscriptionVariables>(OnProposalDocument, options);
}
export type OnUpdateNetworkParametersSubscriptionHookResult = ReturnType<typeof useOnUpdateNetworkParametersSubscription>;
export type OnUpdateNetworkParametersSubscriptionResult = Apollo.SubscriptionResult<OnUpdateNetworkParametersSubscription>;
export type OnProposalSubscriptionHookResult = ReturnType<typeof useOnProposalSubscription>;
export type OnProposalSubscriptionResult = Apollo.SubscriptionResult<OnProposalSubscription>;
export const ProposalOfMarketDocument = gql`
query ProposalOfMarket($marketId: ID!) {
proposal(id: $marketId) {
@@ -3,7 +3,7 @@ export * from './use-proposal-event';
export * from './use-vega-transaction';
export * from './use-proposal-submit';
export * from './use-update-proposal';
export * from './use-update-network-paramaters-toasts';
export * from './use-proposal-toasts';
export * from './use-successor-market-proposal-details';
export * from './use-new-transfer-proposal-details';
export * from './use-cancel-transfer-proposal-details';
@@ -0,0 +1,273 @@
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { ProposalRejectionReason } from '@vegaprotocol/types';
import {
ProposalChangeMapping,
ProposalState,
ProposalStateMapping,
} from '@vegaprotocol/types';
import type { ReactNode } from 'react';
import {
PROPOSAL_STATES_TO_TOAST,
ProposalToastContent,
useProposalToasts,
} from './use-proposal-toasts';
import { useToasts } from '@vegaprotocol/ui-toolkit';
import { waitFor, renderHook, render } from '@testing-library/react';
import {
OnProposalDocument,
type OnProposalFragmentFragment,
type OnProposalSubscription,
} from './__generated__/Proposal';
import sample from 'lodash/sample';
const renderUseProposalToasts = (mocks?: MockedResponse[]) => {
const wrapper = ({ children }: { children: ReactNode }) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
return renderHook(() => useProposalToasts(), { wrapper });
};
type ProposalChange = OnProposalFragmentFragment['terms']['change'];
const NEW_MARKET_CHANGE: ProposalChange = { __typename: 'NewMarket' };
const UPDATE_MARKET_CHANGE: ProposalChange = { __typename: 'UpdateMarket' };
const UPDATE_NETWORK_PARAMETER_CHANGE: ProposalChange = {
__typename: 'UpdateNetworkParameter',
networkParameter: {
__typename: 'NetworkParameter',
key: 'abc.def',
value: '123',
},
};
const NEW_ASSET_CHANGE: ProposalChange = { __typename: 'NewAsset' };
const UPDATE_ASSET_CHANGE: ProposalChange = { __typename: 'UpdateAsset' };
const NEW_FREEFORM_CHANGE: ProposalChange = { __typename: 'NewFreeform' };
const NEW_TRANSFER_CHANGE: ProposalChange = { __typename: 'NewTransfer' };
const CANCEL_TRANSFER_CHANGE: ProposalChange = { __typename: 'CancelTransfer' };
const UPDATE_MARKET_STATE_CHANGE: ProposalChange = {
__typename: 'UpdateMarketState',
};
const NEW_SPOT_MARKET_CHANGE: ProposalChange = { __typename: 'NewSpotMarket' };
const UPDATE_SPOT_MARKET_CHANGE: ProposalChange = {
__typename: 'UpdateSpotMarket',
};
const UPDATE_VOLUME_DISCOUNT_PROGRAM_CHANGE: ProposalChange = {
__typename: 'UpdateVolumeDiscountProgram',
};
const UPDATE_REFERRAL_PROGRAM_CHANGE: ProposalChange = {
__typename: 'UpdateReferralProgram',
};
const GenericToastProposals = [
NEW_MARKET_CHANGE,
UPDATE_MARKET_CHANGE,
NEW_ASSET_CHANGE,
UPDATE_ASSET_CHANGE,
NEW_FREEFORM_CHANGE,
NEW_TRANSFER_CHANGE,
CANCEL_TRANSFER_CHANGE,
UPDATE_MARKET_STATE_CHANGE,
NEW_SPOT_MARKET_CHANGE,
UPDATE_SPOT_MARKET_CHANGE,
UPDATE_VOLUME_DISCOUNT_PROGRAM_CHANGE,
UPDATE_REFERRAL_PROGRAM_CHANGE,
];
const generateProposal = (
title: string,
state: ProposalState = ProposalState.STATE_OPEN,
change: ProposalChange = { __typename: undefined },
rejectionReason: ProposalRejectionReason | null = null
): OnProposalFragmentFragment => ({
__typename: 'Proposal',
id: Math.random().toString(),
datetime: Math.random().toString(),
rationale: {
title,
description: '',
},
rejectionReason,
state,
terms: {
__typename: 'ProposalTerms',
enactmentDatetime: '2022-12-09T14:40:38Z',
change,
},
});
const INITIAL = useToasts.getState();
const clear = () => {
useToasts.setState(INITIAL);
};
describe('useProposalToasts', () => {
beforeEach(clear);
afterAll(clear);
it.each(PROPOSAL_STATES_TO_TOAST)(
'renders toast for %s proposal',
async (state) => {
const mockProposal: MockedResponse<OnProposalSubscription> = {
request: {
query: OnProposalDocument,
},
result: {
data: {
proposals: generateProposal(
'Things to change',
state,
NEW_MARKET_CHANGE
),
},
},
};
const { result } = renderUseProposalToasts([mockProposal]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(1);
});
}
);
const IGNORE_STATES = Object.keys(ProposalState).filter((state) => {
return !PROPOSAL_STATES_TO_TOAST.includes(state as ProposalState);
}) as ProposalState[];
it.each(IGNORE_STATES)(
'does not render toast for %s proposal',
async (state) => {
const mockFailedProposal: MockedResponse<OnProposalSubscription> = {
request: {
query: OnProposalDocument,
},
result: {
data: {
proposals: generateProposal('Things to change but ignored', state),
},
},
};
const { result } = renderUseProposalToasts([mockFailedProposal]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(0);
});
}
);
it('does not render toast for empty proposal', async () => {
const error = console.error;
console.error = () => {
/* no op */
};
const mockEmptyProposal: MockedResponse<OnProposalSubscription> = {
request: {
query: OnProposalDocument,
},
result: {
data: {
proposals: undefined as unknown as OnProposalFragmentFragment,
},
},
};
const { result } = renderUseProposalToasts([mockEmptyProposal]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(0);
});
console.error = error;
});
const allTypes: [
ProposalChange['__typename'],
ProposalChange,
ProposalState?
][] = [...GenericToastProposals, UPDATE_NETWORK_PARAMETER_CHANGE].map(
(ch) => [ch.__typename, ch, sample(PROPOSAL_STATES_TO_TOAST)]
);
it.each(allTypes)(
'renders toast for %s proposal',
async (_, change, state) => {
const proposalData = generateProposal('Things to change', state, change);
const mockProposal: MockedResponse<OnProposalSubscription> = {
request: {
query: OnProposalDocument,
},
result: {
data: {
proposals: proposalData,
},
},
};
const { result } = renderUseProposalToasts([mockProposal]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(1);
});
}
);
});
describe('ProposalToastContent', () => {
const genericTypes: [
ProposalChange['__typename'],
ProposalChange,
ProposalState?
][] = GenericToastProposals.map((ch) => [
ch.__typename,
ch,
sample(PROPOSAL_STATES_TO_TOAST),
]);
it.each(genericTypes)(
'renders generic toast content for %s',
async (_, change, state) => {
const proposalData = generateProposal('Things to change', state, change);
const { container } = render(
<ProposalToastContent proposal={proposalData} />
);
const title = container.querySelector(
'[data-testid="proposal-toast-title"]'
);
const rationale = container.querySelector(
'[data-testid="proposal-toast-rationale-title"]'
);
const expectedChangeName = change.__typename
? ProposalChangeMapping[change.__typename]
: '';
const expectedState =
ProposalStateMapping[proposalData.state].toLocaleLowerCase();
expect(title).toHaveTextContent(
`${expectedChangeName} proposal ${expectedState}`
);
expect(rationale).toHaveTextContent('Things to change');
}
);
it('renders specific content for UpdateNetworkParameter proposal', () => {
const proposalData = generateProposal(
'Things to change',
ProposalState.STATE_OPEN,
UPDATE_NETWORK_PARAMETER_CHANGE
);
const { container } = render(
<ProposalToastContent proposal={proposalData} />
);
const title = container.querySelector(
'[data-testid="proposal-toast-title"]'
);
const rationale = container.querySelector(
'[data-testid="proposal-toast-rationale-title"]'
);
const param = container.querySelector(
'[data-testid="proposal-toast-network-param"]'
);
expect(title).toHaveTextContent('Update network parameter proposal open');
expect(rationale).toBe(null);
expect(param).toHaveTextContent('Update abc.def to 123');
});
});
@@ -0,0 +1,136 @@
import { DApp, TOKEN_PROPOSAL, useLinks } from '@vegaprotocol/environment';
import { getDateTimeFormat } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
ProposalChangeMapping,
ProposalRejectionReasonMapping,
ProposalStateMapping,
} from '@vegaprotocol/types';
import { ProposalState } from '@vegaprotocol/types';
import type { Toast } from '@vegaprotocol/ui-toolkit';
import { ToastHeading } from '@vegaprotocol/ui-toolkit';
import { useToasts } from '@vegaprotocol/ui-toolkit';
import { ExternalLink, Intent } from '@vegaprotocol/ui-toolkit';
import { useCallback } from 'react';
import {
useOnProposalSubscription,
type OnProposalFragmentFragment,
} from './__generated__/Proposal';
export const PROPOSAL_STATES_TO_TOAST = [
ProposalState.STATE_DECLINED,
ProposalState.STATE_ENACTED,
ProposalState.STATE_OPEN,
ProposalState.STATE_PASSED,
];
const CLOSE_AFTER = 0;
type Proposal = OnProposalFragmentFragment;
const ProposalDetails = ({ proposal }: { proposal: Proposal }) => {
const change = proposal.terms.change;
switch (change.__typename) {
case 'UpdateNetworkParameter':
return <UpdateNetworkParameterDetails proposal={proposal} />;
default:
// generic details: rationale title and rejection reason if rejected
return (
<>
{proposal.rationale.title ? (
<p data-testid="proposal-toast-rationale-title" className="italic">
{proposal.rationale.title}
</p>
) : null}
{proposal.state === ProposalState.STATE_REJECTED &&
proposal.rejectionReason ? (
<p data-testid="proposal-toast-rejection-reason">
{t('Rejection reason:')}{' '}
{ProposalRejectionReasonMapping[proposal.rejectionReason]}
</p>
) : null}
</>
);
}
};
const UpdateNetworkParameterDetails = ({
proposal,
}: {
proposal: Proposal;
}) => {
const change = proposal.terms.change;
if (change.__typename !== 'UpdateNetworkParameter') return null;
return (
<p data-testid="proposal-toast-network-param" className="italic">
'{t('Update ')}
<span className="break-all">{change.networkParameter.key}</span>
{t(' to ')}
<span>{change.networkParameter.value}</span>'
</p>
);
};
export const ProposalToastContent = ({ proposal }: { proposal: Proposal }) => {
const tokenLink = useLinks(DApp.Governance);
const change = proposal.terms.change;
// Generates toast's title,
// e.g. Update market proposal enacted, New transfer proposal open, ...
const title = t('%s proposal %s', [
change.__typename ? ProposalChangeMapping[change.__typename] : 'Unknown',
ProposalStateMapping[proposal.state].toLowerCase(),
]);
const enactment = Date.parse(proposal.terms.enactmentDatetime);
return (
<div>
<ToastHeading data-testid="proposal-toast-title">{title}</ToastHeading>
<ProposalDetails proposal={proposal} />
{!isNaN(enactment) && (
<p>
{t('Enactment date:')} {getDateTimeFormat().format(enactment)}
</p>
)}
<p>
<ExternalLink
href={tokenLink(TOKEN_PROPOSAL).replace(':id', proposal?.id || '')}
>
{t('View proposal details')}
</ExternalLink>
</p>
</div>
);
};
export const useProposalToasts = () => {
const { setToast, remove } = useToasts((store) => ({
setToast: store.setToast,
remove: store.remove,
}));
const fromProposal = useCallback(
(proposal: Proposal): Toast => {
const id = `proposal-toast-${proposal.id}`;
return {
id,
intent: Intent.Warning,
content: <ProposalToastContent proposal={proposal} />,
onClose: () => {
remove(id);
},
closeAfter: CLOSE_AFTER,
};
},
[remove]
);
return useOnProposalSubscription({
onData: ({ data }) => {
const proposal = data.data?.proposals;
if (!proposal || !proposal.terms.change.__typename) return;
if (PROPOSAL_STATES_TO_TOAST.includes(proposal.state)) {
setToast(fromProposal(proposal));
}
},
});
};
@@ -1,96 +0,0 @@
import { DApp, TOKEN_PROPOSAL, useLinks } from '@vegaprotocol/environment';
import { getDateTimeFormat } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import type { UpdateNetworkParameter } from '@vegaprotocol/types';
import { ProposalStateMapping } from '@vegaprotocol/types';
import { ProposalState } from '@vegaprotocol/types';
import type { Toast } from '@vegaprotocol/ui-toolkit';
import { ToastHeading } from '@vegaprotocol/ui-toolkit';
import { useToasts } from '@vegaprotocol/ui-toolkit';
import { ExternalLink, Intent } from '@vegaprotocol/ui-toolkit';
import { useCallback } from 'react';
import type { UpdateNetworkParameterProposalFragment } from './__generated__/Proposal';
import { useOnUpdateNetworkParametersSubscription } from './__generated__/Proposal';
export const PROPOSAL_STATES_TO_TOAST = [
ProposalState.STATE_DECLINED,
ProposalState.STATE_ENACTED,
ProposalState.STATE_OPEN,
ProposalState.STATE_PASSED,
];
const CLOSE_AFTER = 0;
type Proposal = UpdateNetworkParameterProposalFragment;
const UpdateNetworkParameterToastContent = ({
proposal,
}: {
proposal: Proposal;
}) => {
const tokenLink = useLinks(DApp.Governance);
const change = proposal.terms.change as UpdateNetworkParameter;
const title = t('Network change proposal %s').replace(
'%s',
ProposalStateMapping[proposal.state].toLowerCase()
);
const enactment = Date.parse(proposal.terms.enactmentDatetime);
return (
<div>
<ToastHeading>{title}</ToastHeading>
<p className="italic">
'{t('Update ')}
<span className="break-all">{change.networkParameter.key}</span>
{t(' to ')}
<span>{change.networkParameter.value}</span>'
</p>
{!isNaN(enactment) && (
<p>
{t('Enactment date:')} {getDateTimeFormat().format(enactment)}
</p>
)}
<p>
<ExternalLink
href={tokenLink(TOKEN_PROPOSAL).replace(':id', proposal?.id || '')}
>
{t('View proposal details')}
</ExternalLink>
</p>
</div>
);
};
export const useUpdateNetworkParametersToasts = () => {
const { setToast, remove } = useToasts((store) => ({
setToast: store.setToast,
remove: store.remove,
}));
const fromProposal = useCallback(
(proposal: Proposal): Toast => {
const id = `update-network-param-proposal-${proposal.id}`;
return {
id: `update-network-param-proposal-${proposal.id}`,
intent: Intent.Warning,
content: <UpdateNetworkParameterToastContent proposal={proposal} />,
onClose: () => {
remove(id);
},
closeAfter: CLOSE_AFTER,
};
},
[remove]
);
return useOnUpdateNetworkParametersSubscription({
onData: ({ data }) => {
// note proposals is poorly named, it is actually a single proposal
const proposal = data.data?.proposals;
if (!proposal) return;
if (proposal.terms.change.__typename !== 'UpdateNetworkParameter') return;
// if one of the following states show a toast
if (PROPOSAL_STATES_TO_TOAST.includes(proposal.state)) {
setToast(fromProposal(proposal));
}
},
});
};
@@ -1,168 +0,0 @@
import merge from 'lodash/merge';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import { ProposalState } from '@vegaprotocol/types';
import type { ReactNode } from 'react';
import {
PROPOSAL_STATES_TO_TOAST,
useUpdateNetworkParametersToasts,
} from './use-update-network-paramaters-toasts';
import type {
UpdateNetworkParameterProposalFragment,
OnUpdateNetworkParametersSubscription,
} from './__generated__/Proposal';
import { OnUpdateNetworkParametersDocument } from './__generated__/Proposal';
import { useToasts } from '@vegaprotocol/ui-toolkit';
import { waitFor, renderHook } from '@testing-library/react';
const render = (mocks?: MockedResponse[]) => {
const wrapper = ({ children }: { children: ReactNode }) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
return renderHook(() => useUpdateNetworkParametersToasts(), { wrapper });
};
const generateUpdateNetworkParametersProposal = (
key: string,
value: string,
state: ProposalState = ProposalState.STATE_OPEN
): UpdateNetworkParameterProposalFragment => ({
__typename: 'Proposal',
id: Math.random().toString(),
datetime: Math.random().toString(),
state,
terms: {
__typename: 'ProposalTerms',
enactmentDatetime: '2022-12-09T14:40:38Z',
change: {
__typename: 'UpdateNetworkParameter',
networkParameter: {
__typename: 'NetworkParameter',
key,
value,
},
},
},
});
const INITIAL = useToasts.getState();
const clear = () => {
useToasts.setState(INITIAL);
};
describe('useUpdateNetworkParametersToasts', () => {
beforeEach(clear);
afterAll(clear);
it.each(PROPOSAL_STATES_TO_TOAST)(
'toasts for %s network param proposals',
async (state) => {
const mockOpenProposal: MockedResponse<OnUpdateNetworkParametersSubscription> =
{
request: {
query: OnUpdateNetworkParametersDocument,
},
result: {
data: {
proposals: generateUpdateNetworkParametersProposal(
'abc.def',
'123.456',
state
),
},
},
};
const { result } = render([mockOpenProposal]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(1);
});
}
);
const IGNORE_STATES = Object.keys(ProposalState).filter((state) => {
return !PROPOSAL_STATES_TO_TOAST.includes(state as ProposalState);
}) as ProposalState[];
it.each(IGNORE_STATES)('does not toast for %s proposals', async (state) => {
const mockFailedProposal: MockedResponse<OnUpdateNetworkParametersSubscription> =
{
request: {
query: OnUpdateNetworkParametersDocument,
},
result: {
data: {
proposals: generateUpdateNetworkParametersProposal(
'abc.def',
'123.456',
state
),
},
},
};
const { result } = render([mockFailedProposal]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(0);
});
});
it('does not return toast for empty propsal', async () => {
const error = console.error;
console.error = () => {
/* no op */
};
const mockEmptyProposal: MockedResponse<OnUpdateNetworkParametersSubscription> =
{
request: {
query: OnUpdateNetworkParametersDocument,
},
result: {
data: {
proposals:
undefined as unknown as UpdateNetworkParameterProposalFragment,
},
},
};
const { result } = render([mockEmptyProposal]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(0);
});
console.error = error;
});
it('does not return toast for wrong proposal type', async () => {
const wrongProposalType = merge(
generateUpdateNetworkParametersProposal('a', 'b'),
{
terms: {
change: {
__typename: 'NewMarket',
},
},
}
);
const mockWrongProposalType: MockedResponse<OnUpdateNetworkParametersSubscription> =
{
request: {
query: OnUpdateNetworkParametersDocument,
},
result: {
data: {
proposals: wrongProposalType,
},
},
};
const { result } = render([mockWrongProposalType]);
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(useToasts.getState().count).toBe(0);
});
});
});
+36 -1
View File
@@ -3387,6 +3387,8 @@ export type Party = {
transfersConnection?: Maybe<TransferConnection>;
/** The current reward vesting summary of the party for the last epoch */
vestingBalancesSummary: PartyVestingBalancesSummary;
/** The current statistics about a party's vesting rewards for the last epoch */
vestingStats?: Maybe<PartyVestingStats>;
/** All votes on proposals in the Vega network by the given party */
votesConnection?: Maybe<ProposalVoteConnection>;
/** The list of all withdrawals initiated by the party */
@@ -3502,6 +3504,7 @@ export type PartytradesConnectionArgs = {
/** Represents a party on Vega, could be an ethereum wallet address in the future */
export type PartytransfersConnectionArgs = {
direction?: InputMaybe<TransferDirection>;
isReward?: InputMaybe<Scalars['Boolean']>;
pagination?: InputMaybe<Pagination>;
};
@@ -3616,6 +3619,15 @@ export type PartyVestingBalancesSummary = {
vestingBalances?: Maybe<Array<PartyVestingBalance>>;
};
/** Statistics about a party's vesting rewards */
export type PartyVestingStats = {
__typename?: 'PartyVestingStats';
/** Epoch for which the statistics are valid */
epochSeq: Scalars['Int'];
/** The reward bonus multiplier */
rewardBonusMultiplier: Scalars['String'];
};
/** Create an order linked to an index rather than a price */
export type PeggedOrder = {
__typename?: 'PeggedOrder';
@@ -4905,6 +4917,7 @@ export type QuerytransferArgs = {
/** Queries allow a caller to read data and filter data via GraphQL. */
export type QuerytransfersConnectionArgs = {
direction?: InputMaybe<TransferDirection>;
isReward?: InputMaybe<Scalars['Boolean']>;
pagination?: InputMaybe<Pagination>;
partyId?: InputMaybe<Scalars['ID']>;
};
@@ -5081,6 +5094,8 @@ export type ReferralSetStats = {
rewardsFactorMultiplier: Scalars['String'];
/** The multiplier applied to the referral reward factor when calculating referral rewards due to the referrer. */
rewardsMultiplier: Scalars['String'];
/** Indicates if the referral set was eligible to be part of the referral program. */
wasEligible: Scalars['Boolean'];
};
/** Connection type for retrieving cursor-based paginated referral set statistics information */
@@ -6102,11 +6117,31 @@ export enum TransferDirection {
export type TransferEdge = {
__typename?: 'TransferEdge';
cursor: Scalars['String'];
node: Transfer;
node: TransferNode;
};
/** A transfer fee record */
export type TransferFee = {
__typename?: 'TransferFee';
/** The fee amount */
amount: Scalars['String'];
/** The epoch when this fee was paid */
epoch: Scalars['Int'];
/** Transfer ID of the transfer for which the fee was paid */
transferId: Scalars['ID'];
};
export type TransferKind = OneOffGovernanceTransfer | OneOffTransfer | RecurringGovernanceTransfer | RecurringTransfer;
/** A transfer record with the fee payments associated with the transfer */
export type TransferNode = {
__typename?: 'TransferNode';
/** The list of fee payments made */
fees?: Maybe<Array<Maybe<TransferFee>>>;
/** The transfer record */
transfer: Transfer;
};
export type TransferResponse = {
__typename?: 'TransferResponse';
/** The balances of accounts involved in the transfer */
+24
View File
@@ -3,6 +3,7 @@ import type {
GovernanceTransferKind,
GovernanceTransferType,
PeggedReference,
ProposalChange,
} from './__generated__/types';
import type { AccountType } from './__generated__/types';
import type {
@@ -299,6 +300,29 @@ export const OrderTypeMapping: {
TYPE_NETWORK: 'Network',
};
/**
* Proposal change type mapping
*/
export const ProposalChangeMapping: Record<
NonNullable<ProposalChange['__typename']>,
string
> = {
NewMarket: 'New market',
UpdateMarket: 'Update market',
UpdateNetworkParameter: 'Update network parameter',
NewAsset: 'New asset',
UpdateAsset: 'Update asset',
/* cspell:disable-next-line */
NewFreeform: 'New free-form',
NewTransfer: 'New transfer',
CancelTransfer: 'Cancel transfer',
UpdateMarketState: 'Update market state',
NewSpotMarket: 'New spot market',
UpdateSpotMarket: 'Update spot market',
UpdateVolumeDiscountProgram: 'Update volume discount program',
UpdateReferralProgram: 'Update referral program',
};
/**
* Reason for the proposal being rejected by the core node
*/
@@ -1,4 +1,4 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { generateAccount, generateAsset } from './test-helpers';
import type { WithdrawManagerProps } from './withdraw-manager';
@@ -57,10 +57,18 @@ describe('WithdrawManager', () => {
);
it('calls submit if valid form submission', async () => {
// 1002-WITH-002
// 1002-WITH-003
const { container } = render(generateJsx(props));
await act(async () => {
await submitValid(container);
});
const select = container.querySelector('select[name="asset"]') as Element;
await userEvent.selectOptions(select, props.assets[0].id);
await userEvent.clear(screen.getByLabelText('To (Ethereum address)'));
await userEvent.type(
screen.getByLabelText('To (Ethereum address)'),
ethereumAddress
);
await userEvent.type(screen.getByLabelText('Amount'), '0.01');
await userEvent.click(screen.getByTestId('submit-withdrawal'));
expect(props.submit).toHaveBeenCalledWith({
amount: '1000',
asset: props.assets[0].id,
@@ -70,58 +78,56 @@ describe('WithdrawManager', () => {
});
it('validates correctly', async () => {
render(generateJsx(props));
// 1002-WITH-010
// 1002-WITH-005
// 1002-WITH-008
// 1002-WITH-018
const { container } = render(generateJsx(props));
// Set other fields to be valid
fireEvent.change(screen.getByLabelText('Asset'), {
target: { value: props.assets[0].id },
});
fireEvent.change(screen.getByLabelText('To (Ethereum address)'), {
target: { value: ethereumAddress },
});
const select = container.querySelector('select[name="asset"]') as Element;
await userEvent.selectOptions(select, props.assets[0].id);
expect(screen.getByTestId('connect-eth-wallet-btn')).toBeInTheDocument();
await userEvent.type(
screen.getByLabelText('To (Ethereum address)'),
ethereumAddress
);
// Min amount
fireEvent.change(screen.getByLabelText('Amount'), {
target: { value: '0.00000001' },
});
fireEvent.submit(screen.getByTestId('withdraw-form'));
await userEvent.clear(screen.getByLabelText('Amount'));
await userEvent.type(screen.getByLabelText('Amount'), '0.00000001');
await userEvent.click(screen.getByTestId('submit-withdrawal'));
expect(
await screen.findByText('Value is below minimum')
).toBeInTheDocument();
expect(props.submit).not.toBeCalled();
fireEvent.change(screen.getByLabelText('Amount'), {
target: { value: '0.00001' },
});
await userEvent.clear(screen.getByLabelText('Amount'));
await userEvent.type(screen.getByLabelText('Amount'), '0.00001');
// Max amount (balance is 1)
fireEvent.change(screen.getByLabelText('Amount'), {
target: { value: '2' },
});
fireEvent.submit(screen.getByTestId('withdraw-form'));
await userEvent.clear(screen.getByLabelText('Amount'));
await userEvent.type(screen.getByLabelText('Amount'), '2');
await userEvent.click(screen.getByTestId('submit-withdrawal'));
expect(
await screen.findByText('Insufficient amount in account')
).toBeInTheDocument();
expect(props.submit).not.toBeCalled();
});
it('can set amount using use maximum button', async () => {
// 1002-WITH-004
render(generateJsx(props));
const submitValid = async (container: HTMLElement) => {
const select = container.querySelector('select[name="asset"]') as Element;
await userEvent.selectOptions(select, props.assets[0].id);
fireEvent.change(screen.getByLabelText('To (Ethereum address)'), {
target: { value: ethereumAddress },
});
fireEvent.change(screen.getByLabelText('Amount'), {
target: { value: '0.01' },
});
fireEvent.submit(screen.getByTestId('withdraw-form'));
};
await userEvent.click(screen.getByTestId('use-maximum'));
expect(screen.getByTestId('amount-input')).toHaveValue(1);
});
it('shows withdraw delay notification if amount greater than threshold', async () => {
render(generateJsx(props));
fireEvent.change(screen.getByLabelText('Amount'), {
target: { value: '1001' },
});
await userEvent.type(screen.getByLabelText('Amount'), '1001');
expect(
await screen.findByTestId('amount-withdrawal-delay-notification')
).toBeInTheDocument();
@@ -130,9 +136,7 @@ describe('WithdrawManager', () => {
it('shows withdraw delay notification if threshold is 0', async () => {
withdrawAsset.threshold = new BigNumber(0);
render(generateJsx(props));
fireEvent.change(screen.getByLabelText('Amount'), {
target: { value: '0.01' },
});
await userEvent.type(screen.getByLabelText('Amount'), '0.01');
expect(
await screen.findByTestId('withdrawals-delay-notification')
).toBeInTheDocument();
+1 -1
View File
@@ -71,7 +71,7 @@
"jsondiffpatch": "^0.4.1",
"lodash": "^4.17.21",
"next": "13.3.0",
"pennant": "1.13.4",
"pennant": "1.14.0",
"react": "18.2.0",
"react-copy-to-clipboard": "^5.0.4",
"react-dom": "18.2.0",
+4 -4
View File
@@ -20500,10 +20500,10 @@ pend@~1.2.0:
resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50"
integrity sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==
pennant@1.13.4:
version "1.13.4"
resolved "https://registry.yarnpkg.com/pennant/-/pennant-1.13.4.tgz#33a5f3413634a2341a7b91c917f023c59ecc44c7"
integrity sha512-sqwkUiYHxmS97RY8jToMfgR9ePcEr5PWVQu9BPrhdUIa1Q/NztE36SWM5tVIsPPTx3pPIHYTNEVJm02Ubl8cZQ==
pennant@1.14.0:
version "1.14.0"
resolved "https://registry.yarnpkg.com/pennant/-/pennant-1.14.0.tgz#4100c25a6d836d6f0ff425181fb6f812f9fe5778"
integrity sha512-9H0zWzFUSbD1BlDXnHFmKwkAxXGb1xTxjkUD+RwaMygtSwPXzQEyk2ScVyMqxdcz0RuJmI5HCVmZTOjdr1NwuA==
dependencies:
"@babel/runtime" "^7.13.10"
"@d3fc/d3fc-technical-indicator" "^8.0.1"