Compare commits

..
Author SHA1 Message Date
bwallacee 81f497b4fa chore(trading): moving acs across 2023-11-21 11:05:58 +00:00
83 changed files with 1039 additions and 793 deletions
+2 -2
View File
@@ -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
@@ -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">
+11 -37
View File
@@ -31,16 +31,17 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.visit('/#/portfolio');
cy.get('[data-testid="pathname-/portfolio"]').should('exist');
// 1001-DEPO-001
// 1001-DEPO-002
// 1001-DEPO-003
// 1001-DEPO-005
// 1001-DEPO-006
// 1001-DEPO-007
// 1001-DEPO-008
// 1001-DEPO-009
// 1001-DEPO-010
/* must select the asset that I want to deposit (1001-DEPO-002)
should easily see the assets that I have a non-zero balance for (in the connected eth wallet)
should see the ERC20 token address of the asset
should see the Vega asset symbol
should see the Vega asset name */
// 1001-DEPO-009
// must see feedback on the deposit ETH transaction (1001-DEPO-009)
// 1001-DEPO-010
// must see feedback that the deposit has or has not been credited to the Vega key (1001-DEPO-010)
cy.getByTestId(depositsTab).click();
cy.getByTestId('deposit-button').click();
connectEthereumWallet('Unknown');
@@ -137,14 +138,9 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
it('can withdrawal', function () {
// 1002-WITH-0014
// 1002-WITH-006
// 1002-WITH-009
// 1002-WITH-011
// 1002-WITH-024
// 1002-WITH-012
// 1002-WITH-013
// 1002-WITH-014
// 1002-WITH-015
// 1002-WITH-016
// 1002-WITH-017
// 1002-WITH-019
@@ -237,28 +233,6 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
// cy.getByTestId('BALANCE_AVAILABLE_value').should('have.text', '6.999');
});
it('approved amount is less than deposit', function () {
// 1001-DEPO-006
// 1001-DEPO-007
cy.visit('/#/portfolio');
cy.get('[data-testid="pathname-/portfolio"]').should('exist');
cy.getByTestId(toastCloseBtn, txTimeout).click();
cy.getByTestId(depositsTab).click();
cy.getByTestId('deposit-button').click();
connectEthereumWallet('Unknown');
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.contains('Deposits of tBTC not approved').should('not.exist');
cy.contains('Use maximum').should('be.visible');
cy.get(amountField).clear().type('20000000');
cy.getByTestId(depositSubmit).should('be.visible');
cy.getByTestId(depositSubmit).click();
cy.getByTestId('input-error-text').should(
'contain.text',
`You can't deposit more than you have in your Ethereum wallet`
);
});
it('withdraw - delay verification', function () {
// 1001-DEPO-024
// 1002-WITH-007
@@ -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' }, () => {
+1 -1
View File
@@ -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'),
@@ -152,8 +152,8 @@ export const ApplyCodeForm = () => {
// 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>{' '}
@@ -205,15 +205,15 @@ export const ApplyCodeForm = () => {
return (
<>
<div 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)}
@@ -227,13 +227,13 @@ export const ApplyCodeForm = () => {
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>
)}
@@ -245,10 +245,10 @@ export const ApplyCodeForm = () => {
) : null}
{previewData ? (
<div className="mt-10">
<h2 className="mb-5 text-2xl">
<h2 className="text-2xl mb-5">
{t(
'You are joining the group shown, but will not have access to benefits until you have completed at least {{count}} epochs.',
{ count: nextBenefitTierEpochsValue }
'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" />
+2 -26
View File
@@ -8,9 +8,6 @@ import classNames from 'classnames';
import type { HTMLAttributes, ReactNode } from 'react';
import { Button } from './buttons';
import { useT } from '../../lib/use-t';
import { Routes } from '../../lib/links';
import { DApp, useLinks } from '@vegaprotocol/environment';
import truncate from 'lodash/truncate';
export const Tile = ({
className,
@@ -66,10 +63,6 @@ export const CodeTile = ({
className?: string;
}) => {
const t = useT();
const consoleLink = useLinks(DApp.Console);
const applyCodeLink = consoleLink(
`#${Routes.REFERRALS_APPLY_CODE}?code=${code}`
);
return (
<StatTile
title={t('Your referral code')}
@@ -96,27 +89,10 @@ export const CodeTile = ({
{code}
</div>
</Tooltip>
<CopyWithTooltip text={code} description={t('Copy referral code')}>
<CopyWithTooltip text={code}>
<Button className="text-sm no-underline !py-0 !px-0 h-fit !bg-transparent">
<span className="sr-only">{t('Copy')}</span>
<VegaIcon size={20} name={VegaIconNames.COPY} />
</Button>
</CopyWithTooltip>
<CopyWithTooltip
text={applyCodeLink}
description={
<>
{t('Copy shareable apply code link')}
{': '}
<a className="text-vega-blue-500 underline" href={applyCodeLink}>
{truncate(applyCodeLink, { length: 32 })}
</a>
</>
}
>
<Button className="text-sm no-underline !py-0 !px-0 h-fit !bg-transparent">
<span className="sr-only">{t('Copy')}</span>
<VegaIcon size={20} name={VegaIconNames.OPEN_EXTERNAL} />
<VegaIcon size={24} name={VegaIconNames.COPY} />
</Button>
</CopyWithTooltip>
</div>
@@ -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>
@@ -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 -1
View File
@@ -1,2 +1,2 @@
CONSOLE_IMAGE_NAME=vegaprotocol/trading:latest
VEGA_VERSION=v0.73.5
VEGA_VERSION=v0.73.4
+1 -1
View File
@@ -1,2 +1,2 @@
CONSOLE_IMAGE_NAME=vegaprotocol/trading:develop
VEGA_VERSION=v0.73.5
VEGA_VERSION=v0.73.4
+1 -1
View File
@@ -1,2 +1,2 @@
CONSOLE_IMAGE_NAME=vegaprotocol/trading:main
VEGA_VERSION=v0.73.5
VEGA_VERSION=v0.73.4
+1 -11
View File
@@ -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()
+14 -1
View File
@@ -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()
)
+14 -4
View File
@@ -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():
+9 -7
View File
@@ -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}"
-12
View File
@@ -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]
-11
View File
@@ -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,
@@ -39,7 +39,6 @@ export const AgGridThemed = ({
ref={gridRef}
overlayLoadingTemplate={t('Loading...')}
overlayNoRowsTemplate={t('No data')}
suppressDragLeaveHidesColumns
{...defaultProps}
{...props}
/>
+21 -2
View File
@@ -84,6 +84,19 @@ beforeEach(() => {
});
});
// Missing ACs
// 1001-DEPO-002
/* must select the asset that I want to deposit (1001-DEPO-002)
should easily see the assets that I have a non-zero balance for (in the connected eth wallet)
should see the ERC20 token address of the asset
should see the Vega asset symbol
should see the Vega asset name */
// 1001-DEPO-009
// must see feedback on the deposit ETH transaction (1001-DEPO-009)
// 1001-DEPO-010
// must see feedback that the deposit has or has not been credited to the Vega key (1001-DEPO-010)
describe('Deposit form', () => {
it('renders with default values', async () => {
render(<DepositForm {...props} />);
@@ -95,6 +108,7 @@ describe('Deposit form', () => {
);
expect(screen.getByLabelText('Asset')).toHaveValue('');
expect(screen.getByLabelText('To (Vega key)')).toHaveValue('');
// 1001-DEPO-003
expect(screen.getByLabelText('Amount')).toHaveValue(null);
});
@@ -104,6 +118,7 @@ describe('Deposit form', () => {
fireEvent.submit(screen.getByTestId('deposit-form'));
// 1001-DEPO-005
expect(props.submitDeposit).not.toHaveBeenCalled();
const validationMessages = await screen.findAllByRole('alert');
expect(validationMessages).toHaveLength(3);
@@ -120,7 +135,7 @@ describe('Deposit form', () => {
render(<DepositForm {...props} />);
fireEvent.submit(screen.getByTestId('deposit-form'));
// 1001-DEPO-001
expect(
await screen.findByText('Connect Ethereum wallet')
).toBeInTheDocument();
@@ -191,6 +206,8 @@ describe('Deposit form', () => {
});
fireEvent.submit(screen.getByTestId('deposit-form'));
// 1001-DEPO-006
// 1001-DEPO-007
expect(
await screen.findByText(
"You can't deposit more than your approved deposit amount, 30"
@@ -306,7 +323,8 @@ describe('Deposit form', () => {
});
fireEvent.click(screen.getByRole('button', { name: 'Deposit' }));
// 1001-DEPO-005
// 1001-DEPO-008
await waitFor(() => {
expect(props.submitDeposit).toHaveBeenCalledWith({
// @ts-ignore contract address definitely defined
@@ -314,6 +332,7 @@ describe('Deposit form', () => {
amount: '8',
vegaPublicKey: pubKey,
});
screen.debug();
});
});
-2
View File
@@ -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,
},
};
+1 -1
View File
@@ -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"
}
+1 -22
View File
@@ -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,7 +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",
"Referral benefits": "Referral benefits",
"Referral discount": "Referral discount",
"referral-statistics-commission": "Commission earned in <0>qUSD</0> (last {{count}} epochs)",
@@ -215,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",
@@ -242,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",
@@ -269,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",
@@ -283,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",
@@ -304,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.",
-63
View File
@@ -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"
}
-49
View File
@@ -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');
});
});
+2 -3
View File
@@ -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 -1
View File
@@ -1,3 +1,3 @@
import { useTranslation } from 'react-i18next';
export const useT = () => useTranslation('markets').t;
export const useT = () => useTranslation('funding-payments').t;
@@ -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;
+1 -3
View File
@@ -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>
);
+1 -13
View File
@@ -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.
@@ -1,41 +1,24 @@
import type { ReactElement, ReactNode } from 'react';
import type { ReactElement } from 'react';
import { Tooltip } from '../tooltip';
import CopyToClipboard from 'react-copy-to-clipboard';
import { useCopyTimeout } from '@vegaprotocol/react-helpers';
import { useT } from '../../use-t';
export const TOOLTIP_TIMEOUT = 800;
export interface CopyWithTooltipProps {
children: ReactElement;
text: string;
/**
* The tooltip's description to be shown on mouse over
* (replaced by "Copied" when clicked on)
*/
description?: ReactNode;
}
export function CopyWithTooltip({
children,
text,
description,
}: CopyWithTooltipProps) {
const t = useT();
export function CopyWithTooltip({ children, text }: CopyWithTooltipProps) {
const [copied, setCopied] = useCopyTimeout();
const copiedDescription = t('Copied');
return (
<CopyToClipboard text={text} onCopy={() => setCopied(true)}>
{/*
// @ts-ignore not sure about this typescript error. Needs this wrapping span as tooltip component interferes with element used to capture click for copy */}
<span>
<Tooltip
description={copied ? copiedDescription : description}
open={description ? copied || undefined : copied}
align="center"
>
<Tooltip description="Copied" open={copied} align="center">
{children}
</Tooltip>
</span>
@@ -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
@@ -1,4 +1,5 @@
import capitalize from 'lodash/capitalize';
import { t } from '@vegaprotocol/i18n';
import {
Button,
ButtonLink,
@@ -15,7 +16,6 @@ import { ConnectDialogTitle } from './connect-dialog-elements';
import { Status } from '../use-json-rpc-connect';
import { useVegaWallet } from '../use-vega-wallet';
import { setAcknowledged } from '../storage';
import { useT } from '../use-t';
export const ServiceErrors = {
NO_HEALTHY_NODE: 1000,
@@ -39,7 +39,6 @@ export const JsonRpcConnectorForm = ({
reset: () => void;
riskMessage?: React.ReactNode;
}) => {
const t = useT();
const { disconnect } = useVegaWallet();
if (status === Status.Idle) {
return null;
@@ -141,7 +140,7 @@ export const JsonRpcConnectorForm = ({
const Center = ({ children }: { children: ReactNode }) => {
return (
<div className="my-6 flex items-center justify-center">{children}</div>
<div className="flex justify-center items-center my-6">{children}</div>
);
};
@@ -156,7 +155,6 @@ const Error = ({
appChainId: string;
onTryAgain: () => void;
}) => {
const t = useT();
const { links } = useVegaWallet();
let title = t('Something went wrong');
let text: ReactNode | undefined = t('An unknown error occurred');
@@ -170,15 +168,13 @@ const Error = ({
if (error.code === ClientErrors.NO_SERVICE.code) {
title = t('No wallet detected');
text = connectorUrl
? t('No wallet application running at {{connectorUrl}}', {
connectorUrl,
})
? t('No wallet application running at %s', connectorUrl)
: t('No Vega Wallet application running');
} else if (error.code === ClientErrors.WRONG_NETWORK.code) {
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.code === ServiceErrors.NO_HEALTHY_NODE) {
title = error.title;
@@ -200,8 +196,9 @@ const Error = ({
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
)}
</>
);
@@ -216,15 +213,15 @@ const Error = ({
</span>
);
} else {
title = error.title;
text = error.message;
title = t(error.title);
text = t(error.message);
}
}
return (
<>
<ConnectDialogTitle>{title}</ConnectDialogTitle>
<p className="mb-2 text-center first-letter:uppercase">{text}</p>
<p className="text-center mb-2 first-letter:uppercase">{text}</p>
{tryAgain}
</>
);
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import {
TradingFormGroup,
TradingInput,
@@ -11,7 +12,6 @@ import { useForm } from 'react-hook-form';
import type { ViewConnector } from '../connectors';
import { useVegaWallet } from '../use-vega-wallet';
import { ConnectDialogTitle } from './connect-dialog-elements';
import { useT } from '../use-t';
interface FormFields {
address: string;
@@ -28,7 +28,6 @@ export function ViewConnectorForm({
onConnect,
reset,
}: ViewConnectorFormProps) {
const t = useT();
const { connect } = useVegaWallet();
const {
register,
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import { WalletClient, WalletClientError } from '@vegaprotocol/wallet-client';
import { clearConfig, getConfig, setConfig } from '../storage';
import type { Transaction, VegaConnector } from './vega-connector';
@@ -6,19 +7,19 @@ import { WalletError } from './vega-connector';
const VERSION = 'v2';
export const ClientErrors = {
NO_SERVICE: new WalletError('No service', 100),
INVALID_WALLET: new WalletError('Wallet version invalid', 103),
NO_SERVICE: new WalletError(t('No service'), 100),
INVALID_WALLET: new WalletError(t('Wallet version invalid'), 103),
WRONG_NETWORK: new WalletError(
'Wrong network',
t('Wrong network'),
104,
'App is configured to work with a different chain'
t('App is configured to work with a different chain')
),
UNKNOWN: new WalletError(
'Something went wrong',
t('Something went wrong'),
105,
'Unknown error occurred'
t('Unknown error occurred')
),
NO_CLIENT: new WalletError('No client found.', 106),
NO_CLIENT: new WalletError(t('No client found.'), 106),
} as const;
export class JsonRpcConnector implements VegaConnector {
@@ -155,10 +156,16 @@ export class JsonRpcConnector implements VegaConnector {
try {
const result = await fetch(`${this._url}/api/${this.version}/methods`);
if (!result.ok) {
const sent1 = `The version of the wallet service running at ${this._url} is not supported.`;
const sent2 = `Update the wallet software to a version that expose the API ${this.version}.`;
const sent1 = t(
'The version of the wallet service running at %s is not supported.',
this._url as string
);
const sent2 = t(
'Update the wallet software to a version that expose the API %s.',
this.version
);
const data = `${sent1}\n ${sent2}`;
const title = 'Wallet version invalid';
const title = t('Wallet version invalid');
throw new WalletError(title, ClientErrors.INVALID_WALLET.code, data);
}
return true;
@@ -1,4 +1,5 @@
import { truncateByChars } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
Button,
Dialog,
@@ -7,7 +8,6 @@ import {
Icon,
} from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '../use-vega-wallet';
import { useT } from '../use-t';
export interface VegaManageDialogProps {
dialogOpen: boolean;
@@ -18,7 +18,6 @@ export const VegaManageDialog = ({
dialogOpen,
setDialogOpen,
}: VegaManageDialogProps) => {
const t = useT();
const { pubKey, pubKeys, selectPubKey, disconnect } = useVegaWallet();
return (
<Dialog
@@ -39,13 +38,13 @@ export const VegaManageDialog = ({
className="mb-2 last:mb-0"
>
<div
className="flex justify-between gap-4 text-sm"
className="flex justify-between text-sm gap-4"
data-testid={isSelected ? 'selected-key' : ''}
>
<p data-testid="vega-public-key-full">
{truncateByChars(pk.publicKey)}
</p>
<div className="ml-auto flex gap-4">
<div className="flex ml-auto gap-4">
{!isSelected && (
<button
onClick={() => {
-13
View File
@@ -1,17 +1,4 @@
import '@testing-library/jest-dom';
import ResizeObserver from 'resize-observer-polyfill';
import { locales } from '@vegaprotocol/i18n';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// Set up i18n instance so that components have the correct default
// en translations
i18n.use(initReactI18next).init({
// we init with resources
resources: locales,
fallbackLng: 'en',
ns: ['wallet'],
defaultNS: 'wallet',
});
global.ResizeObserver = ResizeObserver;
-3
View File
@@ -1,3 +0,0 @@
import { useTranslation } from 'react-i18next';
export const ns = 'wallet';
export const useT = () => useTranslation(ns).t;
@@ -677,8 +677,10 @@ const VegaTxRequestedToastContent = ({ tx }: VegaTxToastContentProps) => {
);
};
const VegaTxPendingToastContent = ({ tx }: VegaTxToastContentProps) => {
const t = useT();
const VegaTxPendingToastContentProps = (
{ tx }: VegaTxToastContentProps,
t: ReturnType<typeof useT>
) => {
const explorerLink = useLinks(DApp.Explorer);
return (
<>
@@ -748,7 +750,7 @@ const VegaTxCompleteToastsContent = ({ tx }: VegaTxToastContentProps) => {
// eslint-disable-next-line jsx-a11y/anchor-is-valid
<a
href="#"
className="inline cursor-pointer break-words text-inherit underline underline-offset-4"
className="inline underline underline-offset-4 cursor-pointer text-inherit break-words"
data-testid="toast-withdrawal-details"
onClick={(e) => {
e.preventDefault();
@@ -991,7 +993,7 @@ export const getVegaTransactionContentIntent = (tx: VegaStoredTxState) => {
content = <VegaTxRequestedToastContent tx={tx} />;
}
if (tx.status === VegaTxStatus.Pending) {
content = <VegaTxPendingToastContent tx={tx} />;
content = <VegaTxPendingToastContentProps tx={tx} />;
}
if (tx.status === VegaTxStatus.Complete) {
content = <VegaTxCompleteToastsContent tx={tx} />;
-14
View File
@@ -1,14 +0,0 @@
export const useTranslation = () => ({
t: (label: string, replacements?: Record<string, string>) => {
let translatedLabel = label;
if (typeof replacements === 'object' && replacements !== null) {
Object.keys(replacements).forEach((key) => {
translatedLabel = translatedLabel.replace(
`{{${key}}}`,
replacements[key]
);
});
}
return translatedLabel;
},
});
@@ -1,13 +1,12 @@
import { t } from '@vegaprotocol/i18n';
import { Dialog } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { WithdrawFormContainer } from './withdraw-form-container';
import { useWeb3ConnectStore } from '@vegaprotocol/web3';
import { useWithdrawalDialog } from './withdrawal-dialog';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import { useT } from './use-t';
export const CreateWithdrawalDialog = () => {
const t = useT();
const { assetId, isOpen, open, close } = useWithdrawalDialog();
const { pubKey } = useVegaWallet();
const createTransaction = useVegaTransactionStore((state) => state.create);
@@ -60,6 +60,7 @@ it('Should perform the Ethereum transaction with the fetched approval', async ()
act(() => {
result.current.submit(withdrawalId);
});
// 1002-WITH-011
await waitFor(() => {
expect(mockPerform).toHaveBeenCalledWith(
erc20WithdrawalApproval.assetSource,
@@ -5,6 +5,7 @@ import type { Toast } from '@vegaprotocol/ui-toolkit';
import { Button, Intent, Panel, ToastHeading } from '@vegaprotocol/ui-toolkit';
import { useToasts } from '@vegaprotocol/ui-toolkit';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { t } from '@vegaprotocol/i18n';
import { formatNumber, toBigNum } from '@vegaprotocol/utils';
import { useNavigate } from 'react-router-dom';
import {
@@ -16,7 +17,6 @@ import {
import { withdrawalProvider } from './withdrawals-provider';
import type { WithdrawalFieldsFragment } from './__generated__/Withdrawal';
import uniqBy from 'lodash/uniqBy';
import { useT } from './use-t';
const CHECK_INTERVAL = 1000;
const ON_APP_START_TOAST_ID = `ready-to-withdraw`;
@@ -199,15 +199,15 @@ const MultipleReadyToWithdrawToastContent = ({
count: number;
withdrawalsLink?: string;
}) => {
const t = useT();
const navigate = useNavigate();
return (
<>
<ToastHeading>{t('Withdrawals ready')}</ToastHeading>
<p>
{t('Complete these {{count}} withdrawals to release your funds', {
count,
})}
{t(
'Complete these %s withdrawals to release your funds',
count.toString()
)}
</p>
<p className="mt-2">
<Button
@@ -229,7 +229,6 @@ const SingleReadyToWithdrawToastContent = ({
}: {
withdrawal: WithdrawalFieldsFragment;
}) => {
const t = useT();
const { createEthWithdrawalApproval } = useEthWithdrawApprovalsStore(
(state) => ({
createEthWithdrawalApproval: state.create,
@@ -267,10 +266,7 @@ const SingleReadyToWithdrawToastContent = ({
<p>{t('Complete the withdrawal to release your funds')}</p>
<Panel>
<strong>
{t('Withdraw {{amount}} {{symbol}}', {
amount,
symbol: withdrawal.asset.symbol,
})}
{t('Withdraw')} {amount} {withdrawal.asset.symbol}
</strong>
</Panel>
{completeButton}
-3
View File
@@ -1,3 +0,0 @@
import { useTranslation } from 'react-i18next';
export const ns = 'withdraws';
export const useT = () => useTranslation(ns).t;
@@ -2,6 +2,7 @@ import { useCallback, useState } from 'react';
import BigNumber from 'bignumber.js';
import { addDecimal } from '@vegaprotocol/utils';
import { localLoggerFactory } from '@vegaprotocol/logger';
import { t } from '@vegaprotocol/i18n';
import {
ApprovalStatus,
useGetWithdrawDelay,
@@ -14,7 +15,6 @@ import {
type Erc20ApprovalQueryVariables,
} from './__generated__/Erc20Approval';
import { useApolloClient } from '@apollo/client';
import { useT } from './use-t';
export interface VerifyState {
status: ApprovalStatus;
@@ -33,7 +33,6 @@ const initialState = {
};
export const useVerifyWithdrawal = () => {
const t = useT();
const client = useApolloClient();
const getThreshold = useGetWithdrawThreshold();
const getDelay = useGetWithdrawDelay();
@@ -63,9 +62,9 @@ export const useVerifyWithdrawal = () => {
if (withdrawal.asset.source.__typename !== 'ERC20') {
setState({
status: ApprovalStatus.Error,
message: t('Invalid asset source: {{source}}', {
source: withdrawal.asset.source.__typename,
}),
message: t(
`Invalid asset source: ${withdrawal.asset.source.__typename}`
),
});
return false;
}
@@ -133,7 +132,7 @@ export const useVerifyWithdrawal = () => {
return false;
}
},
[getThreshold, getDelay, client, setState, t]
[getThreshold, getDelay, client, setState]
);
return { verify, state, reset };
@@ -1,5 +1,6 @@
import { useMemo } from 'react';
import { toBigNum } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { AsyncRendererInline } from '@vegaprotocol/ui-toolkit';
import { accountsDataProvider } from '@vegaprotocol/accounts';
@@ -7,7 +8,6 @@ import { accountsDataProvider } from '@vegaprotocol/accounts';
import { WithdrawManager } from './withdraw-manager';
import * as Types from '@vegaprotocol/types';
import type { WithdrawalArgs } from './withdraw-form';
import { useT } from './use-t';
interface WithdrawFormContainerProps {
partyId?: string;
@@ -20,7 +20,6 @@ export const WithdrawFormContainer = ({
partyId,
submit,
}: WithdrawFormContainerProps) => {
const t = useT();
const { data, loading, error } = useDataProvider({
dataProvider: accountsDataProvider,
variables: { partyId: partyId || '' },
@@ -46,6 +46,7 @@ describe('Withdrawal form', () => {
render(<WithdrawForm {...props} />);
expect(screen.getByLabelText('Asset')).toHaveValue('');
// 1002-WITH-006
expect(screen.getByLabelText('To (Ethereum address)')).toHaveValue(
MOCK_ETH_ADDRESS
);
+10 -18
View File
@@ -8,6 +8,7 @@ import {
isAssetTypeERC20,
formatNumber,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useLocalStorage } from '@vegaprotocol/react-helpers';
import {
TradingFormGroup,
@@ -32,7 +33,6 @@ import {
} from '@vegaprotocol/web3';
import { AssetBalance } from './asset-balance';
import { DocsLinks } from '@vegaprotocol/environment';
import { useT } from './use-t';
export interface WithdrawalArgs {
amount: string;
@@ -69,11 +69,10 @@ const WithdrawDelayNotification = ({
symbol: string;
decimals: number;
}) => {
const t = useT();
const replacements = {
const replacements = [
symbol,
delay: delay ? formatDistanceToNow(Date.now() + delay * 1000) : ' ',
};
delay ? formatDistanceToNow(Date.now() + delay * 1000) : ' ',
];
return (
<Notification
intent={Intent.Warning}
@@ -85,17 +84,11 @@ const WithdrawDelayNotification = ({
}
message={[
threshold.isEqualTo(0)
? t(
'All {{symbol}} withdrawals are subject to a {{delay}} delay.',
replacements
)
: t(
'Withdrawals of {{threshold}} {{symbol}} or more will be delayed for {{delay}}.',
{
threshold: formatNumber(threshold, decimals),
...replacements,
}
),
? t('All %s withdrawals are subject to a %s delay.', replacements)
: t('Withdrawals of %s %s or more will be delayed for %s.', [
formatNumber(threshold, decimals),
...replacements,
]),
DocsLinks?.WITHDRAWAL_LIMITS ? (
<ExternalLink className="ml-1" href={DocsLinks.WITHDRAWAL_LIMITS}>
{t('Read more')}
@@ -118,10 +111,10 @@ export const WithdrawForm = ({
onSelectAsset,
submitWithdraw,
}: WithdrawFormProps) => {
const t = useT();
const ethereumAddress = useEthereumAddress();
const required = useRequired();
const minSafe = useMinSafe();
const { account: address } = useWeb3React();
const {
register,
@@ -322,7 +315,6 @@ const UseButton = (props: UseButtonProps) => {
};
const EthereumButton = ({ clearAddress }: { clearAddress: () => void }) => {
const t = useT();
const openDialog = useWeb3ConnectStore((state) => state.open);
const { isActive, connector } = useWeb3React();
const [, , removeEagerConnector] = useLocalStorage(ETHEREUM_EAGER_CONNECT);
+1 -2
View File
@@ -1,4 +1,5 @@
import type { Asset } from '@vegaprotocol/assets';
import { t } from '@vegaprotocol/i18n';
import { CompactNumber } from '@vegaprotocol/react-helpers';
import { WITHDRAW_THRESHOLD_TOOLTIP_TEXT } from '@vegaprotocol/assets';
import {
@@ -8,7 +9,6 @@ import {
} from '@vegaprotocol/ui-toolkit';
import BigNumber from 'bignumber.js';
import { formatDistanceToNow } from 'date-fns';
import { useT } from './use-t';
interface WithdrawLimitsProps {
amount: string;
@@ -25,7 +25,6 @@ export const WithdrawLimits = ({
delay,
asset,
}: WithdrawLimitsProps) => {
const t = useT();
const delayTime =
new BigNumber(amount).isGreaterThan(threshold) && delay
? formatDistanceToNow(Date.now() + delay * 1000)
@@ -69,6 +69,7 @@ describe('WithdrawManager', () => {
);
await userEvent.type(screen.getByLabelText('Amount'), '0.01');
await userEvent.click(screen.getByTestId('submit-withdrawal'));
// 1002-WITH-009
expect(props.submit).toHaveBeenCalledWith({
amount: '1000',
asset: props.assets[0].id,
+17 -24
View File
@@ -1,5 +1,6 @@
import { useEnvironment } from '@vegaprotocol/environment';
import { addDecimalsFormatNumber, truncateByChars } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
Button,
KeyValueTable,
@@ -10,8 +11,6 @@ import { getChainName, useWeb3ConnectStore } from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core';
import { formatDistanceToNow } from 'date-fns';
import type { WithdrawalFieldsFragment } from './__generated__/Withdrawal';
import { useT } from './use-t';
import { Trans } from 'react-i18next';
export const WithdrawalFeedback = ({
transaction,
@@ -24,7 +23,6 @@ export const WithdrawalFeedback = ({
submitWithdraw: (withdrawalId: string) => void;
availableTimestamp: number | null;
}) => {
const t = useT();
const { VEGA_EXPLORER_URL } = useEnvironment();
const isAvailable =
availableTimestamp === null || Date.now() > availableTimestamp;
@@ -32,20 +30,16 @@ export const WithdrawalFeedback = ({
return (
<div>
<p className="mb-2">
<Trans
defaults="Your funds have been unlocked for withdrawal - <0>View in block explorer<0>"
components={[
<a
className="underline"
data-testid="tx-block-explorer"
href={`${VEGA_EXPLORER_URL}/txs/0x${transaction.txHash}`}
target="_blank"
rel="noreferrer"
>
View in block explorer
</a>,
]}
/>
{t('Your funds have been unlocked for withdrawal')} -{' '}
<a
className="underline"
data-testid="tx-block-explorer"
href={`${VEGA_EXPLORER_URL}/txs/0x${transaction.txHash}`}
target="_blank"
rel="noreferrer"
>
{t('View in block explorer')}
</a>
</p>
{withdrawal && (
<KeyValueTable>
@@ -84,9 +78,11 @@ export const WithdrawalFeedback = ({
<ActionButton withdrawal={withdrawal} submitWithdraw={submitWithdraw} />
) : (
<p className="text-danger">
{t('Available to withdraw in {{availableTimestamp}}', {
availableTimestamp: formatDistanceToNow(availableTimestamp),
})}
{t(
`Available to withdraw in ${formatDistanceToNow(
availableTimestamp
)}`
)}
</p>
)}
</div>
@@ -100,7 +96,6 @@ const ActionButton = ({
withdrawal: WithdrawalFieldsFragment | null;
submitWithdraw: (withdrawalId: string) => void;
}) => {
const t = useT();
const { isActive, chainId } = useWeb3React();
const { open, desiredChainId } = useWeb3ConnectStore((store) => ({
open: store.open,
@@ -120,9 +115,7 @@ const ActionButton = ({
return (
<>
<p className="text-danger mb-2">
{t('This app only works on {{chainName}}. Please change chain.', {
chainName,
})}
{t(`This app only works on ${chainName}. Please change chain.`)}
</p>
<Button disabled={true}>{t('Withdraw funds')}</Button>
</>
@@ -76,6 +76,10 @@ describe('Withdrawals', () => {
'Completed',
'0x1234…121314',
];
// 1002-WITH-012
// 1002-WITH-013
// 1002-WITH-014
// 1002-WITH-015
cells.forEach((cell, i) => {
expect(cell).toHaveTextContent(expectedValues[i]);
});
+6 -12
View File
@@ -7,6 +7,7 @@ import {
isNumeric,
truncateByChars,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
ActionsDropdown,
ButtonLink,
@@ -29,7 +30,6 @@ import {
import * as Schema from '@vegaprotocol/types';
import { type TimestampedWithdrawals } from './use-ready-to-complete-withdrawals-toast';
import classNames from 'classnames';
import { useT } from './use-t';
export const WithdrawalsTable = ({
delayed,
@@ -39,14 +39,13 @@ export const WithdrawalsTable = ({
ready?: TimestampedWithdrawals;
delayed?: TimestampedWithdrawals;
}) => {
const t = useT();
const createWithdrawApproval = useEthWithdrawApprovalsStore(
(store) => store.create
);
const columnDefs = useMemo<ColDef[]>(
() => [
{ headerName: t('Asset'), field: 'asset.symbol' },
{ headerName: 'Asset', field: 'asset.symbol' },
{
headerName: t('Amount'),
field: 'amount',
@@ -129,7 +128,7 @@ export const WithdrawalsTable = ({
}),
},
],
[createWithdrawApproval, delayed, ready, t]
[createWithdrawApproval, delayed, ready]
);
return (
<AgGrid
@@ -152,7 +151,6 @@ export type CompleteCellProps = {
complete: (withdrawal: WithdrawalFieldsFragment) => void;
};
export const CompleteCell = ({ data, complete }: CompleteCellProps) => {
const t = useT();
const open = useWithdrawalApprovalDialog((state) => state.open);
const ref = useRef<HTMLButtonElement>(null);
@@ -208,8 +206,8 @@ export const StatusCell = ({
ready?: TimestampedWithdrawals;
delayed?: TimestampedWithdrawals;
}) => {
const t = useT();
const READY_TO_COMPLETE = t('Ready to complete');
const DELAYED = (readyIn: string) => t('Delayed (ready in %s)', readyIn);
const PENDING = t('Pending');
const COMPLETED = t('Completed');
const REJECTED = t('Rejected');
@@ -248,11 +246,7 @@ export const StatusCell = ({
if (isDelayed.timestamp == null) return;
const remaining = Date.now() - isDelayed.timestamp;
if (remaining < 0) {
setLabel(
t('Delayed (ready in {{readyIn}})', {
readyIn: convertToCountdownString(remaining, '0:00:00:00'),
})
);
setLabel(DELAYED(convertToCountdownString(remaining, '0:00:00:00')));
} else {
setLabel(READY_TO_COMPLETE);
}
@@ -260,7 +254,7 @@ export const StatusCell = ({
return () => {
clearInterval(interval);
};
}, [READY_TO_COMPLETE, data, delayed, isDelayed, isPending, t]);
}, [READY_TO_COMPLETE, data, delayed, isDelayed, isPending]);
return data ? (
<span
+1 -1
View File
@@ -19,7 +19,7 @@ EOT
pre_start {
docker_service "ganache-1" {
image = "vegaprotocol/ganache:v1.2.4"
image = "vegaprotocol/ganache:latest"
cmd = "ganache-cli"
args = [
"--blockTime", "1",