Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbb6a42675 | ||
|
|
7cafc6e6cc | ||
|
|
cd56545042 | ||
|
|
b6e21f7265 | ||
|
|
b1979c4948 | ||
|
|
5e674b1bec |
@@ -10,7 +10,7 @@ on:
|
||||
inputs:
|
||||
console-test-branch:
|
||||
type: choice
|
||||
description: 'main: v0.73.5, develop: v0.73.5'
|
||||
description: 'main: v0.72.14, develop: v0.73.4'
|
||||
options:
|
||||
- main
|
||||
- develop
|
||||
@@ -205,7 +205,7 @@ jobs:
|
||||
# run tests
|
||||
#----------------------------------------------
|
||||
- name: Run tests
|
||||
run: CONSOLE_IMAGE_NAME=ci/trading:local poetry run pytest -v -s --numprocesses 6 --dist loadfile --durations=15
|
||||
run: CONSOLE_IMAGE_NAME=ci/trading:local poetry run pytest -v -s --numprocesses 4 --dist loadfile --durations=15
|
||||
working-directory: apps/trading/e2e
|
||||
#----------------------------------------------
|
||||
# upload traces
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useAssetDataProvider } from '@vegaprotocol/assets';
|
||||
import { addDecimalsFixedFormatNumber } from '@vegaprotocol/utils';
|
||||
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
|
||||
import { AssetLink } from '../links';
|
||||
|
||||
export type AssetBalanceProps = {
|
||||
@@ -23,7 +23,7 @@ const AssetBalance = ({
|
||||
|
||||
const label =
|
||||
!loading && asset && asset.decimals
|
||||
? addDecimalsFixedFormatNumber(price, asset.decimals)
|
||||
? addDecimalsFormatNumber(price, asset.decimals)
|
||||
: price;
|
||||
|
||||
return (
|
||||
|
||||
@@ -120,6 +120,6 @@ describe('Order TX Summary component', () => {
|
||||
// After fetch renders formatted price and asset quotename
|
||||
expect(await res.findByText('3.33')).toBeInTheDocument();
|
||||
expect(await res.findByText('TEST')).toBeInTheDocument();
|
||||
expect(await res.getByText('0.10')).toBeInTheDocument();
|
||||
expect(await res.findByText('0.1')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,7 +64,7 @@ describe('Price in Market component', () => {
|
||||
|
||||
it('Renders the formatted price when market data is fetched, using market decimals by default', async () => {
|
||||
const res = render(renderComponent('100', '123', [fullMock]));
|
||||
expect(await res.findByText('1.00')).toBeInTheDocument();
|
||||
expect(await res.findByText('1')).toBeInTheDocument();
|
||||
expect(await res.findByText('dai')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -69,6 +69,6 @@ describe('Size in Market component', () => {
|
||||
|
||||
it('Renders the formatted size when market data is fetched', async () => {
|
||||
const res = render(renderComponent('100', '123', [fullMock]));
|
||||
expect(await res.findByText('1.00')).toBeInTheDocument();
|
||||
expect(await res.findByText('1')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,14 +3,14 @@ import { formatNumber } from './format-number';
|
||||
|
||||
describe('formatNumber and formatNumberPercentage', () => {
|
||||
it.each([
|
||||
{ v: new BigNumber(123), d: 3, o: '123.00' },
|
||||
{ v: new BigNumber(123), d: 3, o: '123.000' },
|
||||
{ v: new BigNumber(123.123), d: 3, o: '123.123' },
|
||||
{ v: new BigNumber(123.123), d: 6, o: '123.123' },
|
||||
{ v: new BigNumber(123.123), d: 6, o: '123.123000' },
|
||||
{ v: new BigNumber(123.123), d: 0, o: '123' },
|
||||
{ v: new BigNumber(123), d: undefined, o: '123.00' }, // it default to 2 decimal places
|
||||
{ v: new BigNumber(30000), d: undefined, o: '30,000.00' },
|
||||
{ v: new BigNumber(3.000001), d: undefined, o: '3.000001' },
|
||||
])(`formats given number with decimals correctly`, ({ v, d, o }) => {
|
||||
])(`formatNumber($v, $d) -> $o`, ({ v, d, o }) => {
|
||||
expect(formatNumber(v, d)).toStrictEqual(o);
|
||||
});
|
||||
});
|
||||
|
||||
+1
-20
@@ -8,7 +8,7 @@ import {
|
||||
networkParamsQueryMock,
|
||||
nextWeek,
|
||||
} from '../../test-helpers/mocks';
|
||||
import { CompactVotes, VoteBreakdown } from './vote-breakdown';
|
||||
import { VoteBreakdown } from './vote-breakdown';
|
||||
import type { ProposalQuery } from '../../proposal/__generated__/Proposal';
|
||||
import type { MockedResponse } from '@apollo/client/testing';
|
||||
import {
|
||||
@@ -346,22 +346,3 @@ describe('VoteBreakdown', () => {
|
||||
expect(style.width).toBe(`${expectedProgress}%`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CompactVotes', () => {
|
||||
it.each([
|
||||
[0, '0'],
|
||||
[1, '1'],
|
||||
[12, '12'],
|
||||
[123, '123'],
|
||||
[1234, '1.2K'],
|
||||
[12345, '12.3K'],
|
||||
[123456, '123.5K'],
|
||||
[1234567, '1.2M'],
|
||||
[12345678, '12.3M'],
|
||||
[123456789, '123.5M'],
|
||||
[1234567890, '1.2B'],
|
||||
])('compacts %s to %s', (input, output) => {
|
||||
const { getByTestId } = render(<CompactVotes number={BigNumber(input)} />);
|
||||
expect(getByTestId('compact-number').textContent).toBe(output);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,21 +3,11 @@ import BigNumber from 'bignumber.js';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useVoteInformation } from '../../hooks';
|
||||
import { Icon, Tooltip } from '@vegaprotocol/ui-toolkit';
|
||||
import { formatNumber } from '@vegaprotocol/utils';
|
||||
import { formatNumber, toBigNum } from '@vegaprotocol/utils';
|
||||
import { ProposalState } from '@vegaprotocol/types';
|
||||
import type { ReactNode } from 'react';
|
||||
import type { ProposalFieldsFragment } from '../../proposals/__generated__/Proposals';
|
||||
import type { ProposalQuery } from '../../proposal/__generated__/Proposal';
|
||||
import { CompactNumber } from '@vegaprotocol/react-helpers';
|
||||
|
||||
export const CompactVotes = ({ number }: { number: BigNumber }) => (
|
||||
<CompactNumber
|
||||
number={number}
|
||||
decimals={number.isGreaterThan(1000) ? 1 : 0}
|
||||
compactAbove={1000}
|
||||
compactDisplay="short"
|
||||
/>
|
||||
);
|
||||
|
||||
interface VoteBreakdownProps {
|
||||
proposal: ProposalFieldsFragment | ProposalQuery['proposal'];
|
||||
@@ -208,7 +198,10 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
|
||||
)}
|
||||
>
|
||||
<button>
|
||||
<CompactVotes number={yesEquityLikeShareWeight} />
|
||||
{yesEquityLikeShareWeight
|
||||
.dividedBy(toBigNum(10 ** 6, 0))
|
||||
.toFixed(1)}
|
||||
M
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span>
|
||||
@@ -233,7 +226,10 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
|
||||
)}
|
||||
>
|
||||
<button>
|
||||
<CompactVotes number={noEquityLikeShareWeight} />
|
||||
{noEquityLikeShareWeight
|
||||
.dividedBy(toBigNum(10 ** 6, 0))
|
||||
.toFixed(1)}
|
||||
M
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span>
|
||||
@@ -283,7 +279,10 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
|
||||
)}
|
||||
>
|
||||
<button>
|
||||
<CompactVotes number={totalEquityLikeShareWeight} />
|
||||
{totalEquityLikeShareWeight
|
||||
.dividedBy(toBigNum(10 ** 6, 0))
|
||||
.toFixed(1)}
|
||||
M
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span>
|
||||
@@ -322,7 +321,7 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
|
||||
<span>{t('tokenVotesFor')}:</span>
|
||||
<Tooltip description={formatNumber(yesTokens, defaultDP)}>
|
||||
<button data-testid="num-votes-for">
|
||||
<CompactVotes number={yesTokens} />
|
||||
{yesTokens.dividedBy(toBigNum(10 ** 6, 0)).toFixed(1)}M
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span>
|
||||
@@ -342,7 +341,7 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
|
||||
<span>{t('tokenVotesAgainst')}:</span>
|
||||
<Tooltip description={formatNumber(noTokens, defaultDP)}>
|
||||
<button data-testid="num-votes-against">
|
||||
<CompactVotes number={noTokens} />
|
||||
{noTokens.dividedBy(toBigNum(10 ** 6, 0)).toFixed(1)}M
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span>
|
||||
@@ -385,7 +384,7 @@ export const VoteBreakdown = ({ proposal }: VoteBreakdownProps) => {
|
||||
<span>{t('totalTokensVoted')}:</span>
|
||||
<Tooltip description={formatNumber(totalTokensVoted, defaultDP)}>
|
||||
<button data-testid="total-voted">
|
||||
<CompactVotes number={totalTokensVoted} />
|
||||
{totalTokensVoted.dividedBy(toBigNum(10 ** 6, 0)).toFixed(1)}M
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span data-testid="total-voted-percentage">
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
const marketInfoBtn = 'Info';
|
||||
const marketInfoSubtitle = 'accordion-title';
|
||||
const marketSummaryBlock = 'header-summary';
|
||||
const marketExpiry = 'market-expiry';
|
||||
const marketPrice = 'market-price';
|
||||
const marketChange = 'market-change';
|
||||
const marketVolume = 'market-volume';
|
||||
const marketMode = 'market-trading-mode';
|
||||
const marketSettlement = 'market-settlement-asset';
|
||||
const percentageValue = 'price-change-percentage';
|
||||
const priceChangeValue = 'price-change';
|
||||
const itemHeader = 'item-header';
|
||||
const itemValue = 'item-value';
|
||||
const marketListContent = 'popover-content';
|
||||
|
||||
describe(
|
||||
'Console - market info - live env',
|
||||
{ tags: '@live', testIsolation: true },
|
||||
() => {
|
||||
before(() => {
|
||||
cy.visit('/');
|
||||
cy.contains('Loading market data...').should('not.exist');
|
||||
cy.getByTestId('link').should('be.visible');
|
||||
cy.getByTestId('dialog-close').click();
|
||||
cy.getByTestId(marketInfoBtn).click();
|
||||
});
|
||||
const titles = ['Market data', 'Market specification', 'Market governance'];
|
||||
const subtitles = [
|
||||
'Current fees',
|
||||
'Market price',
|
||||
'Market volume',
|
||||
'Insurance pool',
|
||||
'Key details',
|
||||
'Instrument',
|
||||
'Settlement asset',
|
||||
'Metadata',
|
||||
'Risk model',
|
||||
'Risk parameters',
|
||||
'Risk factors',
|
||||
'Price monitoring bounds 1',
|
||||
'Liquidity monitoring parameters',
|
||||
'Liquidity',
|
||||
'Liquidity price range',
|
||||
'Oracle',
|
||||
'Proposal',
|
||||
];
|
||||
|
||||
it('market info titles are displayed', () => {
|
||||
cy.getByTestId('split-view-view')
|
||||
.find('.text-lg')
|
||||
.each((element, index) => {
|
||||
cy.wrap(element).should('have.text', titles[index]);
|
||||
});
|
||||
});
|
||||
|
||||
it('market info subtitles are displayed', () => {
|
||||
cy.getByTestId('popover-trigger').click();
|
||||
cy.contains('Loading market data...').should('not.exist');
|
||||
cy.contains('[data-testid="link"]', 'AAVEDAI.MF21').click();
|
||||
cy.getByTestId(marketInfoBtn).click();
|
||||
cy.getByTestId(marketInfoSubtitle).each((element, index) => {
|
||||
cy.wrap(element).should('have.text', subtitles[index]);
|
||||
});
|
||||
});
|
||||
|
||||
it('renders correctly liquidity in trading tab', () => {
|
||||
cy.getByTestId('Liquidity').click();
|
||||
cy.contains('Loading').should('not.exist');
|
||||
cy.contains('Something went wrong').should('not.exist');
|
||||
cy.contains('Application error').should('not.exist');
|
||||
cy.getByTestId('tab-liquidity').within(() => {
|
||||
cy.get('[col-id="partyId"]').eq(1).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
describe(
|
||||
'Console - market summary - live env',
|
||||
{ tags: '@live', testIsolation: true },
|
||||
() => {
|
||||
before(() => {
|
||||
cy.visit('/');
|
||||
cy.getByTestId('dialog-close').click();
|
||||
cy.getByTestId(marketSummaryBlock).should('be.visible');
|
||||
});
|
||||
|
||||
it('must display market name', () => {
|
||||
cy.getByTestId('popover-trigger').should('not.be.empty');
|
||||
});
|
||||
|
||||
it('must see market expiry', () => {
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketExpiry).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Expiry');
|
||||
cy.getByTestId(itemValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market price', () => {
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketPrice).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Price');
|
||||
cy.getByTestId(itemValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market change', () => {
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketChange).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Change (24h)');
|
||||
cy.getByTestId(percentageValue).should('not.be.empty');
|
||||
cy.getByTestId(priceChangeValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market volume', () => {
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketVolume).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Volume (24h)');
|
||||
cy.getByTestId(itemValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market mode', () => {
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketMode).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Trading mode');
|
||||
cy.getByTestId(itemValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market settlement', () => {
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketSettlement).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Settlement asset');
|
||||
cy.getByTestId(itemValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
describe(
|
||||
'Console - markets table - live env',
|
||||
{ tags: '@live', testIsolation: true },
|
||||
() => {
|
||||
beforeEach(() => {
|
||||
cy.visit('/');
|
||||
});
|
||||
|
||||
it('renders markets correctly', () => {
|
||||
cy.get('[data-testid^="market-link-"]').should('not.be.empty');
|
||||
cy.getByTestId('price').invoke('text').should('not.be.empty');
|
||||
cy.getByTestId('settlement-asset').should('not.be.empty');
|
||||
cy.getByTestId('price-change-percentage').should('not.be.empty');
|
||||
cy.getByTestId('price-change').should('not.be.empty');
|
||||
cy.getByTestId('sparkline-svg').should('be.visible');
|
||||
});
|
||||
|
||||
it('renders market list drop down', () => {
|
||||
openMarketDropDown();
|
||||
cy.getByTestId(marketListContent)
|
||||
.find('[data-testid="price"]')
|
||||
.invoke('text')
|
||||
.should('not.be.empty');
|
||||
cy.getByTestId(marketListContent)
|
||||
.find('[data-testid="trading-mode-col"]')
|
||||
.should('not.be.empty');
|
||||
cy.getByTestId(marketListContent)
|
||||
.find('[data-testid="taker-fee"]')
|
||||
.should('contain.text', '%');
|
||||
cy.getByTestId(marketListContent)
|
||||
.find('[data-testid="market-volume"]')
|
||||
.should('not.be.empty');
|
||||
cy.getByTestId(marketListContent)
|
||||
.find('[data-testid="market-name"]')
|
||||
.should('not.be.empty');
|
||||
});
|
||||
|
||||
it('Able to select market from dropdown', () => {
|
||||
cy.getByTestId('popover-trigger')
|
||||
.invoke('text')
|
||||
.then((marketName) => {
|
||||
openMarketDropDown();
|
||||
cy.get('[data-testid^=market-link]').eq(1).click();
|
||||
cy.getByTestId('popover-trigger').should('not.be.equal', marketName);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
function openMarketDropDown() {
|
||||
cy.contains('Loading...').should('not.exist');
|
||||
cy.getByTestId('link').should('be.visible');
|
||||
cy.getByTestId('dialog-close').click();
|
||||
cy.getByTestId('popover-trigger').click();
|
||||
cy.contains('Loading market data...').should('not.exist');
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import { checkSorting } from '@vegaprotocol/cypress';
|
||||
import * as Schema from '@vegaprotocol/types';
|
||||
|
||||
const liquidityTab = 'Liquidity';
|
||||
const rowSelector =
|
||||
'[data-testid="tab-liquidity"] .ag-center-cols-container .ag-row';
|
||||
const rowSelectorLiquidityActive =
|
||||
'[data-testid="tab-active"] .ag-center-cols-container .ag-row';
|
||||
const rowSelectorLiquidityInactive =
|
||||
'[data-testid="tab-inactive"] .ag-center-cols-container .ag-row';
|
||||
const marketSummaryBlock = 'header-summary';
|
||||
const itemValue = 'item-value';
|
||||
const itemHeader = 'item-header';
|
||||
const colCommitmentAmount = '[col-id="commitmentAmount"]';
|
||||
const colEquityLikeShare = '[col-id="feeShare.equityLikeShare"]';
|
||||
const colFee = '[col-id="fee"]';
|
||||
const colCommitmentAmount_1 = '[col-id="commitmentAmount_1"]';
|
||||
const colBalance = '[col-id="balance"]';
|
||||
const colStatus = '[col-id="status"]';
|
||||
const colCreatedAt = '[col-id="createdAt"] button';
|
||||
const colUpdatedAt = '[col-id="updatedAt"] button';
|
||||
|
||||
const headers = [
|
||||
'Party',
|
||||
'Status',
|
||||
'Commitment (tDAI)',
|
||||
'Obligation',
|
||||
'Fee',
|
||||
'Adjusted stake share',
|
||||
'Share',
|
||||
'Live supplied liquidity',
|
||||
'Fees accrued this epoch',
|
||||
'Live time on book',
|
||||
'Live liquidity quality score (%)',
|
||||
'Last time on the book',
|
||||
'Last fee penalty',
|
||||
'Last bond penalty',
|
||||
'Created',
|
||||
'Updated',
|
||||
];
|
||||
|
||||
describe('liquidity table - trading', { tags: '@smoke' }, () => {
|
||||
before(() => {
|
||||
cy.setOnBoardingViewed();
|
||||
cy.mockSubscription();
|
||||
cy.mockTradingPage(
|
||||
Schema.MarketState.STATE_ACTIVE,
|
||||
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
|
||||
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
|
||||
);
|
||||
cy.visit('/#/markets/market-0');
|
||||
cy.wait('@MarketData');
|
||||
cy.getByTestId(liquidityTab).click();
|
||||
cy.wait('@LiquidityProvisions');
|
||||
});
|
||||
|
||||
it('can see table headers', () => {
|
||||
// 5002-LIQP-001
|
||||
cy.getByTestId('tab-liquidity').within(($headers) => {
|
||||
cy.wrap($headers)
|
||||
.get('.ag-header-cell-text')
|
||||
.each(($header, i) => {
|
||||
cy.wrap($header).should('have.text', headers[i]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('renders liquidity table correctly', () => {
|
||||
// 5002-LIQP-002
|
||||
cy.get(rowSelector)
|
||||
.first()
|
||||
.find('[col-id="partyId"]')
|
||||
.should('have.text', '69464e…dc6f');
|
||||
|
||||
cy.get(rowSelector)
|
||||
.first()
|
||||
.find(colCommitmentAmount)
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelector)
|
||||
.first()
|
||||
.find(colEquityLikeShare)
|
||||
.should('have.text', '100.00%');
|
||||
|
||||
cy.get(rowSelector).first().find(colFee).should('have.text', '0.09%');
|
||||
|
||||
cy.get(rowSelector)
|
||||
.first()
|
||||
.find(colCommitmentAmount_1)
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelector)
|
||||
.first()
|
||||
.find(colBalance)
|
||||
.scrollIntoView()
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelector).first().find(colStatus).should('have.text', 'Active');
|
||||
|
||||
cy.get(rowSelector).first().find(colCreatedAt).should('not.be.empty');
|
||||
cy.get(rowSelector).first().find(colUpdatedAt).should('not.be.empty');
|
||||
});
|
||||
|
||||
it('liquidity status column should be sorted properly', () => {
|
||||
// 5002-LIQP-003
|
||||
const liquidityColDefault = ['Active', 'Pending'];
|
||||
const liquidityColAsc = ['Active', 'Pending'];
|
||||
const liquidityColDesc = ['Pending', 'Active'];
|
||||
checkSorting(
|
||||
'status',
|
||||
liquidityColDefault,
|
||||
liquidityColAsc,
|
||||
liquidityColDesc
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('liquidity table view', { tags: '@smoke' }, () => {
|
||||
before(() => {
|
||||
cy.setOnBoardingViewed();
|
||||
cy.mockSubscription();
|
||||
cy.mockTradingPage(
|
||||
Schema.MarketState.STATE_ACTIVE,
|
||||
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
|
||||
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
|
||||
);
|
||||
cy.visit('/#/liquidity/market-0');
|
||||
cy.wait('@LiquidityProvisions');
|
||||
});
|
||||
|
||||
it('can see header title', () => {
|
||||
// 5002-LIQP-004
|
||||
// 5002-LIQP-005
|
||||
cy.getByTestId('header-title').should(
|
||||
'contain.text',
|
||||
'BTCUSD.MF21 liquidity provision'
|
||||
);
|
||||
});
|
||||
|
||||
it('can see target stake', () => {
|
||||
// 5002-LIQP-006
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId('target-stake').within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Target stake');
|
||||
cy.getByTestId(itemValue).should('have.text', '10.00 tDAI').realHover();
|
||||
});
|
||||
});
|
||||
cy.getByTestId('tooltip-content').should(
|
||||
'contain.text',
|
||||
`The market's liquidity requirement which is derived from the maximum open interest observed over a rolling time window.The market's liquidity requirement which is derived from the maximum open interest observed over a rolling time window.`
|
||||
);
|
||||
});
|
||||
|
||||
it('can see supplied stake', () => {
|
||||
// 5002-LIQP-007
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId('supplied-stake').within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Supplied stake');
|
||||
cy.getByTestId(itemValue).should('have.text', '0.01 tDAI').realHover();
|
||||
});
|
||||
});
|
||||
cy.getByTestId('tooltip-content').should(
|
||||
'contain.text',
|
||||
'The current amount of liquidity supplied for this market.'
|
||||
);
|
||||
});
|
||||
|
||||
it('can see liquidity supplied', () => {
|
||||
// 5002-LIQP-008
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId('liquidity-supplied').within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Liquidity supplied');
|
||||
cy.getByTestId('indicator').should('be.visible');
|
||||
cy.getByTestId(itemValue).should('have.text', ' 0.10%').realHover();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('can see market id', () => {
|
||||
// 5002-LIQP-009
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId('liquidity-market-id').within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Market ID');
|
||||
cy.getByTestId(itemValue).should('have.text', 'market-0');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('can see market id', () => {
|
||||
// 5002-LIQP-010
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId('liquidity-learn-more').within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Learn more');
|
||||
cy.getByTestId(itemValue).should('have.text', 'Providing liquidity');
|
||||
cy.getByTestId('external-link')
|
||||
.should('have.attr', 'href')
|
||||
.and(
|
||||
'include',
|
||||
'https://docs.vega.xyz/testnet/concepts/liquidity/provision'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('liquidity table view', { tags: '@smoke' }, () => {
|
||||
it('can see table headers', () => {
|
||||
cy.getByTestId('tab-active').within(($headers) => {
|
||||
cy.wrap($headers)
|
||||
.get('.ag-header-cell-text')
|
||||
.each(($header, i) => {
|
||||
cy.wrap($header).should('have.text', headers[i]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('renders liquidity active table correctly', () => {
|
||||
// 5002-LIQP-011
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find('[col-id="partyId"]')
|
||||
.should('have.text', '69464e…dc6f');
|
||||
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colCommitmentAmount)
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colEquityLikeShare)
|
||||
.should('have.text', '100.00%');
|
||||
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colFee)
|
||||
.should('have.text', '0.09%');
|
||||
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colCommitmentAmount_1)
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colBalance)
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colStatus)
|
||||
.should('have.text', 'Active');
|
||||
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colCreatedAt)
|
||||
.should('not.be.empty');
|
||||
cy.get(rowSelectorLiquidityActive)
|
||||
.first()
|
||||
.find(colUpdatedAt)
|
||||
.should('not.be.empty');
|
||||
});
|
||||
|
||||
it('renders liquidity inactive table correctly', () => {
|
||||
// 5002-LIQP-012
|
||||
cy.getByTestId('Inactive').click();
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find('[col-id="partyId"]')
|
||||
.should('have.text', 'cc464e…dc6f');
|
||||
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colCommitmentAmount)
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colEquityLikeShare)
|
||||
.should('have.text', '100.00%');
|
||||
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colFee)
|
||||
.should('have.text', '0.40%');
|
||||
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colCommitmentAmount_1)
|
||||
.should('have.text', '4,000.00');
|
||||
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colBalance)
|
||||
.should('have.text', '2,000.00');
|
||||
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colStatus)
|
||||
.should('have.text', 'Pending');
|
||||
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colCreatedAt)
|
||||
.should('not.be.empty');
|
||||
cy.get(rowSelectorLiquidityInactive)
|
||||
.first()
|
||||
.find(colUpdatedAt)
|
||||
.should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { aliasGQLQuery } from '@vegaprotocol/cypress';
|
||||
import { proposalListQuery, marketUpdateProposal } from '@vegaprotocol/mock';
|
||||
import * as Schema from '@vegaprotocol/types';
|
||||
|
||||
const marketSummaryBlock = 'header-summary';
|
||||
|
||||
describe('Market proposal notification', { tags: '@smoke' }, () => {
|
||||
before(() => {
|
||||
cy.setVegaWallet();
|
||||
cy.mockTradingPage(
|
||||
Schema.MarketState.STATE_ACTIVE,
|
||||
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
|
||||
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
|
||||
);
|
||||
cy.mockGQL((req) => {
|
||||
aliasGQLQuery(
|
||||
req,
|
||||
'ProposalsList',
|
||||
proposalListQuery({
|
||||
proposalsConnection: {
|
||||
edges: [{ node: marketUpdateProposal }],
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
cy.mockSubscription();
|
||||
cy.visit('/#/markets/market-0');
|
||||
cy.wait('@MarketData');
|
||||
cy.getByTestId(marketSummaryBlock).should('be.visible');
|
||||
});
|
||||
|
||||
it('should display market proposal notification if proposal found', () => {
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId('market-proposal-notification').should(
|
||||
'contain.text',
|
||||
'Changes have been proposed for this market'
|
||||
);
|
||||
cy.getByTestId('market-proposal-notification').within(() => {
|
||||
cy.getByTestId('external-link').should(
|
||||
'have.attr',
|
||||
'href',
|
||||
`${Cypress.env('VEGA_TOKEN_URL')}/proposals/123`
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ const marketMode = 'market-trading-mode';
|
||||
const marketName = 'header-title';
|
||||
const marketPrice = 'market-price';
|
||||
const marketSettlement = 'market-settlement-asset';
|
||||
const marketState = 'market-state';
|
||||
const marketSummaryBlock = 'header-summary';
|
||||
const marketVolume = 'market-volume';
|
||||
const percentageValue = 'price-change-percentage';
|
||||
@@ -84,6 +85,30 @@ describe('Market trading page', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market mode', () => {
|
||||
// 6002-MDET-006
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketMode).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Trading mode');
|
||||
cy.getByTestId(itemValue).should(
|
||||
'have.text',
|
||||
'Monitoring auction - liquidity (target not met)'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market status', () => {
|
||||
// 6002-MDET-007
|
||||
// 7002-SORD-061
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(marketState).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Status');
|
||||
cy.getByTestId(itemValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('must see market settlement', () => {
|
||||
// 6002-MDET-008
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
@@ -93,6 +118,15 @@ describe('Market trading page', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
it('must see market liquidity supplied', () => {
|
||||
// 6002-MDET-009
|
||||
cy.getByTestId(marketSummaryBlock).within(() => {
|
||||
cy.getByTestId(liquiditySupplied).within(() => {
|
||||
cy.getByTestId(itemHeader).should('have.text', 'Liquidity supplied');
|
||||
cy.getByTestId(itemValue).should('not.be.empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Market tooltips', { tags: '@smoke' }, () => {
|
||||
|
||||
@@ -114,7 +114,7 @@ export const MarketPage = () => {
|
||||
</p>
|
||||
<p className="justify-center text-sm">
|
||||
<Trans
|
||||
defaults="Please choose another market from the <0>market list</0>"
|
||||
defaults="Please choose another market from the <0>market list<0>"
|
||||
ns={ns}
|
||||
components={[
|
||||
<ExternalLink
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import type { TypedDataAgGrid } from '@vegaprotocol/datagrid';
|
||||
import {
|
||||
AgGrid,
|
||||
PriceFlashCell,
|
||||
useDataGridEvents,
|
||||
} from '@vegaprotocol/datagrid';
|
||||
import { AgGrid, PriceFlashCell } from '@vegaprotocol/datagrid';
|
||||
import type { MarketMaybeWithData } from '@vegaprotocol/markets';
|
||||
import { useColumnDefs } from './use-column-defs';
|
||||
import type { DataGridStore } from '../../stores/datagrid-store-slice';
|
||||
import { type StateCreator, create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
|
||||
export const getRowId = ({ data }: { data: { id: string } }) => data.id;
|
||||
|
||||
@@ -25,37 +18,8 @@ const components = {
|
||||
|
||||
type Props = TypedDataAgGrid<MarketMaybeWithData>;
|
||||
|
||||
export type DataGridSlice = {
|
||||
gridStore: DataGridStore;
|
||||
updateGridStore: (gridStore: DataGridStore) => void;
|
||||
};
|
||||
|
||||
export const createDataGridSlice: StateCreator<DataGridSlice> = (set) => ({
|
||||
gridStore: {},
|
||||
updateGridStore: (newStore) => {
|
||||
set((curr) => ({
|
||||
gridStore: {
|
||||
...curr.gridStore,
|
||||
...newStore,
|
||||
},
|
||||
}));
|
||||
},
|
||||
});
|
||||
|
||||
const useMarketsStore = create<DataGridSlice>()(
|
||||
persist(createDataGridSlice, {
|
||||
name: 'vega_market_list_store',
|
||||
})
|
||||
);
|
||||
|
||||
export const MarketListTable = (props: Props) => {
|
||||
const columnDefs = useColumnDefs();
|
||||
const gridStore = useMarketsStore((store) => store.gridStore);
|
||||
const updateGridStore = useMarketsStore((store) => store.updateGridStore);
|
||||
|
||||
const gridStoreCallbacks = useDataGridEvents(gridStore, (colState) => {
|
||||
updateGridStore(colState);
|
||||
});
|
||||
|
||||
return (
|
||||
<AgGrid
|
||||
@@ -64,7 +28,6 @@ export const MarketListTable = (props: Props) => {
|
||||
columnDefs={columnDefs}
|
||||
components={components}
|
||||
rowHeight={45}
|
||||
{...gridStoreCallbacks}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -51,29 +51,6 @@ export const useColumnDefs = () => {
|
||||
headerName: t('Description'),
|
||||
field: 'tradableInstrument.instrument.name',
|
||||
},
|
||||
{
|
||||
headerName: t('Settlement asset'),
|
||||
field: 'tradableInstrument.instrument.product.settlementAsset.symbol',
|
||||
cellRenderer: ({
|
||||
data,
|
||||
}: VegaICellRendererParams<
|
||||
MarketMaybeWithData,
|
||||
'tradableInstrument.instrument.product.settlementAsset.symbol'
|
||||
>) => {
|
||||
const value = data && getAsset(data);
|
||||
return value ? (
|
||||
<ButtonLink
|
||||
onClick={(e) => {
|
||||
openAssetDetailsDialog(value.id, e.target as HTMLElement);
|
||||
}}
|
||||
>
|
||||
{value.symbol}
|
||||
</ButtonLink>
|
||||
) : (
|
||||
''
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
headerName: t('Trading mode'),
|
||||
field: 'tradingMode',
|
||||
@@ -165,21 +142,27 @@ export const useColumnDefs = () => {
|
||||
},
|
||||
},
|
||||
{
|
||||
headerName: t('Open Interest'),
|
||||
field: 'data.openInterest',
|
||||
type: 'rightAligned',
|
||||
valueFormatter: ({
|
||||
headerName: t('Settlement asset'),
|
||||
field: 'tradableInstrument.instrument.product.settlementAsset.symbol',
|
||||
cellRenderer: ({
|
||||
data,
|
||||
}: VegaValueFormatterParams<
|
||||
}: VegaICellRendererParams<
|
||||
MarketMaybeWithData,
|
||||
'data.openInterest'
|
||||
>) =>
|
||||
data?.data?.openInterest === undefined
|
||||
? '-'
|
||||
: addDecimalsFormatNumber(
|
||||
data?.data?.openInterest,
|
||||
data?.positionDecimalPlaces
|
||||
),
|
||||
'tradableInstrument.instrument.product.settlementAsset.symbol'
|
||||
>) => {
|
||||
const value = data && getAsset(data);
|
||||
return value ? (
|
||||
<ButtonLink
|
||||
onClick={(e) => {
|
||||
openAssetDetailsDialog(value.id, e.target as HTMLElement);
|
||||
}}
|
||||
>
|
||||
{value.symbol}
|
||||
</ButtonLink>
|
||||
) : (
|
||||
''
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
headerName: t('Spread'),
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useForm } from 'react-hook-form';
|
||||
import classNames from 'classnames';
|
||||
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import type { ButtonHTMLAttributes, MouseEventHandler } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { RainbowButton } from './buttons';
|
||||
import { useVegaWallet, useVegaWalletDialogStore } from '@vegaprotocol/wallet';
|
||||
import { useReferral } from './hooks/use-referral';
|
||||
@@ -32,19 +32,6 @@ const validateCode = (value: string, t: ReturnType<typeof useT>) => {
|
||||
return true;
|
||||
};
|
||||
|
||||
export const ApplyCodeFormContainer = () => {
|
||||
const { pubKey } = useVegaWallet();
|
||||
const { data: referee } = useReferral({ pubKey, role: 'referee' });
|
||||
const { data: referrer } = useReferral({ pubKey, role: 'referrer' });
|
||||
|
||||
// go to main page if the current pubkey is already a referrer or referee
|
||||
if (referee || referrer) {
|
||||
return <Navigate to={Routes.REFERRALS} />;
|
||||
}
|
||||
|
||||
return <ApplyCodeForm />;
|
||||
};
|
||||
|
||||
export const ApplyCodeForm = () => {
|
||||
const t = useT();
|
||||
const program = useReferralProgram();
|
||||
@@ -68,29 +55,14 @@ export const ApplyCodeForm = () => {
|
||||
} = useForm();
|
||||
const [params] = useSearchParams();
|
||||
|
||||
const { data: referee } = useReferral({ pubKey, role: 'referee' });
|
||||
const { data: referrer } = useReferral({ pubKey, role: 'referrer' });
|
||||
|
||||
const codeField = watch('code');
|
||||
const { data: previewData, loading: previewLoading } = useReferral({
|
||||
code: validateCode(codeField, t) ? codeField : undefined,
|
||||
});
|
||||
|
||||
/**
|
||||
* Validates the set a user tries to apply to.
|
||||
*/
|
||||
const validateSet = useCallback(() => {
|
||||
if (
|
||||
codeField &&
|
||||
!previewLoading &&
|
||||
previewData &&
|
||||
!previewData.isEligible
|
||||
) {
|
||||
return t('The code is no longer valid.');
|
||||
}
|
||||
if (codeField && !previewLoading && !previewData) {
|
||||
return t('The code is invalid');
|
||||
}
|
||||
return true;
|
||||
}, [codeField, previewData, previewLoading, t]);
|
||||
|
||||
useEffect(() => {
|
||||
const code = params.get('code');
|
||||
if (code) setValue('code', code);
|
||||
@@ -172,11 +144,16 @@ export const ApplyCodeForm = () => {
|
||||
}
|
||||
}, [navigate, status]);
|
||||
|
||||
// go to main page if the current pubkey is already a referrer or referee
|
||||
if (referee || referrer) {
|
||||
return <Navigate to={Routes.REFERRALS} />;
|
||||
}
|
||||
|
||||
// show "code applied" message when successfully applied
|
||||
if (status === 'successful') {
|
||||
return (
|
||||
<div className="mx-auto w-1/2">
|
||||
<h3 className="calt mb-5 flex flex-row items-center justify-center gap-2 text-center text-xl uppercase">
|
||||
<div className="w-1/2 mx-auto">
|
||||
<h3 className="mb-5 text-xl text-center uppercase calt flex flex-row gap-2 justify-center items-center">
|
||||
<span className="text-vega-green-500">
|
||||
<VegaIcon name={VegaIconNames.TICK} size={20} />
|
||||
</span>{' '}
|
||||
@@ -228,18 +205,15 @@ export const ApplyCodeForm = () => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
data-testid="referral-apply-code-form"
|
||||
className="bg-vega-clight-800 dark:bg-vega-cdark-800 mx-auto w-2/3 max-w-md rounded-lg p-8"
|
||||
>
|
||||
<h3 className="calt mb-4 text-center text-2xl">
|
||||
<div className="w-2/3 max-w-md mx-auto bg-vega-clight-800 dark:bg-vega-cdark-800 p-8 rounded-lg">
|
||||
<h3 className="mb-4 text-2xl text-center calt">
|
||||
{t('Apply a referral code')}
|
||||
</h3>
|
||||
<p className="mb-4 text-center text-base">
|
||||
{t('Enter a referral code to get trading discounts.')}
|
||||
</p>
|
||||
<form
|
||||
className={classNames('flex w-full flex-col gap-4', {
|
||||
className={classNames('w-full flex flex-col gap-4', {
|
||||
'animate-shake': Boolean(errors.code),
|
||||
})}
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
@@ -250,36 +224,32 @@ export const ApplyCodeForm = () => {
|
||||
hasError={Boolean(errors.code)}
|
||||
{...register('code', {
|
||||
required: t('You have to provide a code to apply it.'),
|
||||
validate: (value) => {
|
||||
const err = validateCode(value, t);
|
||||
if (err !== true) return err;
|
||||
return validateSet();
|
||||
},
|
||||
validate: (value) => validateCode(value, t),
|
||||
})}
|
||||
placeholder="Enter a code"
|
||||
className="bg-vega-clight-900 dark:bg-vega-cdark-700 mb-2"
|
||||
className="mb-2 bg-vega-clight-900 dark:bg-vega-cdark-700"
|
||||
/>
|
||||
</label>
|
||||
<RainbowButton variant="border" {...getButtonProps()} />
|
||||
</form>
|
||||
{errors.code && (
|
||||
<InputError className="overflow-auto break-words">
|
||||
<InputError className="break-words overflow-auto">
|
||||
{errors.code.message?.toString()}
|
||||
</InputError>
|
||||
)}
|
||||
</div>
|
||||
{validateCode(codeField, t) === true && previewLoading && !previewData ? (
|
||||
{previewLoading && !previewData ? (
|
||||
<div className="mt-10">
|
||||
<Loader />
|
||||
</div>
|
||||
) : null}
|
||||
{/* TODO: Re-check plural forms once i18n is updated */}
|
||||
{previewData && previewData.isEligible ? (
|
||||
{previewData ? (
|
||||
<div className="mt-10">
|
||||
<h2 className="text-2xl mb-5">
|
||||
{t('referralApplyPreviewMessage', {
|
||||
count: nextBenefitTierEpochsValue,
|
||||
})}
|
||||
{t(
|
||||
'You are joining the group shown, but will not have access to benefits until you have completed at least %s epochs.',
|
||||
[nextBenefitTierEpochsValue.toString()]
|
||||
)}
|
||||
</h2>
|
||||
<Statistics data={previewData} program={program} as="referee" />
|
||||
</div>
|
||||
|
||||
@@ -39,10 +39,7 @@ export const CreateCodeForm = () => {
|
||||
const { pubKey, isReadOnly } = useVegaWallet();
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="referral-create-code-form"
|
||||
className="w-2/3 max-w-md mx-auto bg-vega-clight-800 dark:bg-vega-cdark-800 p-8 rounded-lg"
|
||||
>
|
||||
<div className="w-2/3 max-w-md mx-auto bg-vega-clight-800 dark:bg-vega-cdark-800 p-8 rounded-lg">
|
||||
<h3 className="mb-4 text-2xl text-center calt">
|
||||
{t('Create a referral code')}
|
||||
</h3>
|
||||
|
||||
@@ -11,7 +11,6 @@ query ReferralSetStats($code: ID!, $epoch: Int) {
|
||||
rewardsMultiplier
|
||||
rewardsFactorMultiplier
|
||||
referrerTakerVolume
|
||||
wasEligible
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
query StakeAvailable($partyId: ID!) {
|
||||
party(id: $partyId) {
|
||||
stakingSummary {
|
||||
currentStakeAvailable
|
||||
}
|
||||
}
|
||||
networkParameter(key: "referralProgram.minStakedVegaTokens") {
|
||||
value
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -9,7 +9,7 @@ export type ReferralSetStatsQueryVariables = Types.Exact<{
|
||||
}>;
|
||||
|
||||
|
||||
export type ReferralSetStatsQuery = { __typename?: 'Query', referralSetStats: { __typename?: 'ReferralSetStatsConnection', edges: Array<{ __typename?: 'ReferralSetStatsEdge', node: { __typename?: 'ReferralSetStats', atEpoch: number, partyId: string, discountFactor: string, rewardFactor: string, epochNotionalTakerVolume: string, referralSetRunningNotionalTakerVolume: string, rewardsMultiplier: string, rewardsFactorMultiplier: string, referrerTakerVolume: string, wasEligible: boolean } } | null> } };
|
||||
export type ReferralSetStatsQuery = { __typename?: 'Query', referralSetStats: { __typename?: 'ReferralSetStatsConnection', edges: Array<{ __typename?: 'ReferralSetStatsEdge', node: { __typename?: 'ReferralSetStats', atEpoch: number, partyId: string, discountFactor: string, rewardFactor: string, epochNotionalTakerVolume: string, referralSetRunningNotionalTakerVolume: string, rewardsMultiplier: string, rewardsFactorMultiplier: string, referrerTakerVolume: string } } | null> } };
|
||||
|
||||
|
||||
export const ReferralSetStatsDocument = gql`
|
||||
@@ -26,7 +26,6 @@ export const ReferralSetStatsDocument = gql`
|
||||
rewardsMultiplier
|
||||
rewardsFactorMultiplier
|
||||
referrerTakerVolume
|
||||
wasEligible
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,53 +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 StakeAvailableQueryVariables = Types.Exact<{
|
||||
partyId: Types.Scalars['ID'];
|
||||
}>;
|
||||
|
||||
|
||||
export type StakeAvailableQuery = { __typename?: 'Query', party?: { __typename?: 'Party', stakingSummary: { __typename?: 'StakingSummary', currentStakeAvailable: string } } | null, networkParameter?: { __typename?: 'NetworkParameter', value: string } | null };
|
||||
|
||||
|
||||
export const StakeAvailableDocument = gql`
|
||||
query StakeAvailable($partyId: ID!) {
|
||||
party(id: $partyId) {
|
||||
stakingSummary {
|
||||
currentStakeAvailable
|
||||
}
|
||||
}
|
||||
networkParameter(key: "referralProgram.minStakedVegaTokens") {
|
||||
value
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* __useStakeAvailableQuery__
|
||||
*
|
||||
* To run a query within a React component, call `useStakeAvailableQuery` and pass it any options that fit your needs.
|
||||
* When your component renders, `useStakeAvailableQuery` 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 } = useStakeAvailableQuery({
|
||||
* variables: {
|
||||
* partyId: // value for 'partyId'
|
||||
* },
|
||||
* });
|
||||
*/
|
||||
export function useStakeAvailableQuery(baseOptions: Apollo.QueryHookOptions<StakeAvailableQuery, StakeAvailableQueryVariables>) {
|
||||
const options = {...defaultOptions, ...baseOptions}
|
||||
return Apollo.useQuery<StakeAvailableQuery, StakeAvailableQueryVariables>(StakeAvailableDocument, options);
|
||||
}
|
||||
export function useStakeAvailableLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<StakeAvailableQuery, StakeAvailableQueryVariables>) {
|
||||
const options = {...defaultOptions, ...baseOptions}
|
||||
return Apollo.useLazyQuery<StakeAvailableQuery, StakeAvailableQueryVariables>(StakeAvailableDocument, options);
|
||||
}
|
||||
export type StakeAvailableQueryHookResult = ReturnType<typeof useStakeAvailableQuery>;
|
||||
export type StakeAvailableLazyQueryHookResult = ReturnType<typeof useStakeAvailableLazyQuery>;
|
||||
export type StakeAvailableQueryResult = Apollo.QueryResult<StakeAvailableQuery, StakeAvailableQueryVariables>;
|
||||
@@ -1,8 +1,8 @@
|
||||
import { getNumberFormat } from '@vegaprotocol/utils';
|
||||
import { addDays } from 'date-fns';
|
||||
import sortBy from 'lodash/sortBy';
|
||||
import omit from 'lodash/omit';
|
||||
import { useReferralProgramQuery } from './__generated__/CurrentReferralProgram';
|
||||
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
|
||||
|
||||
const STAKING_TIERS_MAPPING: Record<number, string> = {
|
||||
1: 'Tradestarter',
|
||||
@@ -85,9 +85,7 @@ export const useReferralProgram = () => {
|
||||
discountFactor: Number(t.referralDiscountFactor),
|
||||
discount: Number(t.referralDiscountFactor) * 100 + '%',
|
||||
minimumVolume: Number(t.minimumRunningNotionalTakerVolume),
|
||||
volume: getNumberFormat(0).format(
|
||||
Number(t.minimumRunningNotionalTakerVolume)
|
||||
),
|
||||
volume: addDecimalsFormatNumber(t.minimumRunningNotionalTakerVolume, 0),
|
||||
epochs: Number(t.minimumEpochs),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
import {
|
||||
Intent,
|
||||
type Toast,
|
||||
useToasts,
|
||||
ToastHeading,
|
||||
Button,
|
||||
} from '@vegaprotocol/ui-toolkit';
|
||||
import { useReferral } from './use-referral';
|
||||
import { useVegaWallet } from '@vegaprotocol/wallet';
|
||||
import { useEffect } from 'react';
|
||||
import { useT } from '../../../lib/use-t';
|
||||
import { matchPath, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Routes } from '../../../lib/links';
|
||||
import { useCurrentEpochInfoQuery } from './__generated__/Epoch';
|
||||
|
||||
const REFETCH_INTERVAL = 60 * 60 * 1000; // 1h
|
||||
const NON_ELIGIBLE_REFERRAL_SET_TOAST_ID = 'non-eligible-referral-set';
|
||||
|
||||
const useNonEligibleReferralSet = () => {
|
||||
const { pubKey } = useVegaWallet();
|
||||
const { data, loading, refetch } = useReferral({ pubKey, role: 'referee' });
|
||||
const {
|
||||
data: epochData,
|
||||
loading: epochLoading,
|
||||
refetch: epochRefetch,
|
||||
} = useCurrentEpochInfoQuery();
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
refetch();
|
||||
epochRefetch();
|
||||
}, REFETCH_INTERVAL);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [epochRefetch, refetch]);
|
||||
|
||||
return { data, epoch: epochData?.epoch.id, loading: loading || epochLoading };
|
||||
};
|
||||
|
||||
export const useReferralToasts = () => {
|
||||
const navigate = useNavigate();
|
||||
const { pathname } = useLocation();
|
||||
const t = useT();
|
||||
const [setToast, hasToast, updateToast] = useToasts((store) => [
|
||||
store.setToast,
|
||||
store.hasToast,
|
||||
store.update,
|
||||
]);
|
||||
|
||||
const { data, epoch, loading } = useNonEligibleReferralSet();
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
data &&
|
||||
epoch &&
|
||||
!loading &&
|
||||
!data.isEligible &&
|
||||
!hasToast(NON_ELIGIBLE_REFERRAL_SET_TOAST_ID + epoch)
|
||||
) {
|
||||
const nonEligibleReferralToast: Toast = {
|
||||
id: NON_ELIGIBLE_REFERRAL_SET_TOAST_ID + epoch,
|
||||
intent: Intent.Warning,
|
||||
content: (
|
||||
<>
|
||||
<ToastHeading>{t('Referral code no longer valid')}</ToastHeading>
|
||||
<p>
|
||||
{t(
|
||||
'Your referral code is no longer valid as the referrer no longer meets the minimum requirements.'
|
||||
)}
|
||||
</p>
|
||||
<p className="mt-2">
|
||||
<Button
|
||||
data-testid="toast-apply-code"
|
||||
size="xs"
|
||||
onClick={() => {
|
||||
const matched = matchPath(
|
||||
Routes.REFERRALS_APPLY_CODE,
|
||||
pathname
|
||||
);
|
||||
if (!matched) navigate(Routes.REFERRALS_APPLY_CODE);
|
||||
updateToast(NON_ELIGIBLE_REFERRAL_SET_TOAST_ID + epoch, {
|
||||
hidden: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t('Apply a new code')}
|
||||
</Button>
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
onClose: () =>
|
||||
updateToast(NON_ELIGIBLE_REFERRAL_SET_TOAST_ID + epoch, {
|
||||
hidden: true,
|
||||
}),
|
||||
};
|
||||
setToast(nonEligibleReferralToast);
|
||||
}
|
||||
}, [
|
||||
data,
|
||||
epoch,
|
||||
hasToast,
|
||||
loading,
|
||||
navigate,
|
||||
pathname,
|
||||
setToast,
|
||||
t,
|
||||
updateToast,
|
||||
]);
|
||||
};
|
||||
@@ -4,7 +4,6 @@ import { useRefereesQuery } from './__generated__/Referees';
|
||||
import compact from 'lodash/compact';
|
||||
import type { ReferralSetsQueryVariables } from './__generated__/ReferralSets';
|
||||
import { useReferralSetsQuery } from './__generated__/ReferralSets';
|
||||
import { useStakeAvailable } from './use-stake-available';
|
||||
|
||||
export const DEFAULT_AGGREGATION_DAYS = 30;
|
||||
|
||||
@@ -63,8 +62,6 @@ export const useReferral = (args: UseReferralArgs) => {
|
||||
? referralData.referralSets.edges[0]?.node
|
||||
: undefined;
|
||||
|
||||
const { isEligible } = useStakeAvailable(referralSet?.referrer);
|
||||
|
||||
const {
|
||||
data: refereesData,
|
||||
loading: refereesLoading,
|
||||
@@ -106,7 +103,6 @@ export const useReferral = (args: UseReferralArgs) => {
|
||||
referee: referee,
|
||||
referrerId: referralSet.referrer,
|
||||
createdAt: referralSet.createdAt,
|
||||
isEligible,
|
||||
referees,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
@@ -1,35 +1,34 @@
|
||||
import { gql, useQuery } from '@apollo/client';
|
||||
import { useVegaWallet } from '@vegaprotocol/wallet';
|
||||
import { useStakeAvailableQuery } from './__generated__/StakeAvailable';
|
||||
|
||||
/**
|
||||
* Gets the current stake available for given public key and required stake for
|
||||
* the referral program.
|
||||
*
|
||||
* (Uses currently connected public key if left empty)
|
||||
*/
|
||||
export const useStakeAvailable = (pubKey?: string) => {
|
||||
const { pubKey: currentPubKey } = useVegaWallet();
|
||||
const partyId = pubKey || currentPubKey;
|
||||
const { data } = useStakeAvailableQuery({
|
||||
variables: { partyId: partyId || '' },
|
||||
skip: !partyId,
|
||||
const STAKE_QUERY = gql`
|
||||
query CreateCode($partyId: ID!) {
|
||||
party(id: $partyId) {
|
||||
stakingSummary {
|
||||
currentStakeAvailable
|
||||
}
|
||||
}
|
||||
networkParameter(key: "referralProgram.minStakedVegaTokens") {
|
||||
value
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const useStakeAvailable = () => {
|
||||
const { pubKey } = useVegaWallet();
|
||||
const { data } = useQuery(STAKE_QUERY, {
|
||||
variables: { partyId: pubKey || '' },
|
||||
skip: !pubKey,
|
||||
// TODO: remove when network params available
|
||||
errorPolicy: 'ignore',
|
||||
});
|
||||
|
||||
const stakeAvailable = data
|
||||
? BigInt(data.party?.stakingSummary.currentStakeAvailable || '0')
|
||||
: undefined;
|
||||
const requiredStake = data
|
||||
? BigInt(data.networkParameter?.value || '0')
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
stakeAvailable,
|
||||
requiredStake,
|
||||
isEligible:
|
||||
stakeAvailable != null &&
|
||||
requiredStake != null &&
|
||||
stakeAvailable >= requiredStake,
|
||||
stakeAvailable: data
|
||||
? BigInt(data.party?.stakingSummary.currentStakeAvailable || '0')
|
||||
: undefined,
|
||||
requiredStake: data
|
||||
? BigInt(data.networkParameter?.value || '0')
|
||||
: undefined,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,374 +0,0 @@
|
||||
import { MockedProvider, type MockedResponse } from '@apollo/react-testing';
|
||||
import { render, waitFor } from '@testing-library/react';
|
||||
import { type VegaWalletContextShape } from '@vegaprotocol/wallet';
|
||||
import { ReferralStatistics } from './referral-statistics';
|
||||
import {
|
||||
ReferralProgramDocument,
|
||||
type ReferralProgramQuery,
|
||||
} from './hooks/__generated__/CurrentReferralProgram';
|
||||
import {
|
||||
ReferralSetsDocument,
|
||||
type ReferralSetsQueryVariables,
|
||||
type ReferralSetsQuery,
|
||||
} from './hooks/__generated__/ReferralSets';
|
||||
import {
|
||||
StakeAvailableDocument,
|
||||
type StakeAvailableQueryVariables,
|
||||
type StakeAvailableQuery,
|
||||
} from './hooks/__generated__/StakeAvailable';
|
||||
import {
|
||||
RefereesDocument,
|
||||
type RefereesQueryVariables,
|
||||
type RefereesQuery,
|
||||
} from './hooks/__generated__/Referees';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
|
||||
const MOCK_PUBKEY =
|
||||
'1234567890123456789012345678901234567890123456789012345678901234';
|
||||
|
||||
const MOCK_STAKE_AVAILABLE: StakeAvailableQuery = {
|
||||
networkParameter: {
|
||||
__typename: 'NetworkParameter',
|
||||
value: '1',
|
||||
},
|
||||
party: {
|
||||
__typename: 'Party',
|
||||
stakingSummary: {
|
||||
__typename: 'StakingSummary',
|
||||
currentStakeAvailable: '1',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const MOCK_NON_ELIGIBILE_STAKE_AVAILABLE: StakeAvailableQuery = {
|
||||
networkParameter: {
|
||||
__typename: 'NetworkParameter',
|
||||
value: '1',
|
||||
},
|
||||
party: {
|
||||
__typename: 'Party',
|
||||
stakingSummary: {
|
||||
__typename: 'StakingSummary',
|
||||
currentStakeAvailable: '0',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const MOCK_REFERRAL_PROGRAM: ReferralProgramQuery = {
|
||||
currentReferralProgram: {
|
||||
__typename: 'CurrentReferralProgram',
|
||||
benefitTiers: [
|
||||
{
|
||||
__typename: 'BenefitTier',
|
||||
minimumEpochs: 1,
|
||||
minimumRunningNotionalTakerVolume: '0',
|
||||
referralDiscountFactor: '0.01',
|
||||
referralRewardFactor: '0.01',
|
||||
},
|
||||
{
|
||||
__typename: 'BenefitTier',
|
||||
minimumEpochs: 2,
|
||||
minimumRunningNotionalTakerVolume: '10',
|
||||
referralDiscountFactor: '0.02',
|
||||
referralRewardFactor: '0.02',
|
||||
},
|
||||
],
|
||||
endOfProgramTimestamp: '202411012023-11-26T05:58:24.045158Z',
|
||||
id: '123',
|
||||
stakingTiers: [
|
||||
{
|
||||
__typename: 'StakingTier',
|
||||
minimumStakedTokens: '100',
|
||||
referralRewardMultiplier: '1',
|
||||
},
|
||||
{
|
||||
__typename: 'StakingTier',
|
||||
minimumStakedTokens: '1000',
|
||||
referralRewardMultiplier: '2',
|
||||
},
|
||||
],
|
||||
version: 2,
|
||||
windowLength: 3,
|
||||
endedAt: null,
|
||||
},
|
||||
};
|
||||
|
||||
const MOCK_REFERRER_SET: ReferralSetsQuery = {
|
||||
referralSets: {
|
||||
__typename: 'ReferralSetConnection',
|
||||
edges: [
|
||||
{
|
||||
__typename: 'ReferralSetEdge',
|
||||
node: {
|
||||
__typename: 'ReferralSet',
|
||||
createdAt: '2023-11-26T05:58:24.045158Z',
|
||||
id: '3772e570fbab89e50e563036b01dd949c554e5b5fe7908449672dfce9a8adffa',
|
||||
referrer: MOCK_PUBKEY,
|
||||
updatedAt: '2023-11-26T05:58:24.045158Z',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const MOCK_REFERREE_SET: ReferralSetsQuery = {
|
||||
referralSets: {
|
||||
__typename: 'ReferralSetConnection',
|
||||
edges: [
|
||||
{
|
||||
__typename: 'ReferralSetEdge',
|
||||
node: {
|
||||
__typename: 'ReferralSet',
|
||||
createdAt: '2023-11-26T05:58:24.045158Z',
|
||||
id: '3772e570fbab89e50e563036b01dd949c554e5b5fe7908449672dfce9a8adffa',
|
||||
referrer:
|
||||
'1111111111111111111111111111111111111111111111111111111111111111',
|
||||
updatedAt: '2023-11-26T05:58:24.045158Z',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const MOCK_REFEREES: RefereesQuery = {
|
||||
referralSetReferees: {
|
||||
__typename: 'ReferralSetRefereeConnection',
|
||||
edges: [
|
||||
{
|
||||
node: {
|
||||
atEpoch: 1,
|
||||
joinedAt: '2023-11-21T14:17:09.257235Z',
|
||||
refereeId:
|
||||
'0987654321098765432109876543210987654321098765432109876543219876',
|
||||
referralSetId:
|
||||
'3772e570fbab89e50e563036b01dd949c554e5b5fe7908449672dfce9a8adffa',
|
||||
totalRefereeGeneratedRewards: '1234',
|
||||
totalRefereeNotionalTakerVolume: '5678',
|
||||
__typename: 'ReferralSetReferee',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const programMock: MockedResponse<ReferralProgramQuery> = {
|
||||
request: {
|
||||
query: ReferralProgramDocument,
|
||||
},
|
||||
result: { data: MOCK_REFERRAL_PROGRAM },
|
||||
};
|
||||
|
||||
const referralSetAsReferrerMock: MockedResponse<
|
||||
ReferralSetsQuery,
|
||||
ReferralSetsQueryVariables
|
||||
> = {
|
||||
request: {
|
||||
query: ReferralSetsDocument,
|
||||
variables: {
|
||||
referrer: MOCK_PUBKEY,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
data: MOCK_REFERRER_SET,
|
||||
},
|
||||
};
|
||||
|
||||
const noReferralSetAsReferrerMock: MockedResponse<
|
||||
ReferralSetsQuery,
|
||||
ReferralSetsQueryVariables
|
||||
> = {
|
||||
request: {
|
||||
query: ReferralSetsDocument,
|
||||
variables: {
|
||||
referrer: MOCK_PUBKEY,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
data: { referralSets: { edges: [] } },
|
||||
},
|
||||
};
|
||||
|
||||
const referralSetAsRefereeMock: MockedResponse<
|
||||
ReferralSetsQuery,
|
||||
ReferralSetsQueryVariables
|
||||
> = {
|
||||
request: {
|
||||
query: ReferralSetsDocument,
|
||||
variables: {
|
||||
referee: MOCK_PUBKEY,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
data: MOCK_REFERREE_SET,
|
||||
},
|
||||
};
|
||||
|
||||
const noReferralSetAsRefereeMock: MockedResponse<
|
||||
ReferralSetsQuery,
|
||||
ReferralSetsQueryVariables
|
||||
> = {
|
||||
request: {
|
||||
query: ReferralSetsDocument,
|
||||
variables: {
|
||||
referee: MOCK_PUBKEY,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
data: { referralSets: { edges: [] } },
|
||||
},
|
||||
};
|
||||
|
||||
const stakeAvailableMock: MockedResponse<
|
||||
StakeAvailableQuery,
|
||||
StakeAvailableQueryVariables
|
||||
> = {
|
||||
request: {
|
||||
query: StakeAvailableDocument,
|
||||
variables: {
|
||||
partyId: MOCK_PUBKEY,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
data: MOCK_STAKE_AVAILABLE,
|
||||
},
|
||||
};
|
||||
|
||||
const nonEligibleStakeAvailableMock: MockedResponse<
|
||||
StakeAvailableQuery,
|
||||
StakeAvailableQueryVariables
|
||||
> = {
|
||||
request: {
|
||||
query: StakeAvailableDocument,
|
||||
variables: {
|
||||
partyId: MOCK_PUBKEY,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
data: MOCK_NON_ELIGIBILE_STAKE_AVAILABLE,
|
||||
},
|
||||
};
|
||||
|
||||
const refereesMock: MockedResponse<RefereesQuery, RefereesQueryVariables> = {
|
||||
request: {
|
||||
query: RefereesDocument,
|
||||
variables: {
|
||||
code: MOCK_REFERRER_SET.referralSets.edges[0]?.node.id as string,
|
||||
aggregationEpochs:
|
||||
MOCK_REFERRAL_PROGRAM.currentReferralProgram?.windowLength,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
data: MOCK_REFEREES,
|
||||
},
|
||||
};
|
||||
|
||||
jest.mock('@vegaprotocol/wallet', () => {
|
||||
return {
|
||||
...jest.requireActual('@vegaprotocol/wallet'),
|
||||
useVegaWallet: () => {
|
||||
const ctx: Partial<VegaWalletContextShape> = {
|
||||
pubKey: MOCK_PUBKEY,
|
||||
};
|
||||
return ctx;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe('ReferralStatistics', () => {
|
||||
it('displays create code when no data has been found for given pubkey', () => {
|
||||
const { queryByTestId } = render(
|
||||
<MockedProvider mocks={[]} showWarnings={false}>
|
||||
<ReferralStatistics />
|
||||
</MockedProvider>
|
||||
);
|
||||
|
||||
expect(queryByTestId('referral-create-code-form')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays referrer stats when given pubkey is a referrer', async () => {
|
||||
const { queryByTestId } = render(
|
||||
<MockedProvider
|
||||
mocks={[
|
||||
programMock,
|
||||
referralSetAsReferrerMock,
|
||||
noReferralSetAsRefereeMock,
|
||||
stakeAvailableMock,
|
||||
refereesMock,
|
||||
]}
|
||||
showWarnings={false}
|
||||
>
|
||||
<ReferralStatistics />
|
||||
</MockedProvider>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
queryByTestId('referral-create-code-form')
|
||||
).not.toBeInTheDocument();
|
||||
expect(queryByTestId('referral-statistics')).toBeInTheDocument();
|
||||
expect(queryByTestId('referral-statistics')?.dataset.as).toEqual(
|
||||
'referrer'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('displays referee stats when given pubkey is a referee', async () => {
|
||||
const { queryByTestId } = render(
|
||||
<MemoryRouter>
|
||||
<MockedProvider
|
||||
mocks={[
|
||||
programMock,
|
||||
noReferralSetAsReferrerMock,
|
||||
referralSetAsRefereeMock,
|
||||
stakeAvailableMock,
|
||||
refereesMock,
|
||||
]}
|
||||
showWarnings={false}
|
||||
>
|
||||
<ReferralStatistics />
|
||||
</MockedProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
queryByTestId('referral-create-code-form')
|
||||
).not.toBeInTheDocument();
|
||||
expect(queryByTestId('referral-statistics')).toBeInTheDocument();
|
||||
expect(queryByTestId('referral-statistics')?.dataset.as).toEqual(
|
||||
'referee'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('displays eligibility warning when the set is no longer valid due to the referrers stake', async () => {
|
||||
const { queryByTestId } = render(
|
||||
<MemoryRouter>
|
||||
<MockedProvider
|
||||
mocks={[
|
||||
programMock,
|
||||
noReferralSetAsReferrerMock,
|
||||
referralSetAsRefereeMock,
|
||||
nonEligibleStakeAvailableMock,
|
||||
refereesMock,
|
||||
]}
|
||||
showWarnings={false}
|
||||
>
|
||||
<ReferralStatistics />
|
||||
</MockedProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
queryByTestId('referral-create-code-form')
|
||||
).not.toBeInTheDocument();
|
||||
expect(queryByTestId('referral-statistics')).toBeInTheDocument();
|
||||
expect(queryByTestId('referral-statistics')?.dataset.as).toEqual(
|
||||
'referee'
|
||||
);
|
||||
expect(queryByTestId('referral-eligibility-warning')).toBeInTheDocument();
|
||||
expect(queryByTestId('referral-apply-code-form')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
addDecimalsFormatNumber,
|
||||
getDateFormat,
|
||||
getDateTimeFormat,
|
||||
getNumberFormat,
|
||||
getUserLocale,
|
||||
removePaginationWrapper,
|
||||
} from '@vegaprotocol/utils';
|
||||
@@ -32,7 +31,6 @@ import maxBy from 'lodash/maxBy';
|
||||
import { DocsLinks } from '@vegaprotocol/environment';
|
||||
import { useT, ns } from '../../lib/use-t';
|
||||
import { Trans } from 'react-i18next';
|
||||
import { ApplyCodeForm } from './apply-code-form';
|
||||
|
||||
export const ReferralStatistics = () => {
|
||||
const { pubKey } = useVegaWallet();
|
||||
@@ -51,21 +49,11 @@ export const ReferralStatistics = () => {
|
||||
});
|
||||
|
||||
if (referee?.code) {
|
||||
return (
|
||||
<>
|
||||
<Statistics data={referee} program={program} as="referee" />;
|
||||
{!referee.isEligible && <ApplyCodeForm />}
|
||||
</>
|
||||
);
|
||||
return <Statistics data={referee} program={program} as="referee" />;
|
||||
}
|
||||
|
||||
if (referrer?.code) {
|
||||
return (
|
||||
<>
|
||||
<Statistics data={referrer} program={program} as="referrer" />;
|
||||
<RefereesTable data={referrer} program={program} />
|
||||
</>
|
||||
);
|
||||
return <Statistics data={referrer} program={program} as="referrer" />;
|
||||
}
|
||||
|
||||
return <CreateCodeContainer />;
|
||||
@@ -185,7 +173,7 @@ export const Statistics = ({
|
||||
|
||||
const { benefitTiers } = useReferralProgram();
|
||||
|
||||
const { stakeAvailable, isEligible } = useStakeAvailable();
|
||||
const { stakeAvailable } = useStakeAvailable();
|
||||
const { details } = program;
|
||||
|
||||
const compactNumFormat = new Intl.NumberFormat(getUserLocale(), {
|
||||
@@ -211,24 +199,12 @@ export const Statistics = ({
|
||||
{baseCommissionValue * 100}%
|
||||
</StatTile>
|
||||
);
|
||||
|
||||
const stakingMultiplierTile = (
|
||||
<StatTile
|
||||
title={t('Staking multiplier')}
|
||||
description={
|
||||
<span
|
||||
className={classNames({
|
||||
'text-vega-red': !isEligible,
|
||||
})}
|
||||
>
|
||||
{t('{{amount}} $VEGA staked', {
|
||||
amount: addDecimalsFormatNumber(
|
||||
stakeAvailable?.toString() || 0,
|
||||
18
|
||||
),
|
||||
})}
|
||||
</span>
|
||||
}
|
||||
description={t('{{amount}} $VEGA staked', {
|
||||
amount: addDecimalsFormatNumber(stakeAvailable?.toString() || 0, 18),
|
||||
})}
|
||||
>
|
||||
{multiplier || t('None')}
|
||||
</StatTile>
|
||||
@@ -279,7 +255,7 @@ export const Statistics = ({
|
||||
})}
|
||||
description={<QUSDTooltip />}
|
||||
>
|
||||
{getNumberFormat(0).format(Number(totalCommissionValue))}
|
||||
{addDecimalsFormatNumber(totalCommissionValue.toString(), 0)}
|
||||
</StatTile>
|
||||
);
|
||||
|
||||
@@ -356,60 +332,28 @@ export const Statistics = ({
|
||||
</>
|
||||
);
|
||||
|
||||
const eligibilityWarning = as === 'referee' && !isEligible && (
|
||||
<div
|
||||
data-testid="referral-eligibility-warning"
|
||||
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center w-1/2 lg:w-1/3"
|
||||
>
|
||||
<h2 className="text-2xl mb-2">{t('Referral code no longer valid')}</h2>
|
||||
<p>
|
||||
{t(
|
||||
'Your referral code is no longer valid as the referrer no longer meets the minimum requirements. Apply a new code to continue receiving discounts.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="referral-statistics"
|
||||
data-as={as}
|
||||
className="relative mx-auto mb-20"
|
||||
>
|
||||
<div
|
||||
className={classNames('grid grid-cols-1 grid-rows-1 gap-5', {
|
||||
'opacity-20 pointer-events-none': as === 'referee' && !isEligible,
|
||||
})}
|
||||
>
|
||||
{as === 'referrer' && referrerTiles}
|
||||
{as === 'referee' && refereeTiles}
|
||||
</div>
|
||||
|
||||
{eligibilityWarning}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const RefereesTable = ({
|
||||
data,
|
||||
program,
|
||||
}: {
|
||||
data: NonNullable<ReturnType<typeof useReferral>['data']>;
|
||||
program: ReturnType<typeof useReferralProgram>;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const tableRef = useRef<HTMLTableElement>(null);
|
||||
const { details } = program;
|
||||
useLayoutEffect(() => {
|
||||
if ((tableRef.current?.getBoundingClientRect().height || 0) > 384) {
|
||||
setCollapsed(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Stats tiles */}
|
||||
<div
|
||||
className={classNames(
|
||||
'grid grid-cols-1 grid-rows-1 gap-5 mx-auto mb-20'
|
||||
)}
|
||||
>
|
||||
{as === 'referrer' && referrerTiles}
|
||||
{as === 'referee' && refereeTiles}
|
||||
</div>
|
||||
|
||||
{/* Referees (only for referrer view) */}
|
||||
{data.referees.length > 0 && (
|
||||
{as === 'referrer' && data.referees.length > 0 && (
|
||||
<div className="mt-20 mb-20">
|
||||
<h2 className="mb-5 text-2xl">{t('Referees')}</h2>
|
||||
<div
|
||||
@@ -473,8 +417,8 @@ export const RefereesTable = ({
|
||||
)
|
||||
.map((r) => ({
|
||||
...r,
|
||||
volume: getNumberFormat(0).format(r.volume),
|
||||
commission: getNumberFormat(0).format(r.commission),
|
||||
volume: addDecimalsFormatNumber(r.volume, 0),
|
||||
commission: addDecimalsFormatNumber(r.commission, 0),
|
||||
}))
|
||||
.reverse()}
|
||||
/>
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useT } from '../../lib/use-t';
|
||||
import { t } from '@vegaprotocol/i18n';
|
||||
import { RewardsContainer } from '../../components/rewards-container';
|
||||
|
||||
export const Rewards = () => {
|
||||
const t = useT();
|
||||
return (
|
||||
<div className="container mx-auto p-4">
|
||||
<h1 className="px-4 pb-4 text-2xl">{t('Rewards')}</h1>
|
||||
|
||||
@@ -139,7 +139,7 @@ describe('RewardPot', () => {
|
||||
renderComponent(props);
|
||||
|
||||
expect(screen.getByTestId('total-rewards')).toHaveTextContent(
|
||||
`7.00 ${rewardAsset.symbol}`
|
||||
`7.0000 ${rewardAsset.symbol}`
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Locked/).nextElementSibling).toHaveTextContent(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import groupBy from 'lodash/groupBy';
|
||||
import type { Account } from '@vegaprotocol/accounts';
|
||||
import { useAccounts } from '@vegaprotocol/accounts';
|
||||
import { t } from '@vegaprotocol/i18n';
|
||||
import {
|
||||
NetworkParams,
|
||||
useNetworkParams,
|
||||
@@ -30,10 +31,8 @@ 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';
|
||||
import { useT } from '../../lib/use-t';
|
||||
|
||||
export const RewardsContainer = () => {
|
||||
const t = useT();
|
||||
const { pubKey } = useVegaWallet();
|
||||
const { params, loading: paramsLoading } = useNetworkParams([
|
||||
NetworkParams.reward_asset,
|
||||
@@ -122,9 +121,7 @@ export const RewardsContainer = () => {
|
||||
return (
|
||||
<Card
|
||||
key={assetId}
|
||||
title={t('{{assetSymbol}} Reward pot', {
|
||||
assetSymbol: asset.symbol,
|
||||
})}
|
||||
title={t('%s Reward pot', asset.symbol)}
|
||||
className="lg:col-span-3 xl:col-span-2"
|
||||
loading={loading}
|
||||
>
|
||||
@@ -170,7 +167,6 @@ export const RewardPot = ({
|
||||
assetId,
|
||||
vestingBalancesSummary,
|
||||
}: RewardPotProps) => {
|
||||
const t = useT();
|
||||
// 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();
|
||||
@@ -246,9 +242,7 @@ export const RewardPot = ({
|
||||
<CardTable>
|
||||
<tr>
|
||||
<CardTableTH className="flex items-center gap-1">
|
||||
{t('Locked {{assetSymbol}}', {
|
||||
assetSymbol: rewardAsset.symbol,
|
||||
})}
|
||||
{t(`Locked ${rewardAsset.symbol}`)}
|
||||
<VegaIcon name={VegaIconNames.LOCK} size={12} />
|
||||
</CardTableTH>
|
||||
<CardTableTD>
|
||||
@@ -260,11 +254,7 @@ export const RewardPot = ({
|
||||
</CardTableTD>
|
||||
</tr>
|
||||
<tr>
|
||||
<CardTableTH>
|
||||
{t('Vesting {{assetSymbol}}', {
|
||||
assetSymbol: rewardAsset.symbol,
|
||||
})}
|
||||
</CardTableTH>
|
||||
<CardTableTH>{t(`Vesting ${rewardAsset.symbol}`)}</CardTableTH>
|
||||
<CardTableTD>
|
||||
{addDecimalsFormatNumberQuantum(
|
||||
totalVesting.toString(),
|
||||
@@ -319,7 +309,6 @@ export const Vesting = ({
|
||||
baseRate: string;
|
||||
multiplier?: string;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const rate = new BigNumber(baseRate).times(multiplier);
|
||||
const rateFormatted = formatPercentage(Number(rate));
|
||||
const baseRateFormatted = formatPercentage(Number(baseRate));
|
||||
@@ -352,7 +341,6 @@ export const Multipliers = ({
|
||||
streakMultiplier?: string;
|
||||
hoarderMultiplier?: string;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const combinedMultiplier = new BigNumber(streakMultiplier).times(
|
||||
hoarderMultiplier
|
||||
);
|
||||
|
||||
@@ -16,12 +16,12 @@ import {
|
||||
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';
|
||||
import { useT } from '../../lib/use-t';
|
||||
|
||||
export const RewardsHistoryContainer = ({
|
||||
epoch,
|
||||
@@ -140,7 +140,6 @@ export const RewardHistoryTable = ({
|
||||
onEpochChange: (epochVariables: { from: number; to: number }) => void;
|
||||
loading: boolean;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const [isParty, setIsParty] = useState(false);
|
||||
|
||||
const rowData = useRewardsRowData({
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
CONSOLE_IMAGE_NAME=vegaprotocol/trading:latest
|
||||
VEGA_VERSION=v0.73.5
|
||||
VEGA_VERSION=v0.73.4
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
CONSOLE_IMAGE_NAME=vegaprotocol/trading:develop
|
||||
VEGA_VERSION=v0.73.5
|
||||
VEGA_VERSION=v0.73.4
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
CONSOLE_IMAGE_NAME=vegaprotocol/trading:main
|
||||
VEGA_VERSION=v0.73.5
|
||||
VEGA_VERSION=v0.73.4
|
||||
|
||||
@@ -34,14 +34,4 @@ def next_epoch(vega: VegaServiceNull):
|
||||
"Epoch not started after forwarding the duration of two epochs."
|
||||
)
|
||||
vega.wait_fn(1)
|
||||
vega.wait_for_total_catchup()
|
||||
|
||||
def truncate_middle(market_id, start=6, end=4):
|
||||
if len(market_id) < 11:
|
||||
return market_id
|
||||
return market_id[:start] + '\u2026' + market_id[-end:]
|
||||
|
||||
def change_keys(page: Page, vega:VegaServiceNull, key_name):
|
||||
page.get_by_test_id("manage-vega-wallet").click()
|
||||
page.get_by_test_id("key-" + vega.wallet.public_key(key_name)).click()
|
||||
page.reload()
|
||||
vega.wait_for_total_catchup()
|
||||
@@ -1,13 +1,26 @@
|
||||
from collections import namedtuple
|
||||
from vega_sim.service import VegaService
|
||||
from actions.vega import submit_multiple_orders, submit_order, submit_liquidity
|
||||
from wallet_config import MM_WALLET, MM_WALLET2, TERMINATE_WALLET, wallets
|
||||
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET]
|
||||
|
||||
mint_amount: float = 10e5
|
||||
market_name = "BTC:DAI_2023"
|
||||
|
||||
|
||||
def setup_simple_market(
|
||||
vega: VegaService,
|
||||
approve_proposal=True,
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import pytest
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from actions.vega import submit_order
|
||||
from actions.utils import wait_for_toast_confirmation
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
|
||||
notional = "deal-ticket-fee-notional"
|
||||
fees = "deal-ticket-fee-fees"
|
||||
margin_required = "deal-ticket-fee-margin-required"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import pytest
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from actions.vega import submit_order
|
||||
@@ -6,6 +7,14 @@ from datetime import datetime, timedelta
|
||||
from conftest import init_vega
|
||||
from fixtures.market import setup_continuous_market
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
stop_order_btn = "order-type-Stop"
|
||||
stop_limit_order_btn = "order-type-StopLimit"
|
||||
stop_market_order_btn = "order-type-StopMarket"
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
import pytest
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from actions.vega import submit_order
|
||||
from conftest import init_vega
|
||||
from fixtures.market import setup_continuous_market
|
||||
from actions.utils import wait_for_toast_confirmation
|
||||
from wallet_config import MM_WALLET, MM_WALLET2, TERMINATE_WALLET, wallets
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
stop_order_btn = "order-type-Stop"
|
||||
stop_limit_order_btn = "order-type-StopLimit"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from actions.utils import change_keys
|
||||
from actions.utils import wait_for_toast_confirmation
|
||||
from conftest import init_vega
|
||||
from fixtures.market import setup_continuous_market
|
||||
|
||||
@@ -39,7 +39,9 @@ def test_should_display_info_and_button_for_deposit(continuous_market, vega: Veg
|
||||
def test_should_show_an_error_if_your_balance_is_zero(continuous_market, vega: VegaService, page: Page):
|
||||
page.goto(f"/#/markets/{continuous_market}")
|
||||
vega.create_key("key_empty")
|
||||
change_keys(page, vega, "key_empty")
|
||||
page.get_by_test_id("manage-vega-wallet").click()
|
||||
page.locator('[role="menuitemradio"]').nth(4).click()
|
||||
page.reload()
|
||||
page.get_by_test_id(order_size).fill("200")
|
||||
page.get_by_test_id(order_price).fill("20")
|
||||
# 7002-SORD-060
|
||||
|
||||
@@ -4,8 +4,8 @@ import json
|
||||
from vega_sim.service import VegaService
|
||||
from fixtures.market import setup_simple_market
|
||||
from conftest import init_vega
|
||||
from collections import namedtuple
|
||||
from actions.vega import submit_order
|
||||
from wallet_config import MM_WALLET, TERMINATE_WALLET, wallets
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger()
|
||||
@@ -74,6 +74,16 @@ class TestGetStarted:
|
||||
|
||||
page.reload()
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET]
|
||||
|
||||
mint_amount: float = 10e5
|
||||
|
||||
for wallet in wallets:
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
import pytest
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import expect, Page
|
||||
from vega_sim.service import VegaService
|
||||
from actions.vega import submit_order
|
||||
from conftest import init_vega
|
||||
from fixtures.market import setup_continuous_market
|
||||
from wallet_config import MM_WALLET2
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET]
|
||||
|
||||
|
||||
def hover_and_assert_tooltip(page: Page, element_text):
|
||||
element = page.get_by_text(element_text)
|
||||
@@ -40,7 +52,7 @@ class TestIcebergOrdersValidations:
|
||||
vega.wait_fn(1)
|
||||
vega.wait_for_total_catchup()
|
||||
expect(page.get_by_test_id("toast-content")).to_have_text(
|
||||
"Order filledYour transaction has been confirmedView in block explorerSubmit order - filledBTC:DAI_2023+3 @ 107.00 tDAI"
|
||||
"Order filledYour transaction has been confirmed View in block explorerSubmit order - filledBTC:DAI_2023+3 @ 107.00 tDAI"
|
||||
)
|
||||
page.get_by_test_id("All").click()
|
||||
expect(
|
||||
|
||||
@@ -3,8 +3,7 @@ from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from conftest import init_vega
|
||||
from fixtures.market import setup_continuous_market
|
||||
from actions.utils import next_epoch, truncate_middle, change_keys
|
||||
|
||||
from actions.utils import next_epoch
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def vega(request):
|
||||
@@ -21,28 +20,19 @@ def continuous_market(vega):
|
||||
def test_liquidity_provision_amendment(continuous_market, vega: VegaService, page: Page):
|
||||
# TODO Refactor asserting the grid
|
||||
page.goto(f"/#/liquidity/{continuous_market}")
|
||||
change_keys(page, vega, "market_maker")
|
||||
page.get_by_test_id("manage-vega-wallet").click()
|
||||
#TODO Rename "mm" to "marketMaker" so that we don't have to specify where to click when switching wallets
|
||||
# Currently the default click will click the middle of the element which will click the copy wallet key button
|
||||
page.locator('[role="menuitemradio"] >> .mr-2.uppercase').nth(1).click(position={ "x": 0, "y": 0}, force=True)
|
||||
page.reload()
|
||||
row = page.get_by_test_id("tab-myLP").locator(".ag-center-cols-container .ag-row").first
|
||||
expect(row).to_contain_text(
|
||||
"Active"
|
||||
)
|
||||
# 5002-LIQP-006
|
||||
expect(page.get_by_test_id("target-stake")).to_have_text("Target stake5.82757 tDAI")
|
||||
# 5002-LIQP-007
|
||||
expect(page.get_by_test_id("supplied-stake")).to_have_text("Supplied stake10,000.00 tDAI")
|
||||
# 5002-LIQP-008
|
||||
expect(page.get_by_test_id("liquidity-supplied")).to_have_text("Liquidity supplied 171,598.11%")
|
||||
expect(page.get_by_test_id("fees-paid")).to_have_text("Fees paid-")
|
||||
# 5002-LIQP-009
|
||||
expect(page.get_by_test_id("liquidity-market-id")).to_have_text("Market ID" + truncate_middle(continuous_market))
|
||||
expect(page.get_by_test_id("liquidity-learn-more")).to_have_text("Learn moreProviding liquidity")
|
||||
# 002-LIQP-010
|
||||
expect(page.get_by_test_id("liquidity-learn-more").get_by_test_id("external-link")).to_have_attribute("href", "https://docs.vega.xyz/testnet/concepts/liquidity/provision")
|
||||
|
||||
vega.submit_simple_liquidity(
|
||||
key_name="market_maker",
|
||||
key_name="mm",
|
||||
market_id=continuous_market,
|
||||
commitment_amount=1,
|
||||
commitment_amount=100,
|
||||
fee=0.001,
|
||||
is_amendment=True,
|
||||
)
|
||||
@@ -56,30 +46,7 @@ def test_liquidity_provision_amendment(continuous_market, vega: VegaService, pag
|
||||
)
|
||||
next_epoch(vega=vega)
|
||||
page.reload()
|
||||
expect(page.get_by_test_id("supplied-stake")).to_have_text("Supplied stake1.00001 tDAI")
|
||||
expect(page.get_by_test_id("liquidity-supplied")).to_have_text("Liquidity supplied 17.16%")
|
||||
row = page.get_by_test_id("tab-myLP").locator(".ag-center-cols-container .ag-row").first
|
||||
expect(row).to_contain_text(
|
||||
"Active"
|
||||
)
|
||||
|
||||
@pytest.mark.skip("Waiting for the ability to cancel LP")
|
||||
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
|
||||
def test_liquidity_provision_inactive(continuous_market, vega: VegaService, page: Page):
|
||||
# TODO Refactor asserting the grid
|
||||
page.goto(f"/#/liquidity/{continuous_market}")
|
||||
change_keys(page,vega, "market_maker")
|
||||
row = page.get_by_test_id("tab-myLP").locator(".ag-center-cols-container .ag-row").first
|
||||
expect(row).to_contain_text(
|
||||
"Active"
|
||||
)
|
||||
vega.submit_simple_liquidity(
|
||||
key_name="market_maker",
|
||||
market_id=continuous_market,
|
||||
commitment_amount=0,
|
||||
fee=0,
|
||||
is_amendment=False,
|
||||
)
|
||||
vega.wait_fn(1)
|
||||
vega.wait_for_total_catchup()
|
||||
|
||||
)
|
||||
@@ -1,12 +1,23 @@
|
||||
import pytest
|
||||
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from vega_sim.service import VegaService, PeggedOrder
|
||||
from actions.vega import submit_order
|
||||
from wallet_config import MM_WALLET, MM_WALLET2
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
# Wallet Configurations
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET]
|
||||
|
||||
table_row_selector = (
|
||||
'[data-testid="tab-open-markets"] .ag-center-cols-container .ag-row'
|
||||
)
|
||||
@@ -74,7 +85,7 @@ def test_price_monitoring(simple_market, vega: VegaService, page: Page):
|
||||
time_in_force="TIME_IN_FORCE_GTC",
|
||||
volume=99,
|
||||
)
|
||||
#6002-MDET-009
|
||||
|
||||
expect(
|
||||
page.get_by_test_id(liquidity_supplied).get_by_test_id(item_value)
|
||||
).to_have_text("0.00 (0.00%)")
|
||||
@@ -192,7 +203,6 @@ def test_price_monitoring(simple_market, vega: VegaService, page: Page):
|
||||
# commented out because we have an issue #4233
|
||||
# expect(page.get_by_text("Opening auction")).to_be_hidden()
|
||||
|
||||
#6002-MDET-009
|
||||
expect(
|
||||
page.get_by_test_id(liquidity_supplied).get_by_test_id(item_value)
|
||||
).to_have_text("50.00 (>100%)")
|
||||
|
||||
@@ -25,15 +25,15 @@ def test_table_headers(page: Page, create_markets):
|
||||
headers = [
|
||||
"Market",
|
||||
"Description",
|
||||
"Settlement asset",
|
||||
"Trading mode",
|
||||
"Status",
|
||||
"Mark price",
|
||||
"24h volume",
|
||||
"Open Interest",
|
||||
"Settlement asset",
|
||||
"Spread",
|
||||
"",
|
||||
]
|
||||
|
||||
page.wait_for_selector('[data-testid="tab-open-markets"]', state="visible")
|
||||
page_headers = (
|
||||
page.get_by_test_id("tab-open-markets").locator(".ag-header-cell-text").all()
|
||||
@@ -157,4 +157,4 @@ def test_drag_and_drop_column(page: Page, create_markets):
|
||||
page.locator(col_instrument_code).drag_to(
|
||||
page.locator('.ag-header-row [col-id="data.bestBidPrice"]')
|
||||
)
|
||||
expect(page.locator(col_instrument_code)).to_have_attribute("aria-colindex", "9")
|
||||
expect(page.locator(col_instrument_code)).to_have_attribute("aria-colindex", "8")
|
||||
|
||||
@@ -1,11 +1,24 @@
|
||||
from math import exp
|
||||
import pytest
|
||||
import vega_sim.api.governance as governance
|
||||
import re
|
||||
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
|
||||
from conftest import init_vega
|
||||
from fixtures.market import setup_simple_market
|
||||
from wallet_config import MM_WALLET, MM_WALLET2, TERMINATE_WALLET, wallets
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET]
|
||||
|
||||
row_selector = '[data-testid="tab-proposed-markets"] .ag-center-cols-container .ag-row'
|
||||
col_market_id = '[col-id="market"] [data-testid="stack-cell-primary"]'
|
||||
@@ -16,6 +29,7 @@ def vega(request):
|
||||
with init_vega(request) as vega:
|
||||
yield vega
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def proposed_market(vega: VegaService):
|
||||
# setup market without liquidity provided
|
||||
@@ -40,6 +54,7 @@ def test_can_see_table_headers(proposed_market, page: Page):
|
||||
"Settlement asset",
|
||||
"State",
|
||||
"Parent market",
|
||||
"Voting",
|
||||
"Closing date",
|
||||
"Enactment date",
|
||||
"",
|
||||
@@ -68,6 +83,10 @@ def test_renders_markets_correctly(proposed_market, page: Page):
|
||||
row.locator('[col-id="terms.change.successorConfiguration.parentMarketId"]')
|
||||
).to_have_text("-")
|
||||
|
||||
# 6001-MARK-054
|
||||
# 6001-MARK-055
|
||||
expect(row.get_by_test_id("vote-progress-bar-against")).to_be_visible()
|
||||
|
||||
# 6001-MARK-056
|
||||
expect(row.locator('[col-id="closing-date"]')).not_to_be_empty()
|
||||
|
||||
@@ -105,8 +124,8 @@ def test_can_drag_and_drop_columns(proposed_market, page: Page):
|
||||
page.goto("/#/markets/all")
|
||||
page.click('[data-testid="Proposed markets"]')
|
||||
col_market = page.locator('[col-id="market"]').first
|
||||
col_state = page.locator('[col-id="state"]').first
|
||||
col_market.drag_to(col_state)
|
||||
col_vote = page.locator('[col-id="voting"]').first
|
||||
col_market.drag_to(col_vote)
|
||||
|
||||
# Check the attribute of the dragged element
|
||||
attribute_value = col_market.get_attribute("aria-colindex")
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
import pytest
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from actions.vega import submit_order
|
||||
from fixtures.market import setup_simple_market
|
||||
from conftest import init_vega
|
||||
|
||||
from actions.utils import wait_for_toast_confirmation
|
||||
from wallet_config import MM_WALLET, MM_WALLET2
|
||||
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET]
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def vega(request):
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
import pytest
|
||||
import vega_sim.api.governance as governance
|
||||
import re
|
||||
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService, PeggedOrder
|
||||
import vega_sim.proto.vega as vega_protos
|
||||
import vega_sim.api.governance as governance
|
||||
from actions.vega import submit_order
|
||||
from wallet_config import MM_WALLET, MM_WALLET2, GOVERNANCE_WALLET
|
||||
from fixtures.market import setup_continuous_market
|
||||
from datetime import datetime
|
||||
from datetime import timedelta
|
||||
from vega_sim.service import MarketStateUpdateType
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
GOVERNANCE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, GOVERNANCE_WALLET]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("vega", "page", "proposed_market", "risk_accepted")
|
||||
@@ -20,9 +36,6 @@ def test_market_lifecycle(proposed_market, vega: VegaService, page: Page):
|
||||
page.goto(f"/#/markets/{market_id}")
|
||||
|
||||
# check that market is in proposed state
|
||||
# 6002-MDET-006
|
||||
# 6002-MDET-007
|
||||
# 7002-SORD-061
|
||||
expect(trading_mode).to_have_text("No trading")
|
||||
expect(market_state).to_have_text("Proposed")
|
||||
|
||||
@@ -122,7 +135,7 @@ def test_market_closing_banners(page: Page, continuous_market, vega: VegaService
|
||||
page.goto(f"/#/markets/{market_id}")
|
||||
proposalID = vega.update_market_state(
|
||||
continuous_market,
|
||||
"market_maker",
|
||||
"mm",
|
||||
MarketStateUpdateType.Terminate,
|
||||
approve_proposal=False,
|
||||
vote_enactment_time = datetime.now() + timedelta(weeks=1),
|
||||
@@ -135,7 +148,7 @@ def test_market_closing_banners(page: Page, continuous_market, vega: VegaService
|
||||
|
||||
vega.update_market_state(
|
||||
continuous_market,
|
||||
"market_maker",
|
||||
"mm",
|
||||
MarketStateUpdateType.Terminate,
|
||||
approve_proposal=False,
|
||||
vote_enactment_time = datetime.now() + timedelta(weeks=1),
|
||||
@@ -148,7 +161,7 @@ def test_market_closing_banners(page: Page, continuous_market, vega: VegaService
|
||||
governance.approve_proposal(
|
||||
proposal_id=proposalID,
|
||||
wallet=vega.wallet,
|
||||
key_name="market_maker"
|
||||
key_name="mm"
|
||||
|
||||
)
|
||||
vega.forward("60s")
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import pytest
|
||||
from collections import namedtuple
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from typing import List
|
||||
from actions.vega import submit_order, submit_liquidity, submit_multiple_orders
|
||||
from conftest import init_vega
|
||||
from fixtures.market import setup_simple_market
|
||||
from wallet_config import MM_WALLET, MM_WALLET2
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("mm", "pin")
|
||||
MM_WALLET2 = WalletConfig("mm2", "pin2")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def vega():
|
||||
|
||||
@@ -2,7 +2,6 @@ import pytest
|
||||
from playwright.sync_api import Page
|
||||
from vega_sim.service import VegaService
|
||||
from actions.vega import submit_order
|
||||
from actions.utils import change_keys
|
||||
|
||||
def check_pnl_color_value(element, expected_color, expected_value):
|
||||
color = element.evaluate("element => getComputedStyle(element).color")
|
||||
@@ -30,16 +29,18 @@ def test_pnl(continuous_market, vega: VegaService, page: Page):
|
||||
check_pnl_color_value(unrealised_pnl, "rgb(236, 0, 60)", "-4.00")
|
||||
|
||||
# profit Trading unrealised
|
||||
change_keys(page, vega, "market_maker")
|
||||
page.get_by_test_id("manage-vega-wallet").click()
|
||||
page.locator('[role="menuitemradio"] >> .mr-2.uppercase').nth(1).click(position={ "x": 0, "y": 0}, force=True)
|
||||
check_pnl_color_value(realised_pnl, "rgb(0, 0, 0)", "0.00")
|
||||
check_pnl_color_value(unrealised_pnl, "rgb(1, 145, 75)", "4.00")
|
||||
|
||||
# neutral Trading unrealised
|
||||
change_keys(page, vega, "market_maker_2")
|
||||
page.locator('[role="menuitemradio"] >> .mr-2.uppercase').nth(2).click(position={ "x": 0, "y": 0}, force=True)
|
||||
check_pnl_color_value(realised_pnl, "rgb(0, 0, 0)", "0.00")
|
||||
check_pnl_color_value(unrealised_pnl, "rgb(0, 0, 0)", "0.00")
|
||||
|
||||
# Portfolio Unrealised
|
||||
page.get_by_test_id("manage-vega-wallet").click(force=True)
|
||||
page.get_by_role("link", name="Portfolio").click()
|
||||
page.get_by_test_id("Positions").click()
|
||||
page.wait_for_selector(
|
||||
@@ -51,10 +52,10 @@ def test_pnl(continuous_market, vega: VegaService, page: Page):
|
||||
'//div[@role="row" and .//div[@col-id="partyId"]/div/span[text()="Key 1"]]'
|
||||
)
|
||||
key_mm = page.query_selector(
|
||||
'//div[@role="row" and .//div[@col-id="partyId"]/div/span[text()="market_maker"]]'
|
||||
'//div[@role="row" and .//div[@col-id="partyId"]/div/span[text()="mm"]]'
|
||||
)
|
||||
key_mm2 = page.query_selector(
|
||||
'//div[@role="row" and .//div[@col-id="partyId"]/div/span[text()="market_maker_2"]]'
|
||||
'//div[@role="row" and .//div[@col-id="partyId"]/div/span[text()="mm2"]]'
|
||||
)
|
||||
|
||||
key_1_unrealised_pnl = key_1.query_selector('xpath=./div[@col-id="unrealisedPNL"]')
|
||||
@@ -100,11 +101,12 @@ def test_pnl(continuous_market, vega: VegaService, page: Page):
|
||||
check_pnl_color_value(unrealised_pnl, "rgb(0, 0, 0)", "0.00")
|
||||
|
||||
# profit trading realised
|
||||
change_keys(page, vega, "market_maker")
|
||||
page.get_by_test_id("manage-vega-wallet").click()
|
||||
page.locator('[role="menuitemradio"] >> .mr-2.uppercase').nth(1).click(position={ "x": 0, "y": 0}, force=True)
|
||||
check_pnl_color_value(realised_pnl, "rgb(1, 145, 75)", "8.00")
|
||||
check_pnl_color_value(unrealised_pnl, "rgb(0, 0, 0)", "0.00")
|
||||
|
||||
# loss trading realised
|
||||
change_keys(page, vega, "Key 1")
|
||||
page.locator('[role="menuitemradio"] >> .mr-2.uppercase').nth(0).click(position={ "x": 0, "y": 0}, force=True)
|
||||
check_pnl_color_value(realised_pnl, "rgb(236, 0, 60)", "-8.00")
|
||||
check_pnl_color_value(unrealised_pnl, "rgb(0, 0, 0)", "0.00")
|
||||
|
||||
@@ -32,12 +32,12 @@ def test_share_usage_data(page: Page):
|
||||
|
||||
# Define a mapping of icon selectors to toast selectors
|
||||
ICON_TO_TOAST = {
|
||||
'aria-label="arrow-top-left icon"': 'class="relative flex-1 overflow-auto p-4 pr-[40px] [&>p]:mb-[2.5px]"',
|
||||
'aria-label="arrow-up icon"': 'class="relative flex-1 overflow-auto p-4 pr-[40px] [&>p]:mb-[2.5px]"',
|
||||
'aria-label="arrow-top-right icon"': 'class="relative flex-1 overflow-auto p-4 pr-[40px] [&>p]:mb-[2.5px]"',
|
||||
'aria-label="arrow-bottom-left icon"': 'class="relative flex-1 overflow-auto p-4 pr-[40px] [&>p]:mb-[2.5px]"',
|
||||
'aria-label="arrow-down icon"': 'class="relative flex-1 overflow-auto p-4 pr-[40px] [&>p]:mb-[2.5px]"',
|
||||
'aria-label="arrow-bottom-right icon"': 'class="relative flex-1 overflow-auto p-4 pr-[40px] [&>p]:mb-[2.5px]"',
|
||||
'aria-label="arrow-top-left icon"': 'class="group absolute z-20 top-0 left-0 max-w-full max-h-full overflow-x-hidden overflow-y-auto p-4"',
|
||||
'aria-label="arrow-up icon"': 'class="group absolute z-20 top-0 left-[50%] translate-x-[-50%] max-w-full max-h-full overflow-x-hidden overflow-y-auto p-4"',
|
||||
'aria-label="arrow-top-right icon"': 'class="group absolute z-20 top-0 right-0 max-w-full max-h-full overflow-x-hidden overflow-y-auto p-4"',
|
||||
'aria-label="arrow-bottom-left icon"': 'class="group absolute z-20 bottom-0 left-0 max-w-full max-h-full overflow-x-hidden overflow-y-auto p-4"',
|
||||
'aria-label="arrow-down icon"': 'class="group absolute z-20 bottom-0 left-[50%] translate-x-[-50%] max-w-full max-h-full overflow-x-hidden overflow-y-auto p-4"',
|
||||
'aria-label="arrow-bottom-right icon"': 'class="group absolute z-20 bottom-0 right-0 max-w-full max-h-full overflow-x-hidden overflow-y-auto p-4"',
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
# page.goto(f"/#/markets/{continuous_market}")
|
||||
# vega.forward("24h")
|
||||
# vega.wait_for_total_catchup()
|
||||
# submit_order(vega, "market_maker", continuous_market, "SIDE_SELL", 1, 101.50000)
|
||||
# submit_order(vega, "market_maker_2", continuous_market, "SIDE_SELL", 1, 101.50000)
|
||||
# submit_order(vega, "mm", continuous_market, "SIDE_SELL", 1, 101.50000)
|
||||
# submit_order(vega, "mm2", continuous_market, "SIDE_SELL", 1, 101.50000)
|
||||
# vega.forward("10s")
|
||||
# vega.wait_for_total_catchup()
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import pytest
|
||||
import re
|
||||
from playwright.sync_api import Page, expect
|
||||
from vega_sim.service import VegaService
|
||||
from actions.utils import wait_for_toast_confirmation, create_and_faucet_wallet, WalletConfig, next_epoch, change_keys
|
||||
from actions.utils import wait_for_toast_confirmation, create_and_faucet_wallet, WalletConfig, next_epoch
|
||||
import vega_sim.proto.vega as vega_protos
|
||||
|
||||
LIQ = WalletConfig("liq", "liq")
|
||||
@@ -42,7 +42,7 @@ def test_transfer_submit(continuous_market, vega: VegaService, page: Page):
|
||||
vega.forward("10s")
|
||||
vega.wait_fn(1)
|
||||
vega.wait_for_total_catchup()
|
||||
expected_confirmation_text = re.compile(r"Transfer completeYour transaction has been confirmedView in block explorerTransferTo .{6}….{6}1\.00 tDAI")
|
||||
expected_confirmation_text = re.compile(r"Transfer completeYour transaction has been confirmed View in block explorerTransferTo .{6}….{6}1\.00 tDAI")
|
||||
actual_confirmation_text = page.get_by_test_id('toast-content').text_content()
|
||||
assert expected_confirmation_text.search(actual_confirmation_text), f"Expected pattern not found in {actual_confirmation_text}"
|
||||
|
||||
@@ -50,7 +50,7 @@ def test_transfer_submit(continuous_market, vega: VegaService, page: Page):
|
||||
@pytest.mark.usefixtures("page", "auth", "risk_accepted")
|
||||
def test_transfer_vesting_below_minimum(continuous_market, vega: VegaService, page: Page):
|
||||
vega.update_network_parameter(
|
||||
"market_maker", parameter="transfer.minTransferQuantumMultiple", new_value="100000"
|
||||
"mm", parameter="transfer.minTransferQuantumMultiple", new_value="100000"
|
||||
)
|
||||
vega.wait_for_total_catchup()
|
||||
|
||||
@@ -97,7 +97,9 @@ def test_transfer_vesting_below_minimum(continuous_market, vega: VegaService, pa
|
||||
page.goto('/#/portfolio')
|
||||
expect(page.get_by_test_id('transfer-form')).to_be_visible
|
||||
|
||||
change_keys(page, vega, "party_b")
|
||||
page.get_by_test_id("manage-vega-wallet").click()
|
||||
page.locator('[role="menuitemradio"]').nth(5).click()
|
||||
page.reload()
|
||||
page.get_by_test_id('select-asset').click()
|
||||
page.get_by_test_id('rich-select-option').click()
|
||||
|
||||
@@ -127,6 +129,6 @@ def test_transfer_vesting_below_minimum(continuous_market, vega: VegaService, pa
|
||||
vega.forward("10s")
|
||||
vega.wait_fn(1)
|
||||
vega.wait_for_total_catchup()
|
||||
expected_confirmation_text = re.compile(r"Transfer completeYour transaction has been confirmedView in block explorerTransferTo .{6}….{6}0\.00001 tDAI")
|
||||
expected_confirmation_text = re.compile(r"Transfer completeYour transaction has been confirmed View in block explorerTransferTo .{6}….{6}0\.00001 tDAI")
|
||||
actual_confirmation_text = page.get_by_test_id('toast-content').text_content()
|
||||
assert expected_confirmation_text.search(actual_confirmation_text), f"Expected pattern not found in {actual_confirmation_text}"
|
||||
@@ -1,12 +0,0 @@
|
||||
from collections import namedtuple
|
||||
|
||||
# Defined namedtuples
|
||||
WalletConfig = namedtuple("WalletConfig", ["name", "passphrase"])
|
||||
|
||||
# Wallet Configurations
|
||||
MM_WALLET = WalletConfig("market_maker", "pin")
|
||||
MM_WALLET2 = WalletConfig("market_maker_2", "pin2")
|
||||
TERMINATE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
GOVERNANCE_WALLET = WalletConfig("FJMKnwfZdd48C8NqvYrG", "bY3DxwtsCstMIIZdNpKs")
|
||||
|
||||
wallets = [MM_WALLET, MM_WALLET2, TERMINATE_WALLET, GOVERNANCE_WALLET]
|
||||
@@ -66,18 +66,7 @@ i18n
|
||||
'environment',
|
||||
'fills',
|
||||
'funding-payments',
|
||||
'ledger',
|
||||
'liquidity',
|
||||
'market-depth',
|
||||
'markets',
|
||||
'orders',
|
||||
'positions',
|
||||
'trades',
|
||||
'trading',
|
||||
'ui-toolkit',
|
||||
'utils',
|
||||
'wallet',
|
||||
'web3',
|
||||
],
|
||||
defaultNS: 'trading',
|
||||
nsSeparator: false,
|
||||
|
||||
@@ -18,7 +18,7 @@ import { Routes as AppRoutes } from '../lib/links';
|
||||
import { LayoutWithSky } from '../client-pages/referrals/layout';
|
||||
import { Referrals } from '../client-pages/referrals/referrals';
|
||||
import { ReferralStatistics } from '../client-pages/referrals/referral-statistics';
|
||||
import { ApplyCodeFormContainer } from '../client-pages/referrals/apply-code-form';
|
||||
import { ApplyCodeForm } from '../client-pages/referrals/apply-code-form';
|
||||
import { CreateCodeContainer } from '../client-pages/referrals/create-code-form';
|
||||
import { NotFound as ReferralNotFound } from '../client-pages/referrals/error-boundary';
|
||||
import { compact } from 'lodash';
|
||||
@@ -79,7 +79,7 @@ export const routerConfig: RouteObject[] = compact([
|
||||
},
|
||||
{
|
||||
path: AppRoutes.REFERRALS_APPLY_CODE,
|
||||
element: <ApplyCodeFormContainer />,
|
||||
element: <ApplyCodeForm />,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useEthereumTransactionToasts } from '@vegaprotocol/web3';
|
||||
import { useEthereumWithdrawApprovalsToasts } from '@vegaprotocol/web3';
|
||||
import { useReadyToWithdrawalToasts } from '@vegaprotocol/withdraws';
|
||||
import { Links } from '../lib/links';
|
||||
import { useReferralToasts } from '../client-pages/referrals/hooks/use-referral-toasts';
|
||||
|
||||
export const ToastsManager = () => {
|
||||
useProposalToasts();
|
||||
@@ -15,7 +14,6 @@ export const ToastsManager = () => {
|
||||
useReadyToWithdrawalToasts({
|
||||
withdrawalsLink: Links.PORTFOLIO(),
|
||||
});
|
||||
useReferralToasts();
|
||||
|
||||
const toasts = useToasts((store) => store.toasts);
|
||||
return <ToastsContainer order="desc" toasts={toasts} />;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import { act, render, screen, within } from '@testing-library/react';
|
||||
import * as Types from '@vegaprotocol/types';
|
||||
import type { AccountFields } from './accounts-data-provider';
|
||||
import { getAccountData } from './accounts-data-provider';
|
||||
@@ -123,11 +123,13 @@ describe('AccountsTable', () => {
|
||||
/>
|
||||
);
|
||||
|
||||
const cells = await screen.findAllByRole('gridcell');
|
||||
const expectedValues = ['tBTC', '1,256.00', '1,256.00', '2,512.00', ''];
|
||||
cells.forEach((cell, i) => {
|
||||
expect(cell).toHaveTextContent(expectedValues[i]);
|
||||
await assertCells({
|
||||
usedAmount: '1,256',
|
||||
usedPct: '0.00%',
|
||||
available: '1,256',
|
||||
total: '2,512',
|
||||
});
|
||||
|
||||
const rows = container.querySelector('.ag-center-cols-container');
|
||||
expect(rows?.childElementCount).toBe(1);
|
||||
});
|
||||
@@ -160,12 +162,13 @@ describe('AccountsTable', () => {
|
||||
/>
|
||||
);
|
||||
|
||||
const cells = await screen.findAllByRole('gridcell');
|
||||
const expectedValues = ['tBTC', '1,256.00', '1,256.00', '2,512.00', ''];
|
||||
expect(cells.length).toBe(expectedValues.length);
|
||||
cells.forEach((cell, i) => {
|
||||
expect(cell).toHaveTextContent(expectedValues[i]);
|
||||
await assertCells({
|
||||
usedAmount: '1,256',
|
||||
usedPct: '0.00%',
|
||||
available: '1,256',
|
||||
total: '2,512',
|
||||
});
|
||||
|
||||
const rows = container.querySelector('.ag-center-cols-container');
|
||||
expect(rows?.childElementCount).toBe(1);
|
||||
});
|
||||
@@ -248,4 +251,36 @@ describe('AccountsTable', () => {
|
||||
];
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
const assertCells = async ({
|
||||
usedAmount,
|
||||
usedPct,
|
||||
available,
|
||||
total,
|
||||
}: {
|
||||
usedAmount: string;
|
||||
usedPct: string;
|
||||
available: string;
|
||||
total: string;
|
||||
}) => {
|
||||
const cells = await screen.findAllByRole('gridcell');
|
||||
|
||||
const usedCell = within(
|
||||
cells.find(
|
||||
(cell) => cell.getAttribute('col-id') === 'used'
|
||||
) as HTMLElement
|
||||
);
|
||||
expect(usedCell.getByTestId('used-amount')).toHaveTextContent(usedAmount);
|
||||
expect(usedCell.getByTestId('used-pct')).toHaveTextContent(usedPct);
|
||||
|
||||
const availableCell = cells.find(
|
||||
(cell) => cell.getAttribute('col-id') === 'available'
|
||||
);
|
||||
expect(availableCell).toHaveTextContent(available);
|
||||
|
||||
const totalCell = cells.find(
|
||||
(cell) => cell.getAttribute('col-id') === 'total'
|
||||
);
|
||||
expect(totalCell).toHaveTextContent(total);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -178,20 +178,28 @@ export const AccountTable = ({
|
||||
|
||||
return data.breakdown ? (
|
||||
<>
|
||||
<span className="underline">{valueFormatted}</span>
|
||||
<span className="underline" data-testid="used-amount">
|
||||
{valueFormatted}
|
||||
</span>
|
||||
<span
|
||||
className={classNames(
|
||||
colorClass(percentageUsed),
|
||||
'ml-1 inline-block w-14'
|
||||
)}
|
||||
data-testid="used-pct"
|
||||
>
|
||||
{percentageUsed.toFixed(2)}%
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="underline">{valueFormatted}</span>
|
||||
<span className="inline-block ml-2 w-14 text-muted">
|
||||
<span className="underline" data-testid="used-amount">
|
||||
{valueFormatted}
|
||||
</span>
|
||||
<span
|
||||
className="inline-block ml-2 w-14 text-muted"
|
||||
data-testid="used-pct"
|
||||
>
|
||||
{(0).toFixed(2)}%
|
||||
</span>
|
||||
</>
|
||||
|
||||
@@ -63,9 +63,9 @@ describe('BreakdownTable', () => {
|
||||
const expectedValues = [
|
||||
'BTCUSD.MF21',
|
||||
'Margin',
|
||||
'1,256.00 (50%)',
|
||||
'1,256.00',
|
||||
'1,256.00',
|
||||
'1,256 (50%)',
|
||||
'1,256',
|
||||
'1,256',
|
||||
];
|
||||
cells.slice(0, -1).forEach((cell, i) => {
|
||||
expect(cell).toHaveTextContent(expectedValues[i]);
|
||||
|
||||
@@ -74,7 +74,7 @@ describe('MarginHealthChart', () => {
|
||||
it('should render correct values', async () => {
|
||||
render(<MarginHealthChart marketId="marketId" assetId="assetId" />);
|
||||
const chart = screen.getByTestId('margin-health-chart');
|
||||
expect(chart).toHaveTextContent('3.00 above maintenance level');
|
||||
expect(chart).toHaveTextContent('3 above maintenance level');
|
||||
const red = screen.getByTestId('margin-health-chart-red');
|
||||
const orange = screen.getByTestId('margin-health-chart-orange');
|
||||
const yellow = screen.getByTestId('margin-health-chart-yellow');
|
||||
@@ -121,7 +121,7 @@ describe('MarginHealthChartTooltip', () => {
|
||||
expect(value).toHaveTextContent(expectedLabels[i]);
|
||||
});
|
||||
const values = await screen.findAllByTestId('margin-health-tooltip-value');
|
||||
const expectedValues = ['4.00', '5.00', '6.00', '8.00', '10.00'];
|
||||
const expectedValues = ['4', '5', '6', '8', '10'];
|
||||
values.forEach((value, i) => {
|
||||
expect(value).toHaveTextContent(expectedValues[i]);
|
||||
});
|
||||
@@ -137,7 +137,7 @@ describe('MarginHealthChartTooltip', () => {
|
||||
);
|
||||
|
||||
let values = await screen.findAllByTestId('margin-health-tooltip-value');
|
||||
expect(values[2]).toHaveTextContent('7.00');
|
||||
expect(values[2]).toHaveTextContent('7');
|
||||
|
||||
rerender(
|
||||
<MarginHealthChartTooltip
|
||||
@@ -149,6 +149,6 @@ describe('MarginHealthChartTooltip', () => {
|
||||
|
||||
values = await screen.findAllByTestId('margin-health-tooltip-value');
|
||||
expect(values.length).toBe(5);
|
||||
expect(values[3]).toHaveTextContent('9.00');
|
||||
expect(values[3]).toHaveTextContent('9');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,7 +39,6 @@ export const AgGridThemed = ({
|
||||
ref={gridRef}
|
||||
overlayLoadingTemplate={t('Loading...')}
|
||||
overlayNoRowsTemplate={t('No data')}
|
||||
suppressDragLeaveHidesColumns
|
||||
{...defaultProps}
|
||||
{...props}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { memo } from 'react';
|
||||
import { addDecimalsFixedFormatNumber } from '@vegaprotocol/utils';
|
||||
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
|
||||
import { NumericCell } from './numeric-cell';
|
||||
import { theme } from '@vegaprotocol/tailwindcss-config';
|
||||
|
||||
@@ -57,7 +57,7 @@ export const CumulativeVol = memo(
|
||||
(
|
||||
<NumericCell
|
||||
value={Number(indicativeVolume)}
|
||||
valueFormatted={addDecimalsFixedFormatNumber(
|
||||
valueFormatted={addDecimalsFormatNumber(
|
||||
indicativeVolume,
|
||||
positionDecimalPlaces ?? 0
|
||||
)}
|
||||
@@ -69,7 +69,7 @@ export const CumulativeVol = memo(
|
||||
{ask ? (
|
||||
<NumericCell
|
||||
value={ask}
|
||||
valueFormatted={addDecimalsFixedFormatNumber(
|
||||
valueFormatted={addDecimalsFormatNumber(
|
||||
ask,
|
||||
positionDecimalPlaces ?? 0
|
||||
)}
|
||||
@@ -79,7 +79,7 @@ export const CumulativeVol = memo(
|
||||
{bid ? (
|
||||
<NumericCell
|
||||
value={ask}
|
||||
valueFormatted={addDecimalsFixedFormatNumber(
|
||||
valueFormatted={addDecimalsFormatNumber(
|
||||
bid,
|
||||
positionDecimalPlaces ?? 0
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { forwardRef } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { getDecimalSeparator, isNumeric } from '@vegaprotocol/utils';
|
||||
import { getNumberParts, isNumeric } from '@vegaprotocol/utils';
|
||||
|
||||
interface NumericCellProps {
|
||||
value: number | bigint | null | undefined;
|
||||
@@ -23,7 +23,7 @@ export const NumericCell = forwardRef<HTMLSpanElement, NumericCellProps>(
|
||||
);
|
||||
}
|
||||
|
||||
const decimalSeparator = getDecimalSeparator();
|
||||
const decimalSeparator = getNumberParts().decimalSeparator;
|
||||
const valueSplit: string[] = decimalSeparator
|
||||
? valueFormatted.split(decimalSeparator).map((v) => `${v}`)
|
||||
: [`${value}`];
|
||||
|
||||
@@ -10,12 +10,12 @@ describe('PriceChangeCell', () => {
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText('-48.51%')).toBeInTheDocument();
|
||||
expect(screen.getByText('-22.10')).toBeInTheDocument();
|
||||
expect(screen.getByText('-22.100')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders correctly and calculates the price change without decimals', () => {
|
||||
render(<PriceChangeCell candles={['45556', '678678', '23456']} />);
|
||||
expect(screen.getByText('-48.51%')).toBeInTheDocument();
|
||||
expect(screen.getByText('-22,100.00')).toBeInTheDocument();
|
||||
expect(screen.getByText('-22,100.000')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -136,7 +136,7 @@ describe('StopOrder', () => {
|
||||
await userEvent.type(screen.getByTestId(sizeInput), '10');
|
||||
await userEvent.type(screen.getByTestId(priceInput), '10');
|
||||
expect(screen.getByTestId('deal-ticket-fee-notional')).toHaveTextContent(
|
||||
'Notional100.00 BTC'
|
||||
'Notional100 BTC'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -147,13 +147,13 @@ describe('StopOrder', () => {
|
||||
await userEvent.type(screen.getByTestId(sizeInput), '10');
|
||||
// price trigger is selected but it's empty, calculate base on size and marketPrice prop
|
||||
expect(screen.getByTestId('deal-ticket-fee-notional')).toHaveTextContent(
|
||||
'Notional20.00 BTC'
|
||||
'Notional20 BTC'
|
||||
);
|
||||
|
||||
await userEvent.type(screen.getByTestId(triggerPriceInput), '3');
|
||||
// calculate base on size and price trigger
|
||||
expect(screen.getByTestId('deal-ticket-fee-notional')).toHaveTextContent(
|
||||
'Notional30.00 BTC'
|
||||
'Notional30 BTC'
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -84,11 +84,11 @@ describe('FillsTable', () => {
|
||||
const cells = screen.getAllByRole('gridcell');
|
||||
const expectedValues = [
|
||||
buyerFill.market?.tradableInstrument.instrument.code || '',
|
||||
'+3.00',
|
||||
'1.00 BTC',
|
||||
'+3',
|
||||
'1 BTC',
|
||||
'3.00 BTC',
|
||||
'Maker',
|
||||
'2.00 BTC',
|
||||
'2 BTC',
|
||||
'0.27 BTC',
|
||||
getDateTimeFormat().format(new Date(buyerFill.createdAt)),
|
||||
'', // action column
|
||||
@@ -121,8 +121,8 @@ describe('FillsTable', () => {
|
||||
const cells = screen.getAllByRole('gridcell');
|
||||
const expectedValues = [
|
||||
buyerFill.market?.tradableInstrument.instrument.code || '',
|
||||
'-3.00',
|
||||
'1.00 BTC',
|
||||
'-3',
|
||||
'1 BTC',
|
||||
'3.00 BTC',
|
||||
'Taker',
|
||||
'0.03 BTC',
|
||||
@@ -158,8 +158,8 @@ describe('FillsTable', () => {
|
||||
const cells = screen.getAllByRole('gridcell');
|
||||
const expectedValues = [
|
||||
buyerFill.market?.tradableInstrument.instrument.code || '',
|
||||
'-3.00',
|
||||
'1.00 BTC',
|
||||
'-3',
|
||||
'1 BTC',
|
||||
'3.00 BTC',
|
||||
'-',
|
||||
'0.03 BTC',
|
||||
|
||||
@@ -55,7 +55,7 @@ describe('FundingPaymentsTable', () => {
|
||||
const cells = screen.getAllByRole('gridcell');
|
||||
const expectedValues = [
|
||||
fundingPayment.market?.tradableInstrument.instrument.code || '',
|
||||
'1.00 BTC',
|
||||
'1 BTC',
|
||||
getDateTimeFormat().format(new Date(fundingPayment.timestamp)),
|
||||
];
|
||||
cells.forEach((cell, i) => {
|
||||
@@ -77,7 +77,7 @@ describe('FundingPaymentsTable', () => {
|
||||
const cells = screen.getAllByRole('gridcell');
|
||||
const expectedValues = [
|
||||
fundingPayment.market?.tradableInstrument.instrument.code || '',
|
||||
'-1.00 BTC',
|
||||
'-1 BTC',
|
||||
getDateTimeFormat().format(new Date(fundingPayment.timestamp)),
|
||||
];
|
||||
cells.forEach((cell, i) => {
|
||||
|
||||
@@ -17,7 +17,6 @@ import en_proposals from './locales/en/proposals.json';
|
||||
import en_positions from './locales/en/positions.json';
|
||||
import en_trades from './locales/en/trading.json';
|
||||
import en_ui_toolkit from './locales/en/ui-toolkit.json';
|
||||
import en_wallet from './locales/en/wallet.json';
|
||||
|
||||
export const locales = {
|
||||
en: {
|
||||
@@ -38,6 +37,5 @@ export const locales = {
|
||||
proposals: en_proposals,
|
||||
trades: en_trades,
|
||||
'ui-toolkit': en_ui_toolkit,
|
||||
wallet: en_wallet,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -139,5 +139,5 @@
|
||||
"View settlement data specification": "View settlement data specification",
|
||||
"View settlement schedule specification": "View settlement schedule specification",
|
||||
"View termination specification": "View termination specification",
|
||||
"Within {{horizonSecs}} seconds": "Within {{horizonSecs}} seconds"
|
||||
"Within %s seconds": "Within %s seconds"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
"(Combined set volume {{runningVolume}} over last {{epochs}} epochs)": "(Combined set volume {{runningVolume}} over last {{epochs}} epochs)",
|
||||
"(Created at: {{createdAt}})": "(Created at: {{createdAt}})",
|
||||
"{{amount}} $VEGA staked": "{{amount}} $VEGA staked",
|
||||
"{{assetSymbol}} Reward pot": "{{assetSymbol}} Reward pot",
|
||||
"{{checkedAssets}} Assets": "{{checkedAssets}} Assets",
|
||||
"{{distance}} ago": "{{distance}} ago",
|
||||
"{{instrumentCode}} liquidity provision": "{{instrumentCode}} liquidity provision",
|
||||
@@ -18,9 +17,7 @@
|
||||
"Anyone with the referral link can apply it to their key(s) of choice via an on chain transaction": "Anyone with the referral link can apply it to their key(s) of choice via an on chain transaction",
|
||||
"Asset (1)": "Asset (1)",
|
||||
"Assets": "Assets",
|
||||
"Available to withdraw this epoch": "Available to withdraw this epoch",
|
||||
"Base commission rate": "Base commission rate",
|
||||
"Base rate": "Base rate",
|
||||
"Best bid": "Best bid",
|
||||
"Best offer": "Best offer",
|
||||
"Browse": "Browse",
|
||||
@@ -74,7 +71,6 @@
|
||||
"Discounts are applied automatically during trading based on the key(s) used": "Discounts are applied automatically during trading based on the key(s) used",
|
||||
"Docs": "Docs",
|
||||
"Earn commission & stake rewards": "Earn commission & stake rewards",
|
||||
"Earned by me": "Earned by me",
|
||||
"Enactment date reached and usual auction exit checks pass": "Enactment date reached and usual auction exit checks pass",
|
||||
"Environment not configured": "Environment not configured",
|
||||
"epochs in referral set": "epochs in referral set",
|
||||
@@ -100,7 +96,6 @@
|
||||
"Funding Rate": "Funding Rate",
|
||||
"Funding rate": "Funding rate",
|
||||
"Futures": "Futures",
|
||||
"From epoch": "From epoch",
|
||||
"Generate a referral code to share with your friends and start earning commission.": "Generate a referral code to share with your friends and start earning commission.",
|
||||
"Generate code": "Generate code",
|
||||
"Get started": "Get started",
|
||||
@@ -114,7 +109,6 @@
|
||||
"Help identify bugs and improve the service by sharing anonymous usage data.": "Help identify bugs and improve the service by sharing anonymous usage data.",
|
||||
"Help us identify bugs and improve Vega Governance by sharing anonymous usage data.": "Help us identify bugs and improve Vega Governance by sharing anonymous usage data.",
|
||||
"Hide closed markets": "Hide closed markets",
|
||||
"Hoarder reward multiplier": "Hoarder reward multiplier",
|
||||
"How it works": "How it works",
|
||||
"I want a code": "I want a code",
|
||||
"Improve vega console": "Improve vega console",
|
||||
@@ -128,7 +122,6 @@
|
||||
"Liquidity": "Liquidity",
|
||||
"Liquidity fees": "Liquidity fees",
|
||||
"Liquidity supplied": "Liquidity supplied",
|
||||
"Locked {{assetSymbol}}": "Locked {{assetSymbol}}",
|
||||
"Low fees and no cost to place orders": "Low fees and no cost to place orders",
|
||||
"Mainnet status & incidents": "Mainnet status & incidents",
|
||||
"Make withdrawal": "Make withdrawal",
|
||||
@@ -164,7 +157,6 @@
|
||||
"No perpetual markets.": "No perpetual markets.",
|
||||
"No referral program active": "No referral program active",
|
||||
"No rejected orders": "No rejected orders",
|
||||
"No rewards": "No rewards",
|
||||
"No thanks": "No thanks",
|
||||
"No third party has access to your funds.": "No third party has access to your funds.",
|
||||
"No volume discount program active": "No volume discount program active",
|
||||
@@ -173,7 +165,6 @@
|
||||
"Non-custodial and pseudonymous": "Non-custodial and pseudonymous",
|
||||
"None": "None",
|
||||
"Number of traders": "Number of traders",
|
||||
"Not connected": "Not connected",
|
||||
"Open": "Open",
|
||||
"Open a position": "Open a position",
|
||||
"Open markets": "Open markets",
|
||||
@@ -185,7 +176,7 @@
|
||||
"Parent of a market": "Parent of a market",
|
||||
"Past {{count}} epochs": "Past {{count}} epochs",
|
||||
"Perpetuals": "Perpetuals",
|
||||
"Please choose another market from the <0>market list</0>": "Please choose another market from the <0>market list</0>",
|
||||
"Please choose another market from the <0>market list<0>": "Please choose another market from the <0>market list<0>",
|
||||
"Please connect Vega wallet": "Please connect Vega wallet",
|
||||
"Portfolio": "Portfolio",
|
||||
"Positions": "Positions",
|
||||
@@ -202,9 +193,6 @@
|
||||
"Read the terms": "Read the terms",
|
||||
"Ready to trade": "Ready to trade",
|
||||
"Ready to trade with real funds? <0>Switch to Mainnet</0>": "Ready to trade with real funds? <0>Switch to Mainnet</0>",
|
||||
"Redeem rewards": "Redeem rewards",
|
||||
"referralApplyPreviewMessage": "You are joining the group shown, but will not have access to benefits until you have completed at least {{count}} epoch.",
|
||||
"referralApplyPreviewMessage_plural": "You are joining the group shown, but will not have access to benefits until you have completed at least {{count}} epochs.",
|
||||
"Referral benefits": "Referral benefits",
|
||||
"Referral discount": "Referral discount",
|
||||
"referral-statistics-commission": "Commission earned in <0>qUSD</0> (last {{count}} epochs)",
|
||||
@@ -217,9 +205,6 @@
|
||||
"Required epochs": "Required epochs",
|
||||
"Required for next tier": "Required for next tier",
|
||||
"Resources": "Resources",
|
||||
"Rewards": "Rewards",
|
||||
"Rewards history": "Rewards history",
|
||||
"Rewards multipliers": "Rewards multipliers",
|
||||
"SCCR": "SCCR",
|
||||
"Search": "Search",
|
||||
"See all markets": "See all markets",
|
||||
@@ -244,12 +229,10 @@
|
||||
"Status": "Status",
|
||||
"Stop": "Stop",
|
||||
"Stop orders": "Stop orders",
|
||||
"Streak reward multiplier": "Streak reward multiplier",
|
||||
"Successor of a market": "Successor of a market",
|
||||
"Successors to this market have been proposed": "Successors to this market have been proposed",
|
||||
"Supplied stake": "Supplied stake",
|
||||
"Suspended due to price or liquidity monitoring trigger": "Suspended due to price or liquidity monitoring trigger",
|
||||
"to": "to",
|
||||
"Target stake": "Target stake",
|
||||
"The amount of fees paid to liquidity providers across the whole market during the last epoch {{epoch}}.": "The amount of fees paid to liquidity providers across the whole market during the last epoch {{epoch}}.",
|
||||
"The commission is taken from the infrastructure fee, maker fee, and liquidity provider fee, not from the referee": "The commission is taken from the infrastructure fee, maker fee, and liquidity provider fee, not from the referee",
|
||||
@@ -271,7 +254,6 @@
|
||||
"Toast location": "Toast location",
|
||||
"Total commission (last {{count}}} epochs)": "Total commission (last {{count}}} epochs)",
|
||||
"Total discount": "Total discount",
|
||||
"Total distributed": "Total distributed",
|
||||
"Total fee after discount": "Total fee after discount",
|
||||
"Total fee before discount": "Total fee before discount",
|
||||
"Trader": "Trader",
|
||||
@@ -285,10 +267,6 @@
|
||||
"Transfer": "Transfer",
|
||||
"Unknown": "Unknown",
|
||||
"Unknown settlement date": "Unknown settlement date",
|
||||
"Vega Reward pot": "Vega Reward pot",
|
||||
"Vesting": "Vesting",
|
||||
"Vesting {{assetSymbol}}": "Vesting {{assetSymbol}}",
|
||||
"Vesting multiplier": "Vesting multiplier",
|
||||
"View as party": "View as party",
|
||||
"View liquidity provision table": "View liquidity provision table",
|
||||
"View on Explorer": "View on Explorer",
|
||||
@@ -306,7 +284,6 @@
|
||||
"We're sorry but we don't have an active referral programme currently running. You can propose a new programme <0>here</0>.": "We're sorry but we don't have an active referral programme currently running. You can propose a new programme <0>here</0>.",
|
||||
"Welcome to Vega trading!": "Welcome to Vega trading!",
|
||||
"Withdraw": "Withdraw",
|
||||
"You are joining the group shown, but will not have access to benefits until you have completed at least {{count}} epochs.": "You are joining the group shown, but will not have access to benefits until you have completed at least {{count}} epochs.",
|
||||
"You can opt out any time via settings": "You can opt out any time via settings",
|
||||
"You may encounter bugs, loss of functionality or loss of assets.": "You may encounter bugs, loss of functionality or loss of assets.",
|
||||
"You must be connected to the Vega wallet.": "You must be connected to the Vega wallet.",
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
{
|
||||
"About the Vega wallet": "About the Vega wallet",
|
||||
"Supported browsers": "Supported browsers",
|
||||
"Connect Vega wallet": "Connect Vega wallet",
|
||||
"Get a Vega wallet": "Get a Vega wallet",
|
||||
"Connect securely, deposit funds and approve or reject transactions with the Vega wallet": "Connect securely, deposit funds and approve or reject transactions with the Vega wallet",
|
||||
"Connect": "Connect",
|
||||
"Vega Wallet <0>full featured<0>": "Vega Wallet <0>full featured<0>",
|
||||
"your browser": "your browser",
|
||||
"Connect with Vega Wallet extension for {{browserName}} to access all features including key management and detailed transaction views from your browser.": "Connect with Vega Wallet extension for {{browserName}} to access all features including key management and detailed transaction views from your browser.",
|
||||
"Install Vega Wallet extension for {{browserName}} to access all features including key management and detailed transaction views from your browser.": "Install Vega Wallet extension for {{browserName}} to access all features including key management and detailed transaction views from your browser.",
|
||||
"Metamask Snap <0>quick start</0>": "Metamask Snap <0>quick start</0>",
|
||||
"Connect directly via Metamask with the Vega Snap for single key support without advanced features.": "Connect directly via Metamask with the Vega Snap for single key support without advanced features.",
|
||||
"Connect via Vega MetaMask Snap": "Connect via Vega MetaMask Snap",
|
||||
"Install Metamask with the Vega Snap for single key support without advanced features.": "Install Metamask with the Vega Snap for single key support without advanced features.",
|
||||
"Install Vega MetaMask Snap": "Install Vega MetaMask Snap",
|
||||
"No MetaMask version that supports snaps detected. Learn more about <0>MetaMask Snaps</0>": "No MetaMask version that supports snaps detected. Learn more about <0>MetaMask Snaps</0>",
|
||||
"Advanced / Other options...": "Advanced / Other options...",
|
||||
"View as party": "View as party",
|
||||
"Get the Vega Wallet": "Get the Vega Wallet",
|
||||
"Custom wallet location": "Custom wallet location",
|
||||
"Go back": "Go back",
|
||||
"Connect the App/CLI": "Connect the App/CLI",
|
||||
"Use the Desktop App/CLI": "Use the Desktop App/CLI",
|
||||
"Enter a custom wallet location": "Enter a custom wallet location",
|
||||
"<0>No running Desktop App/CLI detected. Open your app now to connect or enter a</0> <1>custom wallet location</1>": "<0>No running Desktop App/CLI detected. Open your app now to connect or enter a</0> <1>custom wallet location</1>",
|
||||
"Verifying chain": "Verifying chain",
|
||||
"Successfully connected": "Successfully connected",
|
||||
"Connecting...": "Connecting...",
|
||||
"Approve the connection from your Vega wallet app. If you have multiple wallets you'll need to choose which to connect with.": "Approve the connection from your Vega wallet app. If you have multiple wallets you'll need to choose which to connect with.",
|
||||
"Understand the risk": "Understand the risk",
|
||||
"Cancel": "Cancel",
|
||||
"I agree": "I agree",
|
||||
"Something went wrong": "Something went wrong",
|
||||
"An unknown error occurred": "An unknown error occurred",
|
||||
"Try again": "Try again",
|
||||
"User rejected": "User rejected",
|
||||
"The user rejected the wallet connection": "The user rejected the wallet connection",
|
||||
"Wrong network": "Wrong network",
|
||||
"No wallet detected": "No wallet detected",
|
||||
"Vega browser extension not installed": "Vega browser extension not installed",
|
||||
"Snap failed": "Snap failed",
|
||||
"Could not connect to Vega MetaMask Snap": "Could not connect to Vega MetaMask Snap",
|
||||
"No wallet application running at {{connectorUrl}}": "No wallet application running at {{connectorUrl}}",
|
||||
"No Vega Wallet application running": "No Vega Wallet application running",
|
||||
"Read the docs to troubleshoot": "Read the docs to troubleshoot",
|
||||
"Connection in progress": "Connection in progress",
|
||||
"Approve the connection from your Vega wallet app.": "Approve the connection from your Vega wallet app.",
|
||||
"To complete your wallet connection, set your wallet network in your app to \"{{appChainId}}\".": "To complete your wallet connection, set your wallet network in your app to \"{{appChainId}}\".",
|
||||
"SELECT A VEGA KEY": "SELECT A VEGA KEY",
|
||||
"Select": "Select",
|
||||
"Copy": "Copy",
|
||||
"Disconnect all keys": "Disconnect all keys",
|
||||
"Pubkey must be 64 characters in length": "Pubkey must be 64 characters in length",
|
||||
"Pubkey must be be valid hex": "Pubkey must be be valid hex",
|
||||
"VIEW AS VEGA USER": "VIEW AS VEGA USER",
|
||||
"Browse from the perspective of another Vega user in read-only mode.": "Browse from the perspective of another Vega user in read-only mode.",
|
||||
"Required": "Required",
|
||||
"Browse network": "Browse network",
|
||||
"Checking wallet version": "Checking wallet version",
|
||||
"Checking your wallet is compatible with this app": "Checking your wallet is compatible with this app",
|
||||
"Wrong Network": "Wrong Network"
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
{
|
||||
"All {{symbol}} withdrawals are subject to a {{delay}} delay.": "All {{symbol}} withdrawals are subject to a {{delay}} delay.",
|
||||
"Amount": "Amount",
|
||||
"Asset": "Asset",
|
||||
"Available to withdraw in {{availableTimestamp}}": "Available to withdraw in {{availableTimestamp}}",
|
||||
"Balance available": "Balance available",
|
||||
"Complete the withdrawal to release your funds": "Complete the withdrawal to release your funds",
|
||||
"Complete these {{count}} withdrawals to release your funds": "Complete these {{count}} withdrawals to release your funds",
|
||||
"Complete withdrawal": "Complete withdrawal",
|
||||
"Completed": "Completed",
|
||||
"Connect Ethereum wallet to complete": "Connect Ethereum wallet to complete",
|
||||
"Connect": "Connect",
|
||||
"Created": "Created",
|
||||
"Delay time": "Delay time",
|
||||
"Delayed (ready in {{readyIn}})": "Delayed (ready in {{readyIn}})",
|
||||
"Delayed withdrawal threshold": "Delayed withdrawal threshold",
|
||||
"Disconnect": "Disconnect",
|
||||
"Failed": "Failed",
|
||||
"Insufficient amount in account": "Insufficient amount in account",
|
||||
"Invalid asset source: {{source}}": "Invalid asset source: {{source}}",
|
||||
"No withdrawals": "No withdrawals",
|
||||
"None": "None",
|
||||
"Pending": "Pending",
|
||||
"Please select an asset": "Please select an asset",
|
||||
"Read more": "Read more",
|
||||
"Ready to complete": "Ready to complete",
|
||||
"Recipient": "Recipient",
|
||||
"Rejected": "Rejected",
|
||||
"Release funds": "Release funds",
|
||||
"Status": "Status",
|
||||
"Step 1 - Release funds from Vega": "Step 1 - Release funds from Vega",
|
||||
"Step 2 - Transfer funds to your Ethereum wallet": "Step 2 - Transfer funds to your Ethereum wallet",
|
||||
"There are two steps required to make a withdrawal": "There are two steps required to make a withdrawal",
|
||||
"This app only works on {{chainName}}. Please change chain.": "This app only works on {{chainName}}. Please change chain.",
|
||||
"To (Ethereum address)": "To (Ethereum address)",
|
||||
"Transaction": "Transaction",
|
||||
"Use maximum": "Use maximum",
|
||||
"Verifying withdrawal approval": "Verifying withdrawal approval",
|
||||
"View withdrawal details": "View withdrawal details",
|
||||
"View withdrawals": "View withdrawals",
|
||||
"Withdraw {{amount}} {{symbol}}": "Withdraw {{amount}} {{symbol}}",
|
||||
"Withdraw funds": "Withdraw funds",
|
||||
"Withdraw": "Withdraw",
|
||||
"Withdrawal ready": "Withdrawal ready",
|
||||
"Withdrawals of {{threshold}} {{symbol}} or more will be delayed for {{delay}}.": "Withdrawals of {{threshold}} {{symbol}} or more will be delayed for {{delay}}.",
|
||||
"Withdrawals ready": "Withdrawals ready",
|
||||
"You have no assets to withdraw": "You have no assets to withdraw",
|
||||
"Your funds have been unlocked for withdrawal - <0>View in block explorer<0>": "Your funds have been unlocked for withdrawal - <0>View in block explorer<0>"
|
||||
}
|
||||
@@ -1,60 +1,24 @@
|
||||
import LiquidityTable from './liquidity-table';
|
||||
import { act, render, screen, within } from '@testing-library/react';
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import * as Schema from '@vegaprotocol/types';
|
||||
import type { LiquidityProvisionData } from './liquidity-data-provider';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
const partyId1 = 'party1';
|
||||
const partyId2 = 'party2';
|
||||
|
||||
const singleRow: LiquidityProvisionData = {
|
||||
id: 'lp-single',
|
||||
commitmentMinTimeFraction: '100',
|
||||
performanceHysteresisEpochs: 4,
|
||||
priceRange: '1',
|
||||
slaCompetitionFactor: '1',
|
||||
partyId: partyId1,
|
||||
party: {
|
||||
id: partyId1,
|
||||
},
|
||||
const singleRow = {
|
||||
party: 'a3f762f0a6e998e1d0c6e73017a13ec8a22386c30f7f64a1bdca47330bc592dd',
|
||||
createdAt: '2022-08-19T17:18:36.257028Z',
|
||||
updatedAt: '2022-08-19T17:18:36.257028Z',
|
||||
commitmentAmount: '100',
|
||||
commitmentAmount: '56298653179',
|
||||
fee: '0.001',
|
||||
status: Schema.LiquidityProvisionStatus.STATUS_ACTIVE,
|
||||
feeShare: {
|
||||
equityLikeShare: '0.5',
|
||||
averageEntryValuation: '0.5',
|
||||
virtualStake: '0.5',
|
||||
averageScore: '0.5',
|
||||
},
|
||||
};
|
||||
|
||||
const multiRow: LiquidityProvisionData = {
|
||||
id: 'lp-multi',
|
||||
commitmentMinTimeFraction: '100',
|
||||
performanceHysteresisEpochs: 4,
|
||||
priceRange: '1',
|
||||
slaCompetitionFactor: '1',
|
||||
partyId: partyId2,
|
||||
party: {
|
||||
id: partyId2,
|
||||
},
|
||||
createdAt: '2022-08-19T17:18:37.257028Z',
|
||||
updatedAt: '2022-08-19T17:18:37.257028Z',
|
||||
commitmentAmount: '200',
|
||||
fee: '0.002',
|
||||
status: Schema.LiquidityProvisionStatus.STATUS_ACTIVE,
|
||||
feeShare: {
|
||||
equityLikeShare: '0.5',
|
||||
averageEntryValuation: '0.5',
|
||||
virtualStake: '0.5',
|
||||
averageScore: '0.5',
|
||||
},
|
||||
};
|
||||
supplied: '67895',
|
||||
obligation: '56785',
|
||||
} as unknown as LiquidityProvisionData;
|
||||
|
||||
const singleRowData = [singleRow];
|
||||
const multiRowData = [singleRow, multiRow];
|
||||
|
||||
describe('LiquidityTable', () => {
|
||||
it('should render successfully', async () => {
|
||||
@@ -62,10 +26,6 @@ describe('LiquidityTable', () => {
|
||||
const { baseElement } = render(
|
||||
<LiquidityTable rowData={[]} stakeToCcyVolume={'1'} />
|
||||
);
|
||||
// 5002-LIQP-002
|
||||
// 5002-LIQP-004
|
||||
// 5002-LIQP-005
|
||||
// 5002-LIQP-011
|
||||
expect(baseElement).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -105,30 +65,7 @@ describe('LiquidityTable', () => {
|
||||
'Created',
|
||||
'Updated',
|
||||
];
|
||||
// 5002-LIQP-001
|
||||
expect(headers).toHaveLength(expectedHeaders.length);
|
||||
expect(headerTexts).toEqual(expectedHeaders);
|
||||
});
|
||||
|
||||
it('should be able to sort', async () => {
|
||||
await act(async () => {
|
||||
render(
|
||||
<LiquidityTable rowData={multiRowData} stakeToCcyVolume={'0.3'} />
|
||||
);
|
||||
});
|
||||
const headers = await screen.findAllByRole('columnheader');
|
||||
|
||||
const commitmentHeader = headers.find(
|
||||
(h) => h.getAttribute('col-id') === 'commitmentAmount'
|
||||
);
|
||||
|
||||
if (!commitmentHeader) {
|
||||
throw new Error('No commitment header found');
|
||||
}
|
||||
|
||||
// 5002-LIQP-003
|
||||
expect(commitmentHeader).toHaveAttribute('aria-sort', 'none');
|
||||
await userEvent.click(within(commitmentHeader).getByText(/commitment/i));
|
||||
expect(commitmentHeader).toHaveAttribute('aria-sort', 'ascending');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { DepthChart } from 'pennant';
|
||||
import throttle from 'lodash/throttle';
|
||||
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
|
||||
import { addDecimal, getNumberFormat } from '@vegaprotocol/utils';
|
||||
import { addDecimal, addDecimalsFormatNumber } from '@vegaprotocol/utils';
|
||||
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
|
||||
import { useDataProvider } from '@vegaprotocol/data-provider';
|
||||
import { marketDepthProvider } from './market-depth-provider';
|
||||
@@ -216,13 +216,13 @@ export const DepthChartContainer = ({ marketId }: DepthChartManagerProps) => {
|
||||
|
||||
const volumeFormat = useCallback(
|
||||
(volume: number) =>
|
||||
getNumberFormat(market?.positionDecimalPlaces || 0).format(volume),
|
||||
addDecimalsFormatNumber(volume, market?.positionDecimalPlaces || 0),
|
||||
[market?.positionDecimalPlaces]
|
||||
);
|
||||
|
||||
const priceFormat = useCallback(
|
||||
(price: number) =>
|
||||
getNumberFormat(market?.decimalPlaces || 0).format(price),
|
||||
addDecimalsFormatNumber(price, market?.decimalPlaces || 0),
|
||||
[market?.decimalPlaces]
|
||||
);
|
||||
|
||||
|
||||
@@ -102,12 +102,7 @@ export const OrderbookControls = ({
|
||||
};
|
||||
|
||||
export const formatResolution = (r: number, decimalPlaces: number) => {
|
||||
let num = addDecimalsFormatNumber(r, decimalPlaces);
|
||||
|
||||
// Remove trailing zeroes
|
||||
num = num.replace(/\.?0+$/, '');
|
||||
|
||||
return num;
|
||||
return addDecimalsFormatNumber(r, decimalPlaces);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { memo } from 'react';
|
||||
import { addDecimal, addDecimalsFixedFormatNumber } from '@vegaprotocol/utils';
|
||||
import { addDecimal, addDecimalsFormatNumber } from '@vegaprotocol/utils';
|
||||
import { NumericCell } from '@vegaprotocol/datagrid';
|
||||
import { VolumeType } from './orderbook-data';
|
||||
import classNames from 'classnames';
|
||||
@@ -55,7 +55,7 @@ export const OrderbookRow = memo(
|
||||
<NumericCell
|
||||
testId={`price-${price}`}
|
||||
value={BigInt(price)}
|
||||
valueFormatted={addDecimalsFixedFormatNumber(
|
||||
valueFormatted={addDecimalsFormatNumber(
|
||||
price,
|
||||
decimalPlaces,
|
||||
priceFormatDecimalPlaces
|
||||
@@ -76,7 +76,7 @@ export const OrderbookRow = memo(
|
||||
<NumericCell
|
||||
testId={`${txtId}-vol-${price}`}
|
||||
value={volume}
|
||||
valueFormatted={addDecimalsFixedFormatNumber(
|
||||
valueFormatted={addDecimalsFormatNumber(
|
||||
volume,
|
||||
positionDecimalPlaces ?? 0
|
||||
)}
|
||||
@@ -94,7 +94,7 @@ export const OrderbookRow = memo(
|
||||
<NumericCell
|
||||
testId={`cumulative-vol-${price}`}
|
||||
value={cumulativeVolume}
|
||||
valueFormatted={addDecimalsFixedFormatNumber(
|
||||
valueFormatted={addDecimalsFormatNumber(
|
||||
cumulativeVolume,
|
||||
positionDecimalPlaces
|
||||
)}
|
||||
|
||||
@@ -43,7 +43,7 @@ describe('Orderbook', () => {
|
||||
);
|
||||
expect(
|
||||
screen.getByTestId(`last-traded-${params.lastTradedPrice}`)
|
||||
).toHaveTextContent('122.90');
|
||||
).toHaveTextContent('122.9');
|
||||
});
|
||||
|
||||
it('should format correctly the numbers on resolution change', async () => {
|
||||
|
||||
@@ -172,8 +172,9 @@ export const Orderbook = ({
|
||||
|
||||
// we'll want to only display a relevant number of dps based on the
|
||||
// current resolution selection
|
||||
const priceFormatDecimalPlaces = Math.ceil(
|
||||
decimalPlaces - Math.log10(resolution)
|
||||
const priceFormatDecimalPlaces = Math.max(
|
||||
0,
|
||||
Math.ceil(decimalPlaces - Math.log10(resolution))
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
+2
-3
@@ -3,12 +3,12 @@ import * as Types from '@vegaprotocol/types';
|
||||
import { gql } from '@apollo/client';
|
||||
import * as Apollo from '@apollo/client';
|
||||
const defaultOptions = {} as const;
|
||||
export type MarketsDataFieldsFragment = { __typename?: 'MarketData', bestBidPrice: string, bestOfferPrice: string, markPrice: string, trigger: Types.AuctionTrigger, staticMidPrice: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, indicativeVolume: string, indicativePrice: string, bestStaticBidPrice: string, bestStaticOfferPrice: string, targetStake?: string | null, suppliedStake?: string | null, auctionStart?: string | null, auctionEnd?: string | null, openInterest: string, market: { __typename?: 'Market', id: string } };
|
||||
export type MarketsDataFieldsFragment = { __typename?: 'MarketData', bestBidPrice: string, bestOfferPrice: string, markPrice: string, trigger: Types.AuctionTrigger, staticMidPrice: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, indicativeVolume: string, indicativePrice: string, bestStaticBidPrice: string, bestStaticOfferPrice: string, targetStake?: string | null, suppliedStake?: string | null, auctionStart?: string | null, auctionEnd?: string | null, market: { __typename?: 'Market', id: string } };
|
||||
|
||||
export type MarketsDataQueryVariables = Types.Exact<{ [key: string]: never; }>;
|
||||
|
||||
|
||||
export type MarketsDataQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', data?: { __typename?: 'MarketData', bestBidPrice: string, bestOfferPrice: string, markPrice: string, trigger: Types.AuctionTrigger, staticMidPrice: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, indicativeVolume: string, indicativePrice: string, bestStaticBidPrice: string, bestStaticOfferPrice: string, targetStake?: string | null, suppliedStake?: string | null, auctionStart?: string | null, auctionEnd?: string | null, openInterest: string, market: { __typename?: 'Market', id: string } } | null } }> } | null };
|
||||
export type MarketsDataQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', data?: { __typename?: 'MarketData', bestBidPrice: string, bestOfferPrice: string, markPrice: string, trigger: Types.AuctionTrigger, staticMidPrice: string, marketState: Types.MarketState, marketTradingMode: Types.MarketTradingMode, indicativeVolume: string, indicativePrice: string, bestStaticBidPrice: string, bestStaticOfferPrice: string, targetStake?: string | null, suppliedStake?: string | null, auctionStart?: string | null, auctionEnd?: string | null, market: { __typename?: 'Market', id: string } } | null } }> } | null };
|
||||
|
||||
export const MarketsDataFieldsFragmentDoc = gql`
|
||||
fragment MarketsDataFields on MarketData {
|
||||
@@ -30,7 +30,6 @@ export const MarketsDataFieldsFragmentDoc = gql`
|
||||
suppliedStake
|
||||
auctionStart
|
||||
auctionEnd
|
||||
openInterest
|
||||
}
|
||||
`;
|
||||
export const MarketsDataDocument = gql`
|
||||
|
||||
@@ -723,7 +723,7 @@ export const PriceMonitoringBoundsInfoPanel = ({
|
||||
})}
|
||||
</p>
|
||||
<p className="col-span-1 text-right">
|
||||
{t('Within {{horizonSecs}} seconds', {
|
||||
{t('Within %s seconds', {
|
||||
horizonSecs: formatNumber(trigger.horizonSecs),
|
||||
})}
|
||||
</p>
|
||||
|
||||
@@ -189,7 +189,7 @@ export const OracleFullProfile = ({
|
||||
'verifyProofs',
|
||||
'Verify {{count}} proofs of ownership',
|
||||
{
|
||||
count: signedMessageProofs.length,
|
||||
proofs: signedMessageProofs,
|
||||
}
|
||||
)}{' '}
|
||||
<VegaIcon name={VegaIconNames.OPEN_EXTERNAL} size={13} />
|
||||
|
||||
@@ -17,7 +17,6 @@ fragment MarketsDataFields on MarketData {
|
||||
suppliedStake
|
||||
auctionStart
|
||||
auctionEnd
|
||||
openInterest
|
||||
}
|
||||
|
||||
query MarketsData {
|
||||
|
||||
@@ -40,7 +40,6 @@ export const createMarketsDataFragment = (
|
||||
bestStaticBidPrice: '0',
|
||||
bestStaticOfferPrice: '0',
|
||||
indicativeVolume: '0',
|
||||
openInterest: '0',
|
||||
bestBidPrice: '0',
|
||||
bestOfferPrice: '0',
|
||||
markPrice: '4612690058',
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useT = () => useTranslation('markets').t;
|
||||
export const useT = () => useTranslation('funding-payments').t;
|
||||
|
||||
@@ -80,7 +80,7 @@ describe('OrderListTable', () => {
|
||||
const expectedValues: string[] = [
|
||||
marketOrder.market?.tradableInstrument.instrument.code || '',
|
||||
'0.05',
|
||||
'0.10',
|
||||
'0.1',
|
||||
Schema.OrderTypeMapping[marketOrder.type as Schema.OrderType] || '',
|
||||
Schema.OrderStatusMapping[marketOrder.status],
|
||||
'-',
|
||||
@@ -102,7 +102,7 @@ describe('OrderListTable', () => {
|
||||
const expectedValues: string[] = [
|
||||
limitOrder.market?.tradableInstrument.instrument.code || '',
|
||||
'0.05',
|
||||
'0.10',
|
||||
'0.1',
|
||||
Schema.OrderTypeMapping[limitOrder.type || Schema.OrderType.TYPE_LIMIT],
|
||||
Schema.OrderStatusMapping[limitOrder.status],
|
||||
'-',
|
||||
@@ -135,8 +135,8 @@ describe('OrderListTable', () => {
|
||||
const cells = screen.getAllByRole('gridcell');
|
||||
const expectedValues: string[] = [
|
||||
icebergOrder.market?.tradableInstrument.instrument.code || '',
|
||||
'0.00',
|
||||
'+1.00',
|
||||
'0',
|
||||
'+1',
|
||||
Schema.OrderTypeMapping[
|
||||
icebergOrder.type || Schema.OrderType.TYPE_LIMIT
|
||||
] + ' (Iceberg)',
|
||||
@@ -277,7 +277,7 @@ describe('OrderListTable', () => {
|
||||
|
||||
const amendCell = getAmendCell();
|
||||
const typeCell = screen.getAllByRole('gridcell')[3];
|
||||
expect(typeCell).toHaveTextContent('Mid - 10.0 Peg limit');
|
||||
expect(typeCell).toHaveTextContent('Mid - 10 Peg limit');
|
||||
expect(amendCell.queryByTestId('edit')).toBeInTheDocument();
|
||||
expect(amendCell.queryByTestId('cancel')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -162,17 +162,15 @@ describe('OrderViewDialog', () => {
|
||||
expect(screen.getByTestId('order-type-label')).toHaveTextContent('Type');
|
||||
expect(screen.getByTestId('order-type-value')).toHaveTextContent('Limit');
|
||||
expect(screen.getByTestId('order-price-label')).toHaveTextContent('Price');
|
||||
expect(screen.getByTestId('order-price-value')).toHaveTextContent('150.00');
|
||||
expect(screen.getByTestId('order-price-value')).toHaveTextContent('150');
|
||||
expect(screen.getByTestId('order-size-label')).toHaveTextContent('Size');
|
||||
expect(screen.getByTestId('order-size-value')).toHaveTextContent('+10.00');
|
||||
expect(screen.getByTestId('order-size-value')).toHaveTextContent('+10');
|
||||
expect(screen.getByTestId('order-remaining-label')).toHaveTextContent(
|
||||
'Remaining'
|
||||
);
|
||||
expect(screen.getByTestId('order-remaining-value')).toHaveTextContent(
|
||||
'+5.00'
|
||||
);
|
||||
expect(screen.getByTestId('order-remaining-value')).toHaveTextContent('+5');
|
||||
expect(
|
||||
screen.getByTestId('order-iceberg-order-reserved-remaining-value')
|
||||
).toHaveTextContent('5.00');
|
||||
).toHaveTextContent('5');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -140,8 +140,8 @@ describe('StopOrdersTable', () => {
|
||||
const cells = grid.querySelectorAll('.ag-body [col-id="trigger"]');
|
||||
|
||||
const expectedValues: string[] = [
|
||||
'Mark < 8.0',
|
||||
'Mark > 9.0',
|
||||
'Mark < 8',
|
||||
'Mark > 9',
|
||||
'Mark +10.0%',
|
||||
'Mark -20.0%',
|
||||
];
|
||||
@@ -173,7 +173,7 @@ describe('StopOrdersTable', () => {
|
||||
const grid = screen.getByRole('treegrid');
|
||||
const cells = grid.querySelectorAll('.ag-body [col-id="submission.size"]');
|
||||
|
||||
const expectedValues: string[] = ['+1.00', '-1.10'];
|
||||
const expectedValues: string[] = ['+1', '-1.1'];
|
||||
expectedValues.forEach((expectedValue, i) =>
|
||||
expect(cells[i]).toHaveTextContent(expectedValue)
|
||||
);
|
||||
@@ -219,7 +219,7 @@ describe('StopOrdersTable', () => {
|
||||
const grid = screen.getByRole('treegrid');
|
||||
const cells = grid.querySelectorAll('.ag-body [col-id="submission.price"]');
|
||||
|
||||
const expectedValues: string[] = ['12.0', '-'];
|
||||
const expectedValues: string[] = ['12', '-'];
|
||||
expectedValues.forEach((expectedValue, i) =>
|
||||
expect(cells[i]).toHaveTextContent(expectedValue)
|
||||
);
|
||||
|
||||
@@ -267,7 +267,6 @@ export const preparePositions = (metrics: Position[], showClosed: boolean) => {
|
||||
MarketState.STATE_ACTIVE,
|
||||
MarketState.STATE_PENDING,
|
||||
MarketState.STATE_SUSPENDED,
|
||||
MarketState.STATE_SUSPENDED_VIA_GOVERNANCE,
|
||||
].includes(p.marketState)
|
||||
) {
|
||||
return true;
|
||||
|
||||
@@ -74,7 +74,7 @@ describe('Positions', () => {
|
||||
'+100'
|
||||
);
|
||||
expect(within(cell).getByTestId('stack-cell-secondary')).toHaveTextContent(
|
||||
'1,230.0'
|
||||
'1,230'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -90,7 +90,7 @@ describe('Positions', () => {
|
||||
'-100'
|
||||
);
|
||||
expect(within(cell).getByTestId('stack-cell-secondary')).toHaveTextContent(
|
||||
'1,230.0'
|
||||
'1,230'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -334,7 +334,7 @@ describe('Positions', () => {
|
||||
const tooltip = within(await screen.findByRole('tooltip'));
|
||||
expect(tooltip.getByText('Realised PNL: 1.23')).toBeInTheDocument();
|
||||
expect(
|
||||
tooltip.getByText('Lifetime loss socialisation deductions: 5.00')
|
||||
tooltip.getByText('Lifetime loss socialisation deductions: 5')
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
tooltip.getByText(
|
||||
|
||||
@@ -3,8 +3,7 @@ import type { BigNumber } from 'bignumber.js';
|
||||
import { toNumberParts } from '@vegaprotocol/utils';
|
||||
|
||||
export const useNumberParts = (
|
||||
value: BigNumber | null | undefined,
|
||||
decimals: number
|
||||
value: BigNumber | null | undefined
|
||||
): [integers: string, decimalPlaces: string, separator: string | undefined] => {
|
||||
return useMemo(() => toNumberParts(value, decimals), [decimals, value]);
|
||||
return useMemo(() => toNumberParts(value), [value]);
|
||||
};
|
||||
|
||||
@@ -22,13 +22,11 @@ export const CompactNumber = ({
|
||||
decimals = 'infer',
|
||||
compactDisplay = 'short',
|
||||
testId = 'compact-number',
|
||||
compactAbove = DEFAULT_COMPACT_ABOVE,
|
||||
}: {
|
||||
number: BigNumber;
|
||||
decimals?: number | 'infer';
|
||||
compactDisplay?: 'short' | 'long';
|
||||
testId?: string;
|
||||
compactAbove?: number;
|
||||
}) => {
|
||||
if (!number.isFinite()) {
|
||||
return (
|
||||
@@ -46,7 +44,7 @@ export const CompactNumber = ({
|
||||
return <span data-testid={testId}>{INFINITY}</span>;
|
||||
}
|
||||
|
||||
if (number.isLessThan(compactAbove)) {
|
||||
if (number.isLessThan(DEFAULT_COMPACT_ABOVE)) {
|
||||
return (
|
||||
<span data-testid={testId}>{formatNumber(number, decimalPlaces)}</span>
|
||||
);
|
||||
|
||||
@@ -41,8 +41,8 @@ describe('TradesTable', () => {
|
||||
|
||||
const cells = screen.getAllByRole('gridcell');
|
||||
const expectedValues = [
|
||||
'1,111,222.00',
|
||||
'20.00',
|
||||
'1,111,222',
|
||||
'20',
|
||||
getTimeFormat().format(new Date(trade.createdAt)),
|
||||
];
|
||||
cells.forEach((cell, i) => {
|
||||
|
||||
Generated
+1
-13
@@ -4376,19 +4376,7 @@ export type Query = {
|
||||
/** The last block process by the blockchain */
|
||||
lastBlockHeight: Scalars['String'];
|
||||
/**
|
||||
* Get a list of ledger entries within the given date range. The date range is restricted to a maximum of 5 days.
|
||||
* This query requests and sums the number of ledger entries from a given subset of accounts, specified via the 'filter' argument.
|
||||
* It returns a time series - implemented as a list of AggregateLedgerEntry structs - with a row for every time
|
||||
* the summed ledger entries of the set of specified accounts changes.
|
||||
* Each account filter must contain no more than one party ID.
|
||||
* At least one party ID must be specified in the from or to account filter.
|
||||
*
|
||||
* Entries can be filtered by:
|
||||
* - the sending account (market ID, asset ID, account type)
|
||||
* - receiving account (market ID, asset ID, account type)
|
||||
* - sending AND receiving account
|
||||
* - transfer type either in addition to the above filters or as a standalone option
|
||||
*
|
||||
* Get ledger entries by asset, market, party, account type, transfer type within the given date range.
|
||||
* Note: The date range is restricted to any 5 days.
|
||||
* If no start or end date is provided, only ledger entries from the last 5 days will be returned.
|
||||
* If a start and end date are provided, but the end date is more than 5 days after the start date, only data up to 5 days after the start date will be returned.
|
||||
|
||||
@@ -3,7 +3,6 @@ import BigNumber from 'bignumber.js';
|
||||
import {
|
||||
addDecimalsFormatNumber,
|
||||
addDecimalsFormatNumberQuantum,
|
||||
formatNumber,
|
||||
formatNumberPercentage,
|
||||
getUnlimitedThreshold,
|
||||
isNumeric,
|
||||
@@ -12,94 +11,140 @@ import {
|
||||
quantumDecimalPlaces,
|
||||
toDecimal,
|
||||
toNumberParts,
|
||||
formatNumberRounded,
|
||||
} from './number';
|
||||
|
||||
describe('number utils', () => {
|
||||
it.each([
|
||||
{ v: new BigNumber(123000), d: 5, o: '1.23' },
|
||||
{ v: new BigNumber(123000), d: 3, o: '123.00' },
|
||||
{ v: new BigNumber(123000), d: 1, o: '12,300.0' },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01' },
|
||||
{ v: new BigNumber(123001000), d: 2, o: '1,230,010.00' },
|
||||
])(
|
||||
'formats with addDecimalsFormatNumber given number correctly',
|
||||
({ v, d, o }) => {
|
||||
expect(addDecimalsFormatNumber(v.toString(), d)).toStrictEqual(o);
|
||||
}
|
||||
);
|
||||
{ v: new BigNumber(123000), d: 5, f: undefined, o: '1.23' },
|
||||
{ v: new BigNumber(123000), d: 5, f: 3, o: '1.230' },
|
||||
{ v: new BigNumber(123000), d: 3, f: undefined, o: '123' },
|
||||
{ v: new BigNumber(123000), d: 1, f: undefined, o: '12,300' },
|
||||
{ v: new BigNumber(123001), d: 2, f: undefined, o: '1,230.01' },
|
||||
{ v: new BigNumber(123001000), d: 2, f: undefined, o: '1,230,010' },
|
||||
|
||||
it.each([
|
||||
{ v: new BigNumber(123000), d: 5, o: '1.23', q: 0.1 },
|
||||
{ v: new BigNumber(123000), d: 3, o: '123.00', q: 0.1 },
|
||||
{ v: new BigNumber(123000), d: 1, o: '12,300.00', q: 0.1 },
|
||||
{ v: new BigNumber(123001000), d: 2, o: '1,230,010.00', q: 0.1 },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01', q: 100 },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01', q: 0.1 },
|
||||
{ v: new BigNumber(123001), d: 2, o: '1,230.01', q: 1 },
|
||||
// these would lose precision normally and get rounded to 0.9041951688292778
|
||||
{
|
||||
v: BigNumber('123456789123456789'),
|
||||
d: 10,
|
||||
o: '12,345,678.91234568',
|
||||
q: '0.00003846',
|
||||
v: new BigNumber('904195168829277777'),
|
||||
d: 18,
|
||||
f: undefined,
|
||||
o: '0.904195168829277777',
|
||||
},
|
||||
{
|
||||
v: BigNumber('123456789123456789'),
|
||||
d: 10,
|
||||
o: '12,345,678.91234568',
|
||||
q: '1',
|
||||
v: new BigNumber('1234567904195168829277777'),
|
||||
d: 18,
|
||||
f: undefined,
|
||||
o: '1,234,567.904195168829277777',
|
||||
},
|
||||
// USDT / USDC
|
||||
{ v: new BigNumber(12345678), d: 6, o: '12.35', q: 1000000 },
|
||||
])(
|
||||
'formats with addDecimalsFormatNumberQuantum given number correctly',
|
||||
({ v, d, o, q }) => {
|
||||
expect(addDecimalsFormatNumberQuantum(v.toString(), d, q)).toStrictEqual(
|
||||
o
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ v: new BigNumber(123), d: 3, o: '123.00' },
|
||||
{ v: new BigNumber(123.123), d: 3, o: '123.123' },
|
||||
{ v: new BigNumber(123.6666), d: 3, o: '123.667' },
|
||||
{ v: new BigNumber(123.123), d: 6, o: '123.123' },
|
||||
{ v: new BigNumber(123.123), d: 0, o: '123' },
|
||||
{ v: new BigNumber(123), d: undefined, o: '123' },
|
||||
{ v: new BigNumber(30000), d: undefined, o: '30,000' },
|
||||
{ v: new BigNumber(3.000001), d: undefined, o: '3' },
|
||||
])('formats with formatNumber given number correctly', ({ v, d, o }) => {
|
||||
expect(formatNumber(v, d)).toStrictEqual(o);
|
||||
{
|
||||
v: new BigNumber('1234567904195168829277777'),
|
||||
d: 18,
|
||||
f: 2,
|
||||
o: '1,234,567.90',
|
||||
},
|
||||
{
|
||||
v: new BigNumber('1234567906195168829277777'),
|
||||
d: 18,
|
||||
f: 2,
|
||||
o: '1,234,567.91', // should round here
|
||||
},
|
||||
])('addDecimalsFormatNumber formats $v as $o', ({ v, d, f, o }) => {
|
||||
expect(addDecimalsFormatNumber(v.toString(), d, f)).toStrictEqual(o);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ v: new BigNumber(123), d: 3, o: '123.00%' },
|
||||
// USDT / USDC
|
||||
{
|
||||
v: new BigNumber('12111111'),
|
||||
d: 6,
|
||||
q: '1000000',
|
||||
o: '12.11',
|
||||
},
|
||||
{
|
||||
v: new BigNumber('12456111111'),
|
||||
d: 6,
|
||||
q: '1000000',
|
||||
o: '12,456.11',
|
||||
},
|
||||
{
|
||||
v: new BigNumber('12345678'),
|
||||
d: 6,
|
||||
q: '1000000',
|
||||
o: '12.35', // quantum should round
|
||||
},
|
||||
|
||||
// WETH
|
||||
{
|
||||
v: new BigNumber('1'),
|
||||
d: 18,
|
||||
q: '500000000000000',
|
||||
o: '0.000000', // actually 0.000000000000000001 but we are formatting with quantum so that last 1 weth is not relevant
|
||||
},
|
||||
{
|
||||
v: new BigNumber('493000000000000'),
|
||||
d: 18,
|
||||
q: '500000000000000',
|
||||
o: '0.000493', // 1 USD of WETH ~0.000493
|
||||
},
|
||||
{
|
||||
v: new BigNumber('1000000493000000000000'),
|
||||
d: 18,
|
||||
q: '500000000000000',
|
||||
o: '1,000.000493',
|
||||
},
|
||||
{ v: new BigNumber(123001), d: 2, q: 1, o: '1,230.0100' },
|
||||
{ v: new BigNumber(123001), d: 2, q: 100, o: '1,230.01' },
|
||||
{
|
||||
v: BigNumber('123456789123456789'),
|
||||
d: 10,
|
||||
q: '1',
|
||||
o: '12,345,678.912345678900',
|
||||
},
|
||||
|
||||
// FRACTIONAL QUANTUM
|
||||
{ v: new BigNumber(123000), d: 5, q: 0.1, o: '1.23000000' },
|
||||
{ v: new BigNumber(123000), d: 3, q: 0.1, o: '123.000000' },
|
||||
{ v: new BigNumber(123000), d: 1, q: 0.1, o: '12,300.0000' },
|
||||
{ v: new BigNumber(123001000), d: 2, q: 0.1, o: '1,230,010.00000' },
|
||||
{ v: new BigNumber(123001), d: 2, q: 0.1, o: '1,230.01000' },
|
||||
{
|
||||
v: BigNumber('123456789123456789'),
|
||||
d: 10,
|
||||
q: '0.00003846',
|
||||
o: '12,345,678.91234567890000000',
|
||||
},
|
||||
])('addDecimalsFormatNumberQuantum($v, $d, $q) = $o', ({ v, d, q, o }) => {
|
||||
expect(addDecimalsFormatNumberQuantum(v.toString(), d, q)).toStrictEqual(o);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ v: new BigNumber(123), d: 3, o: '123.000%' },
|
||||
{ v: new BigNumber(123.123), d: 3, o: '123.123%' },
|
||||
{ v: new BigNumber(123.123), d: 6, o: '123.123%' },
|
||||
{ v: new BigNumber(123.123), d: 6, o: '123.123000%' },
|
||||
{ v: new BigNumber(123.123), d: 0, o: '123%' },
|
||||
{ v: new BigNumber(123), d: undefined, o: '123%' }, // it default to 2 decimal places
|
||||
{ v: new BigNumber(30000), d: undefined, o: '30,000%' },
|
||||
{ v: new BigNumber(3.000001), d: undefined, o: '3.000001%' },
|
||||
])('formats given number correctly', ({ v, d, o }) => {
|
||||
])('formatNumberRounded($v, $d) -> $o', ({ v, d, o }) => {
|
||||
expect(formatNumberPercentage(v, d)).toStrictEqual(o);
|
||||
});
|
||||
|
||||
describe('toNumberParts', () => {
|
||||
it.each([
|
||||
{ v: null, d: 3, o: ['0', '000', '.'] },
|
||||
{ v: undefined, d: 3, o: ['0', '000', '.'] },
|
||||
{ v: new BigNumber(123), d: 3, o: ['123', '00', '.'] },
|
||||
{ v: new BigNumber(123.123), d: 3, o: ['123', '123', '.'] },
|
||||
{ v: new BigNumber(123.123), d: 6, o: ['123', '123', '.'] },
|
||||
{ v: new BigNumber(123.123), d: 0, o: ['123', '', '.'] },
|
||||
{ v: new BigNumber(123), d: undefined, o: ['123', '00', '.'] },
|
||||
{ v: null, o: ['0', '', '.'] },
|
||||
{ v: undefined, o: ['0', '', '.'] },
|
||||
{ v: new BigNumber(123), o: ['123', '', '.'] },
|
||||
{ v: new BigNumber(123.123), o: ['123', '123', '.'] },
|
||||
{ v: new BigNumber(123.123), o: ['123', '123', '.'] },
|
||||
{ v: new BigNumber(123.123), o: ['123', '123', '.'] },
|
||||
{ v: new BigNumber(123), o: ['123', '', '.'] },
|
||||
{
|
||||
v: new BigNumber(30000),
|
||||
d: undefined,
|
||||
o: ['30,000', '00', '.'],
|
||||
o: ['30,000', '', '.'],
|
||||
},
|
||||
])('returns correct tuple given the different arguments', ({ v, d, o }) => {
|
||||
expect(toNumberParts(v, d)).toStrictEqual(o);
|
||||
])('$v -> $o', ({ v, o }) => {
|
||||
expect(toNumberParts(v)).toStrictEqual(o);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,3 +291,23 @@ describe('getUnlimitedThreshold', () => {
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
describe('formatNumberRounded', () => {
|
||||
it.each([
|
||||
{ n: new BigNumber(123), o: '123' },
|
||||
{ n: new BigNumber(1234), o: '1,234' },
|
||||
{ n: new BigNumber(404000), o: '404,000' },
|
||||
{ n: new BigNumber(500000), o: '500,000' },
|
||||
{ n: new BigNumber(1000000), o: '1m' },
|
||||
{ n: new BigNumber(1500000), o: '1.5m' },
|
||||
{ n: new BigNumber(1500001), o: '1.5m' },
|
||||
{ n: new BigNumber(1510001), o: '1.5m' },
|
||||
{ n: new BigNumber(1000000000), o: '1b' },
|
||||
{ n: new BigNumber(1500000000), o: '1.5b' },
|
||||
{ n: new BigNumber(1000000000000), o: '1t' },
|
||||
{ n: new BigNumber(1500000000000), o: '1.5t' },
|
||||
{ n: new BigNumber(99510000000000), o: '99.5t' },
|
||||
])('$n -> $o', ({ n, o }) => {
|
||||
expect(formatNumberRounded(n)).toEqual(o);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,75 @@
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import isNil from 'lodash/isNil';
|
||||
import memoize from 'lodash/memoize';
|
||||
|
||||
import { getUserLocale } from '../get-user-locale';
|
||||
|
||||
const DEFAULT_DECIMAL_SEPARATOR = '.';
|
||||
const DEFAULT_GROUP_SEPARATOR = ',';
|
||||
|
||||
// get formatting characters for users locale
|
||||
export const getNumberParts = memoize(() => {
|
||||
// 1000.1 will get us a group character (, for thousand groups, . for decimals in en-GB)
|
||||
const parts = new Intl.NumberFormat(getUserLocale()).formatToParts(1000.1);
|
||||
|
||||
const decimalSeparator = parts.find((part) => part.type === 'decimal');
|
||||
const groupSeparator = parts.find((part) => part.type === 'group');
|
||||
|
||||
if (!decimalSeparator) {
|
||||
console.warn('Could not get locales decimalSeparator');
|
||||
}
|
||||
|
||||
if (!groupSeparator) {
|
||||
console.warn('Could not get locales groupSeparator');
|
||||
}
|
||||
|
||||
return {
|
||||
decimalSeparator: decimalSeparator
|
||||
? decimalSeparator.value
|
||||
: DEFAULT_DECIMAL_SEPARATOR,
|
||||
groupSeparator: groupSeparator
|
||||
? groupSeparator.value
|
||||
: DEFAULT_GROUP_SEPARATOR,
|
||||
};
|
||||
});
|
||||
|
||||
const parts = getNumberParts();
|
||||
|
||||
// Format for bignumber formatting
|
||||
const FORMAT = {
|
||||
prefix: '',
|
||||
decimalSeparator: parts.decimalSeparator,
|
||||
groupSeparator: parts.groupSeparator,
|
||||
groupSize: 3,
|
||||
secondaryGroupSize: 0,
|
||||
fractionGroupSeparator: ' ',
|
||||
fractionGroupSize: 0,
|
||||
suffix: '',
|
||||
};
|
||||
|
||||
BigNumber.config({ FORMAT });
|
||||
|
||||
export const isNumeric = (
|
||||
value?: string | number | BigNumber | bigint | null
|
||||
): value is NonNullable<number | string> => /^-?\d*\.?\d+$/.test(String(value));
|
||||
|
||||
export const toNumberParts = (
|
||||
value: BigNumber | null | undefined
|
||||
): [integers: string, decimalPlaces: string, separator: string] => {
|
||||
if (!value) {
|
||||
return ['0', '', '.'];
|
||||
}
|
||||
|
||||
const separator = getNumberParts().decimalSeparator;
|
||||
|
||||
const dps = value.dp() || 0;
|
||||
|
||||
const [integers, decimalsPlaces] = formatNumber(value, dps)
|
||||
.toString()
|
||||
.split(separator);
|
||||
|
||||
return [integers, decimalsPlaces || '', separator];
|
||||
};
|
||||
|
||||
/**
|
||||
* A raw unformatted value greater than this is considered and displayed
|
||||
* as UNLIMITED.
|
||||
@@ -16,9 +82,6 @@ export const UNLIMITED_THRESHOLD = new BigNumber(2).pow(256).times(0.8);
|
||||
export const getUnlimitedThreshold = (decimalPlaces: number) =>
|
||||
UNLIMITED_THRESHOLD.dividedBy(Math.pow(10, decimalPlaces));
|
||||
|
||||
const MIN_FRACTION_DIGITS = 2;
|
||||
const MAX_FRACTION_DIGITS = 20;
|
||||
|
||||
export function toDecimal(numberOfDecimals: number) {
|
||||
return new BigNumber(1)
|
||||
.dividedBy(new BigNumber(10).exponentiatedBy(numberOfDecimals))
|
||||
@@ -53,35 +116,6 @@ export function removeDecimal(
|
||||
return new BigNumber(value || 0).times(times).toFixed(0);
|
||||
}
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
|
||||
export const getNumberFormat = memoize((digits: number) => {
|
||||
if (isNil(digits) || digits < 0) {
|
||||
return new Intl.NumberFormat(getUserLocale());
|
||||
}
|
||||
return new Intl.NumberFormat(getUserLocale(), {
|
||||
minimumFractionDigits: Math.min(Math.max(0, digits), MIN_FRACTION_DIGITS),
|
||||
maximumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
|
||||
});
|
||||
});
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
|
||||
export const getFixedNumberFormat = memoize((digits: number) => {
|
||||
if (isNil(digits) || digits < 0) {
|
||||
return new Intl.NumberFormat(getUserLocale());
|
||||
}
|
||||
return new Intl.NumberFormat(getUserLocale(), {
|
||||
minimumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
|
||||
maximumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
|
||||
});
|
||||
});
|
||||
|
||||
export const getDecimalSeparator = memoize(
|
||||
() =>
|
||||
getNumberFormat(1)
|
||||
.formatToParts(1.1)
|
||||
.find((part) => part.type === 'decimal')?.value
|
||||
);
|
||||
|
||||
/** formatNumber will format the number with fixed decimals
|
||||
* @param rawValue - should be a number that is not outside the safe range fail as in https://mikemcl.github.io/bignumber.js/#toN
|
||||
* @param formatDecimals - number of decimals to use
|
||||
@@ -90,18 +124,7 @@ export const formatNumber = (
|
||||
rawValue: string | number | BigNumber,
|
||||
formatDecimals = 0
|
||||
) => {
|
||||
return getNumberFormat(formatDecimals).format(Number(rawValue));
|
||||
};
|
||||
|
||||
/** formatNumberFixed will format the number with fixed decimals
|
||||
* @param rawValue - should be a number that is not outside the safe range fail as in https://mikemcl.github.io/bignumber.js/#toN
|
||||
* @param formatDecimals - number of decimals to use
|
||||
*/
|
||||
export const formatNumberFixed = (
|
||||
rawValue: string | number | BigNumber,
|
||||
formatDecimals = 0
|
||||
) => {
|
||||
return getFixedNumberFormat(formatDecimals).format(Number(rawValue));
|
||||
return new BigNumber(rawValue).toFormat(formatDecimals);
|
||||
};
|
||||
|
||||
export const quantumDecimalPlaces = (
|
||||
@@ -117,7 +140,11 @@ export const quantumDecimalPlaces = (
|
||||
? decimalPlaces
|
||||
: Math.max(
|
||||
0,
|
||||
Math.log10(100 / Number(addDecimal(rawQuantum, decimalPlaces)))
|
||||
Math.log10(
|
||||
new BigNumber(100)
|
||||
.dividedBy(toBigNum(rawQuantum, decimalPlaces))
|
||||
.toNumber()
|
||||
)
|
||||
);
|
||||
|
||||
return Math.ceil(formatDecimals);
|
||||
@@ -128,61 +155,44 @@ export const addDecimalsFormatNumberQuantum = (
|
||||
decimalPlaces: number,
|
||||
quantum: number | string
|
||||
) => {
|
||||
const val = toBigNum(rawValue, decimalPlaces);
|
||||
let formatDps = val.dp() ?? decimalPlaces;
|
||||
|
||||
if (isNaN(Number(quantum))) {
|
||||
return addDecimalsFormatNumber(rawValue, decimalPlaces);
|
||||
return val.toFormat(formatDps);
|
||||
}
|
||||
const quantumValue = addDecimal(quantum, decimalPlaces);
|
||||
const numberDP = Math.max(0, Math.log10(100 / Number(quantumValue)));
|
||||
return addDecimalsFormatNumber(rawValue, decimalPlaces, Math.ceil(numberDP));
|
||||
|
||||
formatDps = quantumDecimalPlaces(quantum, decimalPlaces);
|
||||
|
||||
return val.toFormat(formatDps);
|
||||
};
|
||||
|
||||
export const addDecimalsFormatNumber = (
|
||||
rawValue: string | number,
|
||||
decimalPlaces: number,
|
||||
formatDecimals: number = decimalPlaces
|
||||
formatDecimals?: number
|
||||
) => {
|
||||
const x = addDecimal(rawValue, decimalPlaces);
|
||||
|
||||
return formatNumber(x, formatDecimals);
|
||||
const val = toBigNum(rawValue, decimalPlaces);
|
||||
const naturalDp = val.dp() ?? 0;
|
||||
const formatDps = Math.max(
|
||||
0,
|
||||
formatDecimals === undefined ? naturalDp : formatDecimals
|
||||
);
|
||||
return val.toFormat(formatDps || 0);
|
||||
};
|
||||
|
||||
export const addDecimalsFixedFormatNumber = (
|
||||
rawValue: string | number,
|
||||
decimalPlaces: number,
|
||||
formatDecimals: number = decimalPlaces
|
||||
export const formatNumberPercentage = (
|
||||
value: BigNumber,
|
||||
formatDecimals?: number
|
||||
) => {
|
||||
const x = addDecimal(rawValue, decimalPlaces);
|
||||
|
||||
return formatNumberFixed(x, formatDecimals);
|
||||
};
|
||||
|
||||
export const formatNumberPercentage = (value: BigNumber, decimals?: number) => {
|
||||
const decimalPlaces =
|
||||
typeof decimals === 'undefined' ? value.dp() || 0 : decimals;
|
||||
return `${formatNumber(value, decimalPlaces)}%`;
|
||||
typeof formatDecimals === 'undefined' ? value.dp() || 0 : formatDecimals;
|
||||
return `${value.toFormat(decimalPlaces)}%`;
|
||||
};
|
||||
|
||||
export const toNumberParts = (
|
||||
value: BigNumber | null | undefined,
|
||||
decimals = 18
|
||||
): [integers: string, decimalPlaces: string, separator: string] => {
|
||||
if (!value) {
|
||||
return ['0', '0'.repeat(decimals), '.'];
|
||||
}
|
||||
const separator = getDecimalSeparator() || '.';
|
||||
const [integers, decimalsPlaces] = formatNumber(value, decimals)
|
||||
.toString()
|
||||
.split(separator);
|
||||
return [integers, decimalsPlaces || '', separator];
|
||||
};
|
||||
|
||||
export const isNumeric = (
|
||||
value?: string | number | BigNumber | bigint | null
|
||||
): value is NonNullable<number | string> => /^-?\d*\.?\d+$/.test(String(value));
|
||||
|
||||
/**
|
||||
* Format a number greater than 1 million with m for million, b for billion
|
||||
* and t for trillion
|
||||
* Format numbers greater than 1 million with m for million, b for billion
|
||||
* and t for trillion, rounding to the nearest half
|
||||
*/
|
||||
export const formatNumberRounded = (num: BigNumber) => {
|
||||
let value = '';
|
||||
@@ -204,7 +214,7 @@ export const formatNumberRounded = (num: BigNumber) => {
|
||||
// Million
|
||||
value = `${format('1e6')}m`;
|
||||
} else {
|
||||
value = formatNumber(num);
|
||||
value = num.toFormat();
|
||||
}
|
||||
|
||||
return value;
|
||||
|
||||
@@ -3,61 +3,59 @@ import { formatRange, formatValue } from './range';
|
||||
describe('formatValue', () => {
|
||||
it.each([
|
||||
{ v: 123000, d: 5, o: '1.23' },
|
||||
{ v: 123000, d: 3, o: '123.00' },
|
||||
{ v: 123000, d: 1, o: '12,300.0' },
|
||||
{ v: 123001000, d: 2, o: '1,230,010.00' },
|
||||
{ v: 123000, d: 3, o: '123' },
|
||||
{ v: 123000, d: 1, o: '12,300' },
|
||||
{ v: 123001000, d: 2, o: '1,230,010' },
|
||||
{ v: 123001, d: 2, o: '1,230.01' },
|
||||
{
|
||||
v: '123456789123456789',
|
||||
d: 10,
|
||||
o: '12,345,678.91234568',
|
||||
o: '12,345,678.9123456789',
|
||||
},
|
||||
])('formats values correctly', ({ v, d, o }) => {
|
||||
])('formatValue($v, $d) -> $o', ({ v, d, o }) => {
|
||||
expect(formatValue(v, d)).toStrictEqual(o);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ v: 123000, d: 5, o: '1.23', q: '0.1' },
|
||||
{ v: 123000, d: 3, o: '123.00', q: '0.1' },
|
||||
{ v: 123000, d: 1, o: '12,300.00', q: '0.1' },
|
||||
{ v: 123001000, d: 2, o: '1,230,010.00', q: '0.1' },
|
||||
{ v: 123000, d: 5, o: '1.2300000', q: '1' },
|
||||
{ v: 123000, d: 3, o: '123.00000', q: '1' },
|
||||
{ v: 123000, d: 1, o: '12,300.000', q: '1' },
|
||||
{ v: 123001000, d: 2, o: '1,230,010.0000', q: '1' },
|
||||
{ v: 123001, d: 2, o: '1,230.01', q: '100' },
|
||||
{ v: 123001, d: 2, o: '1,230.01', q: '0.1' },
|
||||
{ v: 123001, d: 2, o: '1,230.0100', q: '1' },
|
||||
{
|
||||
v: '123456789123456789',
|
||||
d: 10,
|
||||
o: '12,345,678.91234568',
|
||||
o: '12,345,678.91234567890000000',
|
||||
q: '0.00003846',
|
||||
},
|
||||
])(
|
||||
'formats with formatValue with quantum given number correctly',
|
||||
({ v, d, o, q }) => {
|
||||
expect(formatValue(v.toString(), d, q)).toStrictEqual(o);
|
||||
}
|
||||
);
|
||||
])('with quantum formatValue($v, $d, $q) -> $o', ({ v, d, o, q }) => {
|
||||
expect(formatValue(v.toString(), d, q)).toStrictEqual(o);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatRange', () => {
|
||||
it.each([
|
||||
{
|
||||
min: 123000,
|
||||
max: 12300011111,
|
||||
d: 5,
|
||||
o: '1.23 - 123,000.11111',
|
||||
q: '0.1',
|
||||
o: '1.2300000 - 123,000.1111100',
|
||||
q: '1',
|
||||
},
|
||||
{
|
||||
min: 123000,
|
||||
max: 12300011111,
|
||||
d: 3,
|
||||
o: '123.00 - 12,300,011.111',
|
||||
q: '0.1',
|
||||
o: '123.00000 - 12,300,011.11100',
|
||||
q: '1',
|
||||
},
|
||||
{
|
||||
min: 123000,
|
||||
max: 12300011111,
|
||||
d: 1,
|
||||
o: '12,300.00 - 1,230,001,111.10',
|
||||
q: '0.1',
|
||||
o: '12,300.000 - 1,230,001,111.100',
|
||||
q: '1',
|
||||
},
|
||||
{
|
||||
min: 123001000,
|
||||
@@ -66,10 +64,7 @@ describe('formatRange', () => {
|
||||
o: '1,230,010.00 - 123,000,111.11',
|
||||
q: '100',
|
||||
},
|
||||
])(
|
||||
'formats with formatValue with quantum given number correctly',
|
||||
({ min, max, d, o, q }) => {
|
||||
expect(formatRange(min, max, d, q)).toStrictEqual(o);
|
||||
}
|
||||
);
|
||||
])('formatRange($min, $max, $d, $q) -> $o', ({ min, max, d, o, q }) => {
|
||||
expect(formatRange(min, max, d, q)).toStrictEqual(o);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '@vegaprotocol/i18n';
|
||||
import {
|
||||
ExternalLink,
|
||||
VegaIcon,
|
||||
@@ -8,11 +9,10 @@ import type { ReactNode } from 'react';
|
||||
import { MozillaIcon } from './mozilla-icon';
|
||||
import { ChromeIcon } from './chrome-icon';
|
||||
import { useVegaWallet } from '../use-vega-wallet';
|
||||
import { useT } from '../use-t';
|
||||
|
||||
export const ConnectDialogTitle = ({ children }: { children: ReactNode }) => {
|
||||
return (
|
||||
<h1 data-testid="wallet-dialog-title" className="font-alpha mb-6 text-2xl">
|
||||
<h1 data-testid="wallet-dialog-title" className="mb-6 text-2xl font-alpha">
|
||||
{children}
|
||||
</h1>
|
||||
);
|
||||
@@ -23,7 +23,6 @@ export const ConnectDialogContent = ({ children }: { children: ReactNode }) => {
|
||||
};
|
||||
|
||||
export const ConnectDialogFooter = () => {
|
||||
const t = useT();
|
||||
const { links } = useVegaWallet();
|
||||
const wrapperClasses = classNames(
|
||||
'flex justify-center gap-4 mt-4',
|
||||
@@ -57,7 +56,7 @@ export const BrowserIcon = ({
|
||||
const isItMozilla =
|
||||
window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
|
||||
return (
|
||||
<div className="absolute right-1 top-0 flex h-8 items-center">
|
||||
<div className="absolute top-0 flex items-center h-8 right-1">
|
||||
{!isItChrome && !isItMozilla ? (
|
||||
<>
|
||||
<a href={mozillaExtensionUrl} target="_blank" rel="noreferrer">
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from '@vegaprotocol/ui-toolkit';
|
||||
import { useCallback, useState, type ReactNode } from 'react';
|
||||
import { type WalletClientError } from '@vegaprotocol/wallet-client';
|
||||
import { t } from '@vegaprotocol/i18n';
|
||||
import { type Connectors, type VegaConnector } from '../connectors';
|
||||
import { DEFAULT_SNAP_VERSION } from '../connectors';
|
||||
import {
|
||||
@@ -45,8 +46,6 @@ import { useIsWalletServiceRunning } from '../use-is-wallet-service-running';
|
||||
import { SnapStatus, useSnapStatus } from '../use-snap-status';
|
||||
import { useVegaWalletDialogStore } from './vega-wallet-dialog-store';
|
||||
import { useChainId } from './use-chain-id';
|
||||
import { useT } from '../use-t';
|
||||
import { Trans } from 'react-i18next';
|
||||
|
||||
export const CLOSE_DELAY = 1700;
|
||||
|
||||
@@ -226,7 +225,6 @@ const ConnectorList = ({
|
||||
isDesktopWalletRunning: boolean | null;
|
||||
snapStatus: SnapStatus;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const { pubKey, links } = useVegaWallet();
|
||||
const title = isBrowserWalletInstalled()
|
||||
? t('Connect Vega wallet')
|
||||
@@ -250,7 +248,7 @@ const ConnectorList = ({
|
||||
? 'Chrome'
|
||||
: isItMozilla
|
||||
? 'Firefox'
|
||||
: t('your browser');
|
||||
: 'your browser';
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -267,28 +265,34 @@ const ConnectorList = ({
|
||||
text={extendedText}
|
||||
onClick={() => onSelect('injected')}
|
||||
title={
|
||||
<Trans
|
||||
defaults="Vega Wallet <0>full featured<0>"
|
||||
components={[<span className="text-xs">full featured</span>]}
|
||||
/>
|
||||
<>
|
||||
<span>{t('Vega Wallet')}</span>
|
||||
{' '}
|
||||
<span className="text-xs">{t('full featured')}</span>
|
||||
</>
|
||||
}
|
||||
description={t(
|
||||
'Connect with Vega Wallet extension for {{browserName}} to access all features including key management and detailed transaction views from your browser.',
|
||||
{ browserName }
|
||||
`Connect with Vega Wallet extension
|
||||
for %s to access all features including key
|
||||
management and detailed transaction views from your
|
||||
browser.`,
|
||||
[browserName]
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<div>
|
||||
<h1 className="mb-1 text-lg">
|
||||
<Trans
|
||||
defaults="Vega Wallet <0>full featured<0>"
|
||||
components={[<span className="text-xs">full featured</span>]}
|
||||
/>
|
||||
<span>{t('Vega Wallet')}</span>
|
||||
{' '}
|
||||
<span className="text-xs"> {t('full featured')}</span>
|
||||
</h1>
|
||||
<p className="mb-2 text-sm">
|
||||
{t(
|
||||
'Install Vega Wallet extension for {{browserName}} to access all features including key management and detailed transaction views from your browser.',
|
||||
{ browserName }
|
||||
`Install Vega Wallet extension
|
||||
for %s to access all features including key
|
||||
management and detailed transaction views from your
|
||||
browser.`,
|
||||
[browserName]
|
||||
)}
|
||||
</p>
|
||||
<GetWalletButton
|
||||
@@ -303,10 +307,11 @@ const ConnectorList = ({
|
||||
<ConnectionOptionWithDescription
|
||||
type="snap"
|
||||
title={
|
||||
<Trans
|
||||
defaults="Metamask Snap <0>quick start</0>"
|
||||
components={[<span className="text-xs">quick start</span>]}
|
||||
/>
|
||||
<>
|
||||
<span>{t('Metamask Snap')}</span>
|
||||
{' '}
|
||||
<span className="text-xs"> {t('quick start')}</span>
|
||||
</>
|
||||
}
|
||||
description={t(
|
||||
`Connect directly via Metamask with the Vega Snap for single key support without advanced features.`
|
||||
@@ -331,12 +336,11 @@ const ConnectorList = ({
|
||||
type="snap"
|
||||
disabled={snapStatus === SnapStatus.NOT_SUPPORTED}
|
||||
title={
|
||||
<Trans
|
||||
defaults="Metamask Snap <0>quick start</0>"
|
||||
components={[
|
||||
<span className="text-xs">quick start</span>,
|
||||
]}
|
||||
/>
|
||||
<>
|
||||
<span>{t('Metamask Snap')}</span>
|
||||
{' '}
|
||||
<span className="text-xs"> {t('quick start')}</span>
|
||||
</>
|
||||
}
|
||||
description={t(
|
||||
`Install Metamask with the Vega Snap for single key support without advanced features.`
|
||||
@@ -359,14 +363,11 @@ const ConnectorList = ({
|
||||
/>
|
||||
{snapStatus === SnapStatus.NOT_SUPPORTED ? (
|
||||
<p className="text-muted pt-1 text-xs leading-tight">
|
||||
<Trans
|
||||
defaults="No MetaMask version that supports snaps detected. Learn more about <0>MetaMask Snaps</0>"
|
||||
components={[
|
||||
<ExternalLink href="https://metamask.io/snaps/">
|
||||
MetaMask Snaps
|
||||
</ExternalLink>,
|
||||
]}
|
||||
/>
|
||||
{t('No MetaMask version that supports snaps detected.')}{' '}
|
||||
{t('Learn more about')}{' '}
|
||||
<ExternalLink href="https://metamask.io/snaps/">
|
||||
MetaMask Snaps
|
||||
</ExternalLink>
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
@@ -468,7 +469,6 @@ export const GetWalletButton = ({
|
||||
mozillaExtensionUrl?: string;
|
||||
className?: string;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const isItChrome = window.navigator.userAgent.includes('Chrome');
|
||||
const isItMozilla =
|
||||
window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
|
||||
@@ -599,7 +599,6 @@ const CustomUrlInput = ({
|
||||
isDesktopWalletRunning: boolean | null;
|
||||
onSelect: (type: WalletType) => void;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const { pubKey } = useVegaWallet();
|
||||
const [urlInputExpanded, setUrlInputExpanded] = useState(false);
|
||||
return urlInputExpanded ? (
|
||||
@@ -655,22 +654,18 @@ const CustomUrlInput = ({
|
||||
</button>
|
||||
) : (
|
||||
<p className="text-muted leading-tight">
|
||||
<Trans
|
||||
defaults="<0>No running Desktop App/CLI detected. Open your app now to connect or enter a</0> <1>custom wallet location</1>"
|
||||
components={[
|
||||
<span className="text-xs">
|
||||
No running Desktop App/CLI detected. Open your app now to
|
||||
connect or enter a
|
||||
</span>,
|
||||
<button
|
||||
className="text-xs underline"
|
||||
onClick={() => setUrlInputExpanded(true)}
|
||||
disabled={Boolean(pubKey)}
|
||||
>
|
||||
custom wallet location
|
||||
</button>,
|
||||
]}
|
||||
/>
|
||||
<span className="text-xs">
|
||||
{t(
|
||||
'No running Desktop App/CLI detected. Open your app now to connect or enter a'
|
||||
)}
|
||||
</span>{' '}
|
||||
<button
|
||||
className="text-xs underline"
|
||||
onClick={() => setUrlInputExpanded(true)}
|
||||
disabled={Boolean(pubKey)}
|
||||
>
|
||||
{t('custom wallet location')}
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '@vegaprotocol/i18n';
|
||||
import { Status } from '../use-injected-connector';
|
||||
import { ConnectDialogTitle } from './connect-dialog-elements';
|
||||
import type { ReactNode } from 'react';
|
||||
@@ -11,7 +12,6 @@ import {
|
||||
import { setAcknowledged } from '../storage';
|
||||
import { useVegaWallet } from '../use-vega-wallet';
|
||||
import { InjectedConnectorErrors, SnapConnectorErrors } from '../connectors';
|
||||
import { useT } from '../use-t';
|
||||
|
||||
export const InjectedConnectorForm = ({
|
||||
status,
|
||||
@@ -28,7 +28,6 @@ export const InjectedConnectorForm = ({
|
||||
reset: () => void;
|
||||
riskMessage?: React.ReactNode;
|
||||
}) => {
|
||||
const t = useT();
|
||||
const { disconnect } = useVegaWallet();
|
||||
|
||||
if (status === Status.Idle) {
|
||||
@@ -110,7 +109,7 @@ export const InjectedConnectorForm = ({
|
||||
|
||||
const Center = ({ children }: { children: ReactNode }) => {
|
||||
return (
|
||||
<div className="my-6 flex items-center justify-center">{children}</div>
|
||||
<div className="flex items-center justify-center my-6">{children}</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -123,7 +122,6 @@ const Error = ({
|
||||
appChainId: string;
|
||||
onTryAgain: () => void;
|
||||
}) => {
|
||||
const t = useT();
|
||||
let title = t('Something went wrong');
|
||||
let text: ReactNode | undefined = t('An unknown error occurred');
|
||||
const tryAgain: ReactNode | null = (
|
||||
@@ -141,8 +139,8 @@ const Error = ({
|
||||
) {
|
||||
title = t('Wrong network');
|
||||
text = t(
|
||||
'To complete your wallet connection, set your wallet network in your app to "{{appChainId}}".',
|
||||
{ appChainId }
|
||||
'To complete your wallet connection, set your wallet network in your app to "%s".',
|
||||
appChainId
|
||||
);
|
||||
} else if (
|
||||
error.message === InjectedConnectorErrors.VEGA_UNDEFINED.message
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user