feat: persist table columns - resolve conflicts

This commit is contained in:
maciek
2023-05-03 13:25:15 +02:00
141 changed files with 3359 additions and 867 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ jobs:
secrets: inherit
lint-test-build:
timeout-minutes: 35
timeout-minutes: 60
needs: node-modules
runs-on: ubuntu-22.04
name: '(CI) lint + unit test + build'
@@ -4,7 +4,7 @@ import { t } from '@vegaprotocol/i18n';
import { ButtonLink } from '@vegaprotocol/ui-toolkit';
import type { AgGridReact } from 'ag-grid-react';
import { AgGridColumn } from 'ag-grid-react';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import type { VegaICellRendererParams } from '@vegaprotocol/datagrid';
import { useRef, useLayoutEffect } from 'react';
import { BREAKPOINT_MD } from '../../config/breakpoints';
@@ -14,7 +14,6 @@ import {
SettlementAssetInfoPanel,
} from '@vegaprotocol/market-info';
import { MarketInfoTable } from '@vegaprotocol/market-info';
import { Link } from 'react-router-dom';
export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
if (!market) return null;
@@ -97,22 +96,19 @@ export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
),
},
{
title: t('Oracle'),
title: t('Settlement Oracle'),
content: (
<OracleInfoPanel noBorder={false} market={market}>
<Link
className="text-xs hover:underline"
to={`/oracles#${market.tradableInstrument.instrument.product.dataSourceSpecForSettlementData.id}`}
>
{t('View settlement data oracle specification')}
</Link>
<Link
className="text-xs hover:underline"
to={`/oracles#${market.tradableInstrument.instrument.product.dataSourceSpecForTradingTermination.id}`}
>
{t('View termination oracle specification')}
</Link>
</OracleInfoPanel>
<OracleInfoPanel
noBorder={false}
market={market}
type="settlementData"
/>
),
},
{
title: t('Termination Oracle'),
content: (
<OracleInfoPanel noBorder={false} market={market} type="termination" />
),
},
];
@@ -3,7 +3,7 @@ import { t } from '@vegaprotocol/i18n';
import { ButtonLink } from '@vegaprotocol/ui-toolkit';
import type { AgGridReact } from 'ag-grid-react';
import { AgGridColumn } from 'ag-grid-react';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import type {
VegaICellRendererParams,
VegaValueGetterParams,
@@ -3,7 +3,7 @@ import { VoteProgress } from '@vegaprotocol/proposals';
import type { AgGridReact } from 'ag-grid-react';
import { AgGridColumn } from 'ag-grid-react';
import { ExternalLink } from '@vegaprotocol/ui-toolkit';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import type {
VegaICellRendererParams,
VegaValueFormatterParams,
+44
View File
@@ -1,3 +1,7 @@
@import 'ag-grid-community/dist/styles/ag-grid.css';
@import 'ag-grid-community/dist/styles/ag-theme-balham.css';
@import 'ag-grid-community/dist/styles/ag-theme-balham-dark.css';
/* You can add global styles to this file, and also import other style files */
@tailwind base;
@tailwind components;
@@ -11,3 +15,43 @@
.react-markdown-container a:before {
content: '🔗 ';
}
/* AG GRID - Do not edit without updating other global stylesheets for each app */
.vega-ag-grid .ag-root-wrapper {
border: solid 0px;
}
.vega-ag-grid .ag-react-container {
overflow: hidden;
text-overflow: ellipsis;
}
.vega-ag-grid .ag-cell,
.vega-ag-grid .ag-full-width-row .ag-cell-wrapper.ag-row-group {
line-height: calc(min(var(--ag-line-height, 26px), 26px) - 4px);
}
/* Light variables */
.ag-theme-balham {
--ag-background-color: theme(colors.white);
--ag-border-color: theme(colors.neutral[300]);
--ag-header-background-color: theme(colors.white);
--ag-odd-row-background-color: theme(colors.white);
--ag-header-column-separator-color: theme(colors.neutral[300]);
--ag-row-border-color: theme(colors.white);
--ag-row-hover-color: theme(colors.neutral[100]);
--ag-font-size: 12px;
}
/* Dark variables */
.ag-theme-balham-dark {
--ag-background-color: theme(colors.black);
--ag-border-color: theme(colors.neutral[700]);
--ag-header-background-color: theme(colors.black);
--ag-odd-row-background-color: theme(colors.black);
--ag-header-column-separator-color: theme(colors.neutral[600]);
--ag-row-border-color: theme(colors.black);
--ag-row-hover-color: theme(colors.neutral[800]);
--ag-font-size: 12px;
}
@@ -9,7 +9,7 @@
"name": "Token test market",
"code": "Token.24h",
"future": {
"settlementAsset": "fBTC",
"settlementAsset": "73174a6fb1d5802ba0ac7bd7ab79e0a3a4837b262de0a4e80815a55442692bd0",
"quoteName": "fBTC",
"dataSourceSpecForSettlementData": {
"external": {
@@ -49,6 +49,7 @@ describe(
});
beforeEach('visit proposals tab', function () {
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -217,9 +218,9 @@ describe(
vegaWalletSetSpecifiedApprovalAmount('1000');
createRawProposal();
cy.get<testFreeformProposal>('@rawProposal').then((rawProposal) => {
getSubmittedProposalFromProposalList(rawProposal.rationale.title)
.as('submittedProposal')
.within(() => cy.get(viewProposalButton).click());
getSubmittedProposalFromProposalList(
rawProposal.rationale.title
).within(() => cy.get(viewProposalButton).click());
});
voteForProposal('for');
// 3001-VOTE-079
@@ -237,9 +238,9 @@ describe(
);
navigateTo(navigation.proposals);
cy.get<testFreeformProposal>('@rawProposal').then((rawProposal) => {
getSubmittedProposalFromProposalList(rawProposal.rationale.title)
.as('submittedProposal')
.within(() => cy.get(viewProposalButton).click());
getSubmittedProposalFromProposalList(
rawProposal.rationale.title
).within(() => cy.get(viewProposalButton).click());
});
cy.get(proposalVoteProgressForPercentage)
.contains('100.00%')
@@ -16,6 +16,7 @@ import {
import { ethereumWalletConnect } from '../../support/wallet-eth.functions';
import { vegaWalletSetSpecifiedApprovalAmount } from '../../support/wallet-teardown.functions';
const proposalListItem = '[data-testid="proposals-list-item"]';
const closedProposals = '[data-testid="closed-proposals"]';
const proposalStatus = '[data-testid="proposal-status"]';
const viewProposalButton = '[data-testid="view-proposal-btn"]';
@@ -35,6 +36,7 @@ context(
});
beforeEach('visit proposals', function () {
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -51,7 +53,8 @@ context(
waitForSpinner();
cy.get(closedProposals).within(() => {
cy.contains(proposalTitle)
.parentsUntil('[data-testid="proposals-list-item"]')
.parentsUntil(proposalListItem)
.last()
.within(() => {
cy.get(proposalStatus).should('have.text', 'Enacted ');
cy.get(viewProposalButton).click();
@@ -78,7 +81,8 @@ context(
waitForSpinner();
cy.get(openProposals).within(() => {
cy.contains(proposalTitle)
.parentsUntil('[data-testid="proposals-list-item"]')
.parentsUntil(proposalListItem)
.last()
.within(() => cy.get(viewProposalButton).click());
});
getProposalInformationFromTable('State')
@@ -111,7 +115,8 @@ context(
waitForSpinner();
cy.get(openProposals, { timeout: 6000 }).within(() => {
cy.contains(proposalTitle)
.parentsUntil('[data-testid="proposals-list-item"]')
.parentsUntil(proposalListItem)
.last()
.within(() => cy.get(viewProposalButton).click());
});
getProposalInformationFromTable('State')
@@ -133,7 +138,8 @@ context(
waitForSpinner();
cy.get(openProposals).within(() => {
cy.contains(proposalTitle)
.parentsUntil('[data-testid="proposals-list-item"]')
.parentsUntil(proposalListItem)
.last()
.within(() => cy.get(viewProposalButton).click());
});
getProposalInformationFromTable('State')
@@ -84,6 +84,7 @@ context(
});
beforeEach('visit governance tab', function () {
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -76,6 +76,7 @@ context(
});
beforeEach('visit governance tab', function () {
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -304,7 +305,10 @@ context(
cy.get('dd').eq(0).should('have.text', 'Test market 1');
cy.get('dd').eq(1).should('have.text', 'TEST.24h');
cy.get('dd').eq(2).should('not.be.empty');
cy.get('dd').eq(2).invoke('text').as('EnactedMarketId');
cy.get('dd')
.eq(2)
.invoke('text')
.as('EnactedMarketId', { type: 'static' });
});
cy.get('@EnactedMarketId').then((marketId) => {
cy.VegaWalletSubmitLiquidityProvision(String(marketId), '1');
@@ -322,6 +326,7 @@ context(
cy.get('@EnactedMarketId').then((marketId) => {
cy.contains(String(marketId))
.parentsUntil(proposalListItem)
.last()
.within(() => {
cy.getByTestId(viewProposalBtn).click();
});
@@ -375,16 +380,19 @@ context(
cy.get(newProposalSubmitButton).should('be.visible').click();
// cannot submit a proposal with ERC20 address already in use
cy.contains('Proposal rejected', proposalTimeout).should('be.visible');
cy.getByTestId('dialog-content').within(() => {
cy.get('p').should(
'have.text',
'PROPOSAL_ERROR_ERC20_ADDRESS_ALREADY_IN_USE'
);
});
cy.getByTestId('dialog-content')
.last()
.within(() => {
cy.get('p').should(
'have.text',
'PROPOSAL_ERROR_ERC20_ADDRESS_ALREADY_IN_USE'
);
});
closeDialog();
navigateTo(navigation.proposals);
cy.contains(proposalTitle)
.parentsUntil(proposalListItem)
.last()
.within(() => {
cy.getByTestId(viewProposalBtn).click();
});
@@ -422,6 +430,7 @@ context(
cy.get(proposalType)
.contains('Update asset')
.parentsUntil(proposalListItem)
.last()
.within(() => {
cy.get(proposalDetails).should('contain.text', assetId); // 3001-VOTE-029
cy.getByTestId(viewProposalBtn).click();
@@ -35,6 +35,7 @@ describe('Governance flow for proposal list', { tags: '@slow' }, function () {
});
beforeEach('visit proposals tab', function () {
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -59,7 +60,10 @@ describe('Governance flow for proposal list', { tags: '@slow' }, function () {
cy.get(openProposals).within(() => {
cy.get(proposalClosingDate).first().should('contain.text', 'year');
cy.get(proposalClosingDate).should('contain.text', 'months');
cy.get(proposalClosingDate).last().should('contain.text', 'days');
cy.get(proposalClosingDate)
.last()
.invoke('text')
.should('match', /days|minutes/);
});
});
@@ -25,9 +25,10 @@ const rewardsTimeOut = { timeout: 60000 };
context('rewards - flow', { tags: '@slow' }, function () {
before('set up environment to allow rewards', function () {
cy.clearLocalStorage();
cy.visit('/');
waitForSpinner();
depositAsset(vegaAssetAddress, '1000');
depositAsset(vegaAssetAddress, '1000', 18);
cy.validatorsSelfDelegate();
ethereumWalletConnect();
cy.connectVegaWallet();
@@ -56,7 +57,7 @@ context('rewards - flow', { tags: '@slow' }, function () {
cy.getByTestId(rewardsTable)
.first()
.within(() => {
cy.getByTestId('asset').should('have.text', 'Vega');
cy.getByTestId('asset', rewardsTimeOut).should('have.text', 'Vega');
cy.getByTestId('ACCOUNT_TYPE_GLOBAL_REWARD').should('have.text', '1');
cy.getByTestId('ACCOUNT_TYPE_FEES_INFRASTRUCTURE').should(
'have.text',
@@ -93,13 +94,13 @@ context('rewards - flow', { tags: '@slow' }, function () {
.within(() => {
cy.get('h2').first().should('contain.text', 'EPOCH');
cy.getByTestId('individual-rewards-asset').should('have.text', 'Vega');
cy.getByTestId('ACCOUNT_TYPE_GLOBAL_REWARD')
.should('contain.text', '0.1177')
.and('contain.text', '(11.7733%)');
cy.getByTestId('ACCOUNT_TYPE_GLOBAL_REWARD', rewardsTimeOut)
.should('contain.text', '0.4415')
.and('contain.text', '(44.15%)');
cy.getByTestId('ACCOUNT_TYPE_FEES_INFRASTRUCTURE')
.should('contain.text', '0.0001')
.and('contain.text', '(11.7733%)');
cy.getByTestId('total').should('have.text', '0.1179');
.should('contain.text', '0.0004')
.and('contain.text', '(44.15%)');
cy.getByTestId('total').should('have.text', '0.4419');
});
});
});
@@ -66,7 +66,7 @@ context(
beforeEach(
'teardown wallet & drill into a specific validator',
function () {
cy.clearAllLocalStorage();
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -53,6 +53,7 @@ context(
beforeEach(
'teardown wallet & drill into a specific validator',
function () {
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -90,9 +91,14 @@ context(
verifyEthWalletTotalAssociatedBalance('2.0');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 2.0);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
2.0
);
});
cy.get(vegaWalletUnstakedBalance, txTimeout).should('contain', 2.0);
});
@@ -128,26 +134,38 @@ context(
stakingPageAssociateTokens('1001', { approve: true });
verifyEthWalletAssociatedBalance('1,001.00');
verifyEthWalletTotalAssociatedBalance('1,001.00');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
'1,001.00'
);
});
cy.get(vegaWallet)
.last()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
'1,001.00'
);
});
});
it('Able to disassociate a partial amount of tokens currently associated', function () {
stakingPageAssociateTokens('2');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 2.0);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
2.0
);
});
cy.get('button').contains('Select a validator to nominate').click();
stakingPageDisassociateTokens('1');
verifyEthWalletAssociatedBalance('1.0');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 1.0);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
1.0
);
});
});
it('Able to disassociate all tokens - using max', function () {
@@ -155,26 +173,40 @@ context(
const warningText =
'Warning: Any tokens that have been nominated to a node will sacrifice rewards they are due for the current epoch. If you do not wish to sacrifice these, you should remove stake from a node at the end of an epoch before disassociation.';
stakingPageAssociateTokens('2');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 2.0);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
2.0
);
});
cy.get('button').contains('Select a validator to nominate').click();
cy.get(ethWalletDissociateButton).click();
cy.get(disassociationWarning).should('contain', warningText);
stakingPageDisassociateAllTokens();
cy.get(ethWalletContainer).within(() => {
cy.contains(vegaWalletPublicKeyShort, { timeout: 20000 }).should(
'not.exist'
);
});
cy.get(ethWalletContainer).within(() => {
cy.contains(vegaWalletPublicKeyShort, { timeout: 20000 }).should(
'not.exist'
);
});
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 0.0);
});
cy.get(ethWalletContainer)
.first()
.within(() => {
cy.contains(vegaWalletPublicKeyShort, { timeout: 20000 }).should(
'not.exist'
);
});
cy.get(ethWalletContainer)
.first()
.within(() => {
cy.contains(vegaWalletPublicKeyShort, { timeout: 20000 }).should(
'not.exist'
);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
0.0
);
});
});
it('Able to associate and disassociate vesting contract tokens', function () {
@@ -200,9 +232,14 @@ context(
cy.getByTestId('currency-title', txTimeout).should('have.length', 6);
verifyEthWalletAssociatedBalance('2.0');
verifyEthWalletTotalAssociatedBalance('2.0');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 2.0);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
2.0
);
});
cy.get(vegaWalletUnstakedBalance, txTimeout).should('contain', 2.0);
stakingPageDisassociateTokens('1', {
type: 'contract',
@@ -228,38 +265,61 @@ context(
stakingPageAssociateTokens('21', { type: 'wallet' });
cy.get('button').contains('Select a validator to nominate').click();
stakingPageAssociateTokens('37', { type: 'contract' });
cy.get(vestingContractSection).within(() => {
cy.get(associatedKey).should(
'contain',
Cypress.env('vegaWalletPublicKeyShort')
);
cy.get(associatedAmount, txTimeout).should('contain', 37);
});
cy.get(vegaInWalletSection).within(() => {
cy.get(associatedKey).should(
'contain',
Cypress.env('vegaWalletPublicKeyShort')
);
cy.get(associatedAmount, txTimeout).should('contain', 21);
});
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 58);
});
cy.get(vestingContractSection)
.first()
.within(() => {
cy.get(associatedKey).should(
'contain',
Cypress.env('vegaWalletPublicKeyShort')
);
cy.get(associatedAmount, txTimeout).should('contain', 37);
});
cy.get(vegaInWalletSection)
.first()
.within(() => {
cy.get(associatedKey).should(
'contain',
Cypress.env('vegaWalletPublicKeyShort')
);
cy.get(associatedAmount, txTimeout).should('contain', 21);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
58
);
});
stakingPageDisassociateTokens('6', { type: 'contract' });
cy.get(vestingContractSection).within(() => {
cy.get(associatedAmount, txTimeout).should('contain', 31);
});
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 52);
});
cy.get(vestingContractSection)
.first()
.within(() => {
cy.get(associatedAmount, txTimeout).should('contain', 31);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
52
);
});
navigateTo(navigation.validators);
stakingPageDisassociateTokens('9', { type: 'wallet' });
cy.get(vegaInWalletSection).within(() => {
cy.get(associatedAmount, txTimeout).should('contain', 12);
});
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 43);
});
cy.get(vegaInWalletSection)
.first()
.within(() => {
cy.get(associatedAmount, txTimeout).should('contain', 12);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
43
);
});
});
it('Not able to associate more tokens than owned', function () {
@@ -318,9 +378,14 @@ context(
Cypress.env('vegaWalletPublicKey2')
);
stakingPageAssociateTokens('2');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should('contain', 2.0);
});
cy.get(vegaWallet)
.first()
.within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
2.0
);
});
cy.get(associateCompleteText).should(
'have.text',
`Vega key ${Cypress.env(
@@ -4,10 +4,7 @@ import {
waitForSpinner,
} from '../../support/common.functions';
import { ethereumWalletConnect } from '../../support/wallet-eth.functions';
import {
depositAsset,
vegaWalletTeardown,
} from '../../support/wallet-teardown.functions';
import { depositAsset } from '../../support/wallet-teardown.functions';
const withdraw = 'withdraw';
const withdrawalForm = 'withdraw-form';
@@ -25,6 +22,13 @@ const withdrawalAmount = 'withdrawal-amount';
const withdrawalRecipient = 'withdrawal-recipient';
const withdrawFundsButton = 'withdraw-funds';
const completeWithdrawalButton = 'complete-withdrawal';
const tableTxHash = '[col-id="txHash"]';
const tableAssetSymbol = '[col-id="asset.symbol"]';
const tableAmount = '[col-id="amount"]';
const tableReceiverAddress = '[col-id="details.receiverAddress"]';
const tableWithdrawnTimeStamp = '[col-id="withdrawnTimestamp"]';
const tableWithdrawnStatus = '[col-id="status"]';
const tableCreatedTimeStamp = '[col-id="createdTimestamp"]';
const usdtName = 'USDC (local)';
const usdcEthAddress = '0x1b8a1B6CBE5c93609b46D1829Cc7f3Cb8eeE23a0';
const usdcSymbol = 'tUSDC';
@@ -42,26 +46,23 @@ context(
cy.visit('/');
// When running tests locally, will fail if run without restarting capsule
cy.updateCapsuleMultiSig().then(() => {
depositAsset(usdcEthAddress, '100');
ethereumWalletConnect();
depositAsset(usdcEthAddress, '1000', 5);
});
});
beforeEach('Navigate to withdrawal page', function () {
cy.clearLocalStorage();
cy.reload();
waitForSpinner();
navigateTo(navigation.withdraw);
cy.connectVegaWallet();
ethereumWalletConnect();
vegaWalletTeardown();
});
it('Able to open withdrawal form with vega wallet connected', function () {
// needs to reload page for withdrawal form to be displayed in ci - not reproducible outside of ci
cy.reload();
waitForSpinner();
ethereumWalletConnect();
cy.getByTestId(withdraw).should('be.visible').click();
cy.getByTestId(withdrawalForm).within(() => {
cy.getByTestId(withdrawalForm, txTimeout).within(() => {
cy.get('select').find('option').should('have.length.at.least', 2);
cy.getByTestId(ethAddressInput).should('be.visible');
cy.getByTestId(amountInput).should('be.visible');
@@ -70,7 +71,7 @@ context(
it('Unable to submit withdrawal with invalid fields', function () {
cy.getByTestId(withdraw).should('be.visible').click();
cy.getByTestId(withdrawalForm).within(() => {
cy.getByTestId(withdrawalForm, txTimeout).within(() => {
cy.get('select').select(usdtSelectValue, { force: true });
cy.getByTestId(balanceAvailable, txTimeout).should('exist');
cy.getByTestId(submitWithdrawalButton).click();
@@ -94,7 +95,7 @@ context(
it('Able to withdraw asset: -eth wallet connected -withdraw funds button', function () {
// fill in withdrawal form
cy.getByTestId(withdraw).should('be.visible').click();
cy.getByTestId(withdrawalForm).within(() => {
cy.getByTestId(withdrawalForm, txTimeout).within(() => {
cy.get('select').select(usdtSelectValue, { force: true });
cy.getByTestId(balanceAvailable, txTimeout).should('exist');
cy.getByTestId(withdrawalThreshold).should(
@@ -102,7 +103,7 @@ context(
'100,000.00000T'
);
cy.getByTestId(delayTime).should('have.text', 'None');
cy.getByTestId(amountInput).click().type('100');
cy.getByTestId(amountInput).click().type('120');
cy.getByTestId(submitWithdrawalButton).click();
});
@@ -116,7 +117,7 @@ context(
.should('have.attr', 'href')
.and('contain', '/txs/');
cy.getByTestId(withdrawalAssetSymbol).should('have.text', usdcSymbol);
cy.getByTestId(withdrawalAmount).should('have.text', '100.00');
cy.getByTestId(withdrawalAmount).should('have.text', '120.00');
cy.getByTestId(withdrawalRecipient)
.should('have.text', truncatedWithdrawalEthAddress)
.and('have.attr', 'href')
@@ -128,26 +129,20 @@ context(
'Withdraw asset complete'
);
cy.getByTestId(dialogClose).click();
// need to reload page to see withdrawal history complete
cy.reload();
waitForAssetsDisplayed(usdtName);
// withdrawal history for complete withdrawal displayed
cy.get('[col-id="txHash"]', txTimeout)
.should('have.length.above', 1)
.eq(1)
cy.get(tableWithdrawnStatus)
.eq(1, txTimeout)
.should('have.text', 'Completed')
.parent()
.within(() => {
cy.get('[col-id="asset.symbol"]').should('have.text', usdcSymbol);
cy.get('[col-id="amount"]').should('have.text', '100.00');
cy.get('[col-id="details.receiverAddress"]')
cy.get(tableAssetSymbol).should('have.text', usdcSymbol);
cy.get(tableAmount).should('have.text', '120.00');
cy.get(tableReceiverAddress)
.find('a')
.should('have.attr', 'href')
.and('contain', 'https://sepolia.etherscan.io/address/');
cy.get('[col-id="withdrawnTimestamp"]').should('not.be.empty');
cy.get('[col-id="status"]').should('have.text', 'Completed');
cy.get('[col-id="txHash"]')
cy.get(tableWithdrawnTimeStamp).should('not.be.empty');
cy.get(tableTxHash)
.find('a')
.should('have.attr', 'href')
.and('contain', 'https://sepolia.etherscan.io/tx/');
@@ -155,16 +150,16 @@ context(
});
// Skipping because of bug #1857
it.skip('Able to withdraw asset: -eth wallet not connected', function () {
it('Able to withdraw asset: -eth wallet not connected', function () {
const ethWalletAddress = Cypress.env('ethWalletPublicKey');
cy.reload();
waitForAssetsDisplayed(usdtName);
// fill in withdrawal form
cy.getByTestId(withdraw).should('be.visible').click();
cy.getByTestId(withdrawalForm).within(() => {
cy.getByTestId(withdrawalForm, txTimeout).within(() => {
cy.get('select').select(usdtSelectValue, { force: true });
cy.getByTestId(ethAddressInput).should('be.empty');
cy.getByTestId(amountInput).click().type('100');
cy.getByTestId(amountInput).click().type('110');
cy.getByTestId(submitWithdrawalButton).click();
// Need eth address to submit withdrawal
@@ -180,20 +175,20 @@ context(
'Transaction complete'
);
cy.getByTestId(dialogClose).click();
cy.getByTestId(completeWithdrawalButton)
.eq(0)
.parent()
cy.get(tableTxHash)
.eq(1)
.should('have.text', 'Complete withdrawal')
.parent()
.within(() => {
cy.get('[col-id="asset.symbol"]').should('have.text', usdcSymbol);
cy.get('[col-id="amount"]').should('have.text', '100.00');
cy.get('[col-id="details.receiverAddress"]')
cy.get(tableAssetSymbol).should('have.text', usdcSymbol);
cy.get(tableAmount).should('have.text', '110.00');
cy.get(tableReceiverAddress)
.find('a')
.should('have.attr', 'href')
.and('contain', 'https://sepolia.etherscan.io/address/');
cy.get('[col-id="createdTimestamp"]').should('not.be.empty');
cy.get(tableCreatedTimeStamp).should('not.be.empty');
cy.getByTestId(completeWithdrawalButton).click();
// Unable to complete withdrawal in Capsule
});
});
@@ -202,26 +197,28 @@ context(
const expectedErrorTxt = `You are connected in a view only state for public key: ${vegaWalletPubKey}. In order to send transactions you must connect to a real wallet.`;
// Disconnect vega wallet
cy.getByTestId('manage-vega-wallet').click();
cy.getByTestId('manage-vega-wallet').last().click();
cy.getByTestId('disconnect').click();
cy.connectPublicKey(vegaWalletPubKey);
cy.getByTestId(withdraw).should('be.visible').click();
cy.getByTestId(withdrawalForm).within(() => {
cy.getByTestId(withdrawalForm, txTimeout).within(() => {
cy.get('select').select(usdtSelectValue, { force: true });
cy.getByTestId(balanceAvailable, txTimeout).should('exist');
cy.getByTestId(amountInput).click().type('100');
cy.getByTestId(submitWithdrawalButton).click();
});
cy.getByTestId('dialog-content').within(() => {
cy.get('h1').should('have.text', 'Transaction failed');
cy.getByTestId('Error').should('have.text', expectedErrorTxt);
});
cy.getByTestId('dialog-content')
.last()
.within(() => {
cy.get('h1').should('have.text', 'Transaction failed');
cy.getByTestId('Error').should('have.text', expectedErrorTxt);
});
});
function waitForAssetsDisplayed(expectedAsset: string) {
cy.contains(expectedAsset, txTimeout).should('be.visible');
cy.getByTestId('currency-title').should('contain.text', expectedAsset);
}
}
);
@@ -90,6 +90,7 @@ export function getSubmittedProposalFromProposalList(proposalTitle: string) {
export function getProposalIdFromList(proposalTitle: string) {
cy.contains(proposalTitle)
.parentsUntil(proposalListItem)
.last()
.within(() => {
cy.get(proposalDetails)
.invoke('text')
@@ -133,7 +134,7 @@ export function waitForProposalSync() {
// before proposal appears in the list - so rather than hard coded wait - we just wait on the
// delegation checks that are performed on the governance page.
cy.intercept('POST', '/query', (req) => {
cy.intercept('POST', '/graphql', (req) => {
if (req.body.operationName === 'Delegations') {
req.alias = 'proposalDelegationsCompletion';
}
@@ -143,7 +144,7 @@ export function waitForProposalSync() {
cy.wait(['@proposalDelegationsCompletion', '@proposalDelegationsCompletion']);
// Turn off this intercept from here on in
cy.intercept('POST', '/query', (req) => {
cy.intercept('POST', '/graphql', (req) => {
if (req.body.operationName === 'Delegations') {
req.continue();
}
@@ -35,18 +35,25 @@ const stakingBridgeContract = new StakingBridge(
);
const vestingContract = new TokenVesting(vegaTokenContractAddress, signer);
export async function depositAsset(assetEthAddress: string, amount: string) {
export async function depositAsset(
assetEthAddress: string,
amount: string,
decimalPlaces: number
) {
// Approve asset
const faucet = new TokenFaucetable(assetEthAddress, signer);
cy.wrap(faucet.approve(Erc20BridgeAddress, amount + '0'.repeat(19)), {
timeout: transactionTimeout,
log: false,
}).then(() => {
cy.wrap(
faucet.approve(Erc20BridgeAddress, amount + '0'.repeat(decimalPlaces + 1)),
{
timeout: transactionTimeout,
log: false,
}
).then(() => {
const collateralBridge = new CollateralBridge(Erc20BridgeAddress, signer);
cy.wrap(
collateralBridge.deposit_asset(
assetEthAddress,
amount + '0'.repeat(18),
amount + '0'.repeat(decimalPlaces),
'0x' + vegaWalletPubKey
),
{ timeout: transactionTimeout, log: false }
@@ -102,27 +109,49 @@ async function vegaWalletTeardownStaking(stakingBridgeContract: StakingBridge) {
cy.highlight('Tearing down staking tokens from vega wallet if present');
cy.wrap(
stakingBridgeContract.stake_balance(ethWalletPubKey, vegaWalletPubKey),
{ timeout: transactionTimeout, log: false }
{ timeout: transactionTimeout }
).then((stakeBalance) => {
if (Number(stakeBalance) != 0) {
cy.get('[data-testid="vega-wallet-balance-unstaked"]:visible').within(
() => {
cy.get(associatedAmountInWallet)
.invoke('text')
.then(($walletAmount) => {
cy.wrap(
stakingBridgeContract.remove_stake(
String(stakeBalance),
vegaWalletPubKey
),
{ timeout: transactionTimeout, log: false }
);
cy.get(associatedAmountInWallet, {
cy.get(vegaWalletContainer).within(() => {
cy.getByTestId('currency-value')
.first()
.invoke('text')
.then(($associatedAmount) => {
cy.wrap(
stakingBridgeContract.remove_stake(
String(stakeBalance),
vegaWalletPubKey
),
{ timeout: transactionTimeout }
);
cy.wrap(
vestingContract.stake_balance(ethWalletPubKey, vegaWalletPubKey),
{
timeout: transactionTimeout,
}).should('not.have.text', $walletAmount);
log: false,
}
).then((vestingAmount) => {
if (Number(vestingAmount) != 0) {
cy.contains('Associated', {
timeout: transactionTimeout,
})
.parent()
.parent()
.within(() => {
cy.getByTestId('currency-value', {
timeout: transactionTimeout,
})
.should('have.length', 1)
.invoke('text')
.as('displayedAmount');
cy.get('@displayedAmount', {
timeout: transactionTimeout,
}).should('not.eq', $associatedAmount);
});
}
});
}
);
});
});
}
});
}
@@ -136,7 +165,7 @@ async function vegaWalletTeardownVesting(vestingContract: TokenVesting) {
if (Number(vestingAmount) != 0) {
cy.wrap(
vestingContract.remove_stake(String(vestingAmount), vegaWalletPubKey),
{ timeout: transactionTimeout, log: false }
{ timeout: transactionTimeout }
);
}
});
@@ -0,0 +1,39 @@
import { render, screen } from '@testing-library/react';
import { DisconnectedNotice } from './disconnected-notice';
describe('DisconnectedNotice', () => {
it('renders Notification when isDisconnected is true and correctNetworkChainId is valid', () => {
render(
<DisconnectedNotice isDisconnected={true} correctNetworkChainId={'1'} />
);
const disconnectedNotice = screen.getByTestId('disconnected-notice');
expect(disconnectedNotice).toBeInTheDocument();
});
it("doesn't render Notification when isDisconnected is false", () => {
render(
<DisconnectedNotice isDisconnected={false} correctNetworkChainId={'1'} />
);
const disconnectedNotice = screen.queryByTestId('disconnected-notice');
expect(disconnectedNotice).not.toBeInTheDocument();
});
it("doesn't render Notification when correctNetworkChainId is undefined", () => {
render(
<DisconnectedNotice
isDisconnected={true}
correctNetworkChainId={undefined}
/>
);
const disconnectedNotice = screen.queryByTestId('disconnected-notice');
expect(disconnectedNotice).not.toBeInTheDocument();
});
it("doesn't render Notification when correctNetworkChainId is null", () => {
render(
<DisconnectedNotice isDisconnected={true} correctNetworkChainId={null} />
);
const disconnectedNotice = screen.queryByTestId('disconnected-notice');
expect(disconnectedNotice).not.toBeInTheDocument();
});
});
@@ -0,0 +1,33 @@
import { useTranslation } from 'react-i18next';
import { Intent, Notification } from '@vegaprotocol/ui-toolkit';
interface DisconnectedNoticeProps {
isDisconnected: boolean;
correctNetworkChainId?: string | null;
}
export const DisconnectedNotice = ({
isDisconnected,
correctNetworkChainId,
}: DisconnectedNoticeProps) => {
const { t } = useTranslation();
if (
!isDisconnected ||
correctNetworkChainId === undefined ||
correctNetworkChainId === null
) {
return null;
}
return (
<div className="col-span-full" data-testid="disconnected-notice">
<Notification
message={t('disconnectedNotice', {
correctNetwork: correctNetworkChainId,
})}
intent={Intent.Danger}
/>
</div>
);
};
@@ -0,0 +1 @@
export * from './disconnected-notice';
@@ -3,6 +3,7 @@ import React from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Button } from '@vegaprotocol/ui-toolkit';
import { DisconnectedNotice } from '../disconnected-notice';
import {
AppStateActionType,
@@ -26,7 +27,8 @@ import {
import { Loader } from '@vegaprotocol/ui-toolkit';
import colors from 'tailwindcss/colors';
import { useBalances } from '../../lib/balances/balances-store';
import { useWeb3Disconnect } from '@vegaprotocol/web3';
import { useEthereumConfig, useWeb3Disconnect } from '@vegaprotocol/web3';
import { getChainName } from '@vegaprotocol/web3';
const removeLeadingAddressSymbol = (key: string) => {
if (key && key.length > 2 && key.slice(0, 2) === '0x') {
@@ -182,16 +184,21 @@ const ConnectedKey = () => {
export const EthWallet = () => {
const { t } = useTranslation();
const { appDispatch } = useAppState();
const { appDispatch, appState } = useAppState();
const { account, connector } = useWeb3React();
const pendingTxs = usePendingTransactions();
const disconnect = useWeb3Disconnect(connector);
const { config } = useEthereumConfig();
return (
<WalletCard>
<section data-testid="ethereum-wallet">
<WalletCardHeader>
<h1 className="m-0 uppercase">{t('ethereumKey')}</h1>
<DisconnectedNotice
isDisconnected={appState.disconnectNotice}
correctNetworkChainId={getChainName(Number(config?.chain_id))}
/>
{account && (
<div className="place-self-end font-mono">
<div
@@ -1,13 +1,12 @@
import { Button, Splash } from '@vegaprotocol/ui-toolkit';
import {
getChainName,
useWeb3ConnectStore,
useWeb3Disconnect,
Web3ConnectDialog,
} from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core';
import type { ReactElement } from 'react';
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect, useState } from 'react';
import {
AppStateActionType,
useAppState,
@@ -36,9 +35,7 @@ export function Web3Connector({
const appChainId = Number(chainId);
return (
<>
<Web3Content appChainId={appChainId} setDialogOpen={setDialogOpen}>
{children}
</Web3Content>
<Web3Content appChainId={appChainId}>{children}</Web3Content>
<Web3ConnectDialog
connectors={connectors}
dialogOpen={appState.ethConnectOverlay}
@@ -52,23 +49,59 @@ export function Web3Connector({
interface Web3ContentProps {
children: ReactElement;
appChainId: number;
setDialogOpen: (isOpen: boolean) => void;
}
export const Web3Content = ({ children, appChainId }: Web3ContentProps) => {
const { appState, appDispatch } = useAppState();
const { connector, chainId } = useWeb3React();
const [previousChainId, setPreviousChainId] = useState(chainId);
const error = useWeb3ConnectStore((store) => store.error);
const disconnect = useWeb3Disconnect(connector);
const showDisconnectNotice = useCallback(
(isVisible: boolean) =>
appDispatch({
type: AppStateActionType.SET_DISCONNECT_NOTICE,
isVisible,
}),
[appDispatch]
);
useEffect(() => {
if (connector?.connectEagerly) {
connector.connectEagerly();
}
// wallet connect doesnt handle connectEagerly being called when connector is also in the
// wallet connect doesn't handle connectEagerly being called when connector is also in the
// deps array.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (chainId !== undefined) {
// We use this to detect when the user switches networks.
setPreviousChainId(chainId);
if (chainId !== appChainId) {
disconnect();
// If the user was previously connected, show the disconnect explanation notice.
if (previousChainId !== undefined && !appState.disconnectNotice) {
showDisconnectNotice(true);
}
} else if (appState.disconnectNotice) {
showDisconnectNotice(false);
}
}
}, [
appChainId,
appDispatch,
appState.disconnectNotice,
chainId,
disconnect,
previousChainId,
showDisconnectNotice,
]);
if (error) {
return (
<Splash>
@@ -80,18 +113,5 @@ export const Web3Content = ({ children, appChainId }: Web3ContentProps) => {
);
}
if (chainId !== undefined && chainId !== appChainId) {
return (
<Splash>
<div className="flex flex-col items-center gap-12">
<p className="text-white">
This app only works on {getChainName(appChainId)}
</p>
<Button onClick={() => disconnect()}>Disconnect</Button>
</div>
</Splash>
);
}
return children;
};
@@ -43,6 +43,11 @@ export interface AppState {
* Message to display in a banner at the top of the screen, currently always shown as a warning/error
*/
bannerMessage: string;
/**
* Displays a notice to the user that they have been disconnected because they've changed their
* ethereum network to an incompatible one.
*/
disconnectNotice: boolean;
}
export enum AppStateActionType {
@@ -58,6 +63,7 @@ export enum AppStateActionType {
SET_ASSOCIATION_BREAKDOWN,
SET_TRANSACTION_OVERLAY,
SET_BANNER_MESSAGE,
SET_DISCONNECT_NOTICE,
}
export type AppStateAction =
@@ -90,6 +96,10 @@ export type AppStateAction =
| {
type: AppStateActionType.SET_BANNER_MESSAGE;
message: string;
}
| {
type: AppStateActionType.SET_DISCONNECT_NOTICE;
isVisible: boolean;
};
type AppStateContextShape = {
@@ -1,8 +1,8 @@
import React from 'react';
import { BigNumber } from '../../lib/bignumber';
import { AppStateActionType, AppStateContext } from './app-state-context';
import type { AppState, AppStateAction } from './app-state-context';
import { AppStateActionType, AppStateContext } from './app-state-context';
interface AppStateProviderProps {
children: React.ReactNode;
@@ -19,6 +19,7 @@ const initialAppState: AppState = {
ethConnectOverlay: false,
transactionOverlay: false,
bannerMessage: '',
disconnectNotice: false,
};
function appStateReducer(state: AppState, action: AppStateAction): AppState {
@@ -68,6 +69,12 @@ function appStateReducer(state: AppState, action: AppStateAction): AppState {
bannerMessage: action.message,
};
}
case AppStateActionType.SET_DISCONNECT_NOTICE: {
return {
...state,
disconnectNotice: action.isVisible,
};
}
}
}
@@ -790,5 +790,6 @@
"approval (% validator voting power)": "approval (% validator voting power)",
"67% voting power required": "67% voting power required",
"Token": "Token",
"associateVegaNow": "Associate $VEGA now"
"associateVegaNow": "Associate $VEGA now",
"disconnectedNotice": "You have been disconnected. Connect your ETH wallet to the {{correctNetwork}} network to use this app."
}
@@ -56,6 +56,7 @@ const mockAppState: AppState = {
ethConnectOverlay: false,
transactionOverlay: false,
bannerMessage: '',
disconnectNotice: false,
};
jest.mock('../../../contexts/app-state/app-state-context', () => ({
@@ -1,8 +1,7 @@
import { render, screen } from '@testing-library/react';
import { ProposalRejectionReason, ProposalState } from '@vegaprotocol/types';
import { format } from 'date-fns';
import { formatDateWithLocalTimezone } from '@vegaprotocol/utils';
import { DATE_FORMAT_DETAILED } from '../../../../lib/date-formats';
import { generateProposal } from '../../test-helpers/generate-proposals';
import { ProposalChangeTable } from './proposal-change-table';
@@ -24,16 +23,15 @@ it('Renders all data for table', () => {
expect(screen.getByText('Closes on')).toBeInTheDocument();
expect(
screen.getByText(
format(new Date(proposal?.terms.closingDatetime), DATE_FORMAT_DETAILED)
formatDateWithLocalTimezone(new Date(proposal?.terms.closingDatetime))
)
).toBeInTheDocument();
expect(screen.getByText('Proposed enactment')).toBeInTheDocument();
expect(
screen.getByText(
format(
new Date(proposal?.terms.enactmentDatetime || 0),
DATE_FORMAT_DETAILED
formatDateWithLocalTimezone(
new Date(proposal?.terms.enactmentDatetime || 0)
)
)
).toBeInTheDocument();
@@ -43,7 +41,7 @@ it('Renders all data for table', () => {
expect(screen.getByText('Proposed on')).toBeInTheDocument();
expect(
screen.getByText(format(new Date(proposal?.datetime), DATE_FORMAT_DETAILED))
screen.getByText(formatDateWithLocalTimezone(new Date(proposal?.datetime)))
).toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
@@ -62,16 +60,15 @@ it('Changes data based on if data is in future or past', () => {
expect(screen.getByText('Closed on')).toBeInTheDocument();
expect(
screen.getByText(
format(new Date(proposal?.terms.closingDatetime), DATE_FORMAT_DETAILED)
formatDateWithLocalTimezone(new Date(proposal?.terms.closingDatetime))
)
).toBeInTheDocument();
expect(screen.getByText('Enacted on')).toBeInTheDocument();
expect(
screen.getByText(
format(
new Date(proposal?.terms.enactmentDatetime || 0),
DATE_FORMAT_DETAILED
formatDateWithLocalTimezone(
new Date(proposal?.terms.enactmentDatetime || 0)
)
)
).toBeInTheDocument();
@@ -91,9 +88,8 @@ it('Does not render enactment time for freeform proposal', () => {
expect(screen.queryByText('Enacted on')).not.toBeInTheDocument();
expect(
screen.queryByText(
format(
new Date(proposal?.terms.enactmentDatetime || 0),
DATE_FORMAT_DETAILED
formatDateWithLocalTimezone(
new Date(proposal?.terms.enactmentDatetime || 0)
)
)
).not.toBeInTheDocument();
@@ -1,12 +1,11 @@
import { format, isFuture } from 'date-fns';
import { isFuture } from 'date-fns';
import { useTranslation } from 'react-i18next';
import { formatDateWithLocalTimezone } from '@vegaprotocol/utils';
import {
KeyValueTable,
KeyValueTableRow,
RoundedWrapper,
} from '@vegaprotocol/ui-toolkit';
import { DATE_FORMAT_DETAILED } from '../../../../lib/date-formats';
import { CurrentProposalState } from '../current-proposal-state';
import type { ProposalFieldsFragment } from '../../proposals/__generated__/Proposals';
import type { ProposalQuery } from '../../proposal/__generated__/Proposal';
@@ -35,16 +34,15 @@ export const ProposalChangeTable = ({ proposal }: ProposalChangeTableProps) => {
{isFuture(new Date(terms?.closingDatetime))
? t('closesOn')
: t('closedOn')}
{format(new Date(terms?.closingDatetime), DATE_FORMAT_DETAILED)}
{formatDateWithLocalTimezone(new Date(terms?.closingDatetime))}
</KeyValueTableRow>
{terms?.change.__typename !== 'NewFreeform' ? (
<KeyValueTableRow>
{isFuture(new Date(terms?.enactmentDatetime || 0))
? t('proposedEnactment')
: t('enactedOn')}
{format(
new Date(terms?.enactmentDatetime || 0),
DATE_FORMAT_DETAILED
{formatDateWithLocalTimezone(
new Date(terms?.enactmentDatetime || 0)
)}
</KeyValueTableRow>
) : null}
@@ -54,7 +52,7 @@ export const ProposalChangeTable = ({ proposal }: ProposalChangeTableProps) => {
</KeyValueTableRow>
<KeyValueTableRow>
{t('proposedOn')}
{format(new Date(proposal?.datetime), DATE_FORMAT_DETAILED)}
{formatDateWithLocalTimezone(new Date(proposal?.datetime))}
</KeyValueTableRow>
{proposal?.rejectionReason ? (
<KeyValueTableRow>
@@ -19,6 +19,7 @@ const mockAppState: AppState = {
ethConnectOverlay: false,
transactionOverlay: false,
bannerMessage: '',
disconnectNotice: false,
};
jest.mock('../../../contexts/app-state/app-state-context', () => ({
@@ -3,7 +3,7 @@ import { forwardRef, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Button, Icon } from '@vegaprotocol/ui-toolkit';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import { useAppState } from '../../../../contexts/app-state/app-state-context';
import { BigNumber } from '../../../../lib/bignumber';
import {
@@ -17,7 +17,6 @@ import {
} from '../../shared';
import {
defaultColDef,
NODE_LIST_GRID_STYLES,
PendingStakeRenderer,
stakedTotalPercentage,
StakeShareRenderer,
@@ -382,12 +381,14 @@ export const ConsensusValidatorsTable = ({
);
return (
<div data-testid="consensus-validators-table">
<div
data-testid="consensus-validators-table"
className="validators-table"
>
{nodes.length > 0 && (
<AgGrid
domLayout="autoHeight"
style={{ width: '100%' }}
customThemeParams={NODE_LIST_GRID_STYLES}
getRowHeight={(params: RowHeightParams) => getRowHeight(params)}
defaultColDef={defaultColDef}
tooltipShowDelay={0}
@@ -79,17 +79,6 @@ export interface ValidatorsTableProps {
validatorsView: ValidatorsView;
}
// Custom styling to account for the scrollbar. This is needed because the
// AG Grid places the scrollbar over the bottom validator, which obstructs
export const NODE_LIST_GRID_STYLES = `
.ag-theme-balham-dark .ag-body-horizontal-scroll {
opacity: 0.75;
}
.ag-theme-balham-dark *:hover {
cursor: pointer;
}
`;
export const stakedTotalPercentage = (stakeScore: string) =>
formatNumberPercentage(toBigNum(stakeScore, 0).times(100), 2);
@@ -1,7 +1,7 @@
import { forwardRef, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import { useAppState } from '../../../../contexts/app-state/app-state-context';
import { BigNumber } from '../../../../lib/bignumber';
import {
@@ -13,7 +13,6 @@ import {
} from '../../shared';
import {
defaultColDef,
NODE_LIST_GRID_STYLES,
StakeNeededForPromotionRenderer,
stakedTotalPercentage,
ValidatorFields,
@@ -248,11 +247,13 @@ export const StandbyPendingValidatorsTable = ({
);
return (
<div data-testid="standby-pending-validators-table">
<div
data-testid="standby-pending-validators-table"
className="validators-table"
>
<AgGrid
domLayout="autoHeight"
style={{ width: '100%' }}
customThemeParams={NODE_LIST_GRID_STYLES}
rowHeight={68}
defaultColDef={defaultColDef}
tooltipShowDelay={0}
+44
View File
@@ -1,3 +1,7 @@
@import 'ag-grid-community/dist/styles/ag-grid.css';
@import 'ag-grid-community/dist/styles/ag-theme-balham.css';
@import 'ag-grid-community/dist/styles/ag-theme-balham-dark.css';
@tailwind base;
@tailwind components;
@tailwind utilities;
@@ -19,3 +23,43 @@
@apply border-vega-dark-200;
}
}
/* AG GRID - Do not edit without updating other global stylesheets for each app */
.vega-ag-grid .ag-root-wrapper {
border: solid 0px;
}
.vega-ag-grid .ag-react-container {
overflow: hidden;
text-overflow: ellipsis;
}
.vega-ag-grid .ag-cell,
.vega-ag-grid .ag-full-width-row .ag-cell-wrapper.ag-row-group {
line-height: calc(min(var(--ag-line-height, 26px), 26px) - 4px);
}
/* Light variables */
.ag-theme-balham {
--ag-background-color: theme(colors.white);
--ag-border-color: theme(colors.neutral[300]);
--ag-header-background-color: theme(colors.white);
--ag-odd-row-background-color: theme(colors.white);
--ag-header-column-separator-color: theme(colors.neutral[300]);
--ag-row-border-color: theme(colors.white);
--ag-row-hover-color: theme(colors.neutral[100]);
--ag-font-size: 12px;
}
/* Dark variables */
.ag-theme-balham-dark {
--ag-background-color: theme(colors.black);
--ag-border-color: theme(colors.neutral[700]);
--ag-header-background-color: theme(colors.black);
--ag-odd-row-background-color: theme(colors.black);
--ag-header-column-separator-color: theme(colors.neutral[600]);
--ag-row-border-color: theme(colors.black);
--ag-row-hover-color: theme(colors.neutral[800]);
--ag-font-size: 12px;
}
+44 -22
View File
@@ -38,7 +38,7 @@
"tranche_end": "2023-05-20T00:00:00.000Z",
"total_added": "19242.125",
"total_removed": "959.3245960538025",
"locked_amount": "11380.640506896220893725",
"locked_amount": "10740.2904998553229338",
"deposits": [
{
"amount": "188",
@@ -845,7 +845,7 @@
"tranche_end": "2023-05-06T00:00:00.000Z",
"total_added": "14520",
"total_removed": "5079.76864115505",
"locked_amount": "1811.7677314814820336",
"locked_amount": "1328.5631944444439712",
"deposits": [
{
"amount": "111",
@@ -4703,7 +4703,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "86666.297",
"total_removed": "0",
"locked_amount": "51463.9482091904865949352",
"locked_amount": "51226.896539776924515462",
"deposits": [
{
"amount": "86666.297",
@@ -4769,7 +4769,7 @@
"tranche_end": "2023-06-01T00:00:00.000Z",
"total_added": "2500",
"total_removed": "0",
"locked_amount": "408.562112077737175",
"locked_amount": "394.848424145299",
"deposits": [
{
"amount": "2500",
@@ -4802,7 +4802,7 @@
"tranche_end": "2023-11-01T00:00:00.000Z",
"total_added": "15000.000000000000015",
"total_removed": "0",
"locked_amount": "14897.55340428744001489755340428744",
"locked_amount": "14816.165647644927014816165647644927",
"deposits": [
{
"amount": "1.5e-14",
@@ -4890,7 +4890,7 @@
"tranche_end": "2023-09-01T00:00:00.000Z",
"total_added": "17500",
"total_removed": "0",
"locked_amount": "11578.848536886071",
"locked_amount": "11483.8961541364725",
"deposits": [
{
"amount": "12500",
@@ -5157,7 +5157,7 @@
"tranche_end": "2023-08-01T00:00:00.000Z",
"total_added": "37500",
"total_removed": "17836.1796921",
"locked_amount": "18800.41196669736",
"locked_amount": "18593.57015423572875",
"deposits": [
{
"amount": "7500",
@@ -5565,7 +5565,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "129999.45",
"total_removed": "0",
"locked_amount": "51416.99383189185572154",
"locked_amount": "51180.15844229965399674",
"deposits": [
{
"amount": "129999.45",
@@ -5598,7 +5598,7 @@
"tranche_end": "2024-04-01T00:00:00.000Z",
"total_added": "54144.7663",
"total_removed": "0",
"locked_amount": "49520.76209601310870544447",
"locked_amount": "49373.06871247784644592557",
"deposits": [
{
"amount": "54144.7663",
@@ -5631,7 +5631,7 @@
"tranche_end": "2023-09-03T00:00:00.000Z",
"total_added": "62600",
"total_removed": "0",
"locked_amount": "21222.827238711314258",
"locked_amount": "21051.60226407915008",
"deposits": [
{
"amount": "10000",
@@ -5824,7 +5824,7 @@
"tranche_end": "2023-09-17T00:00:00.000Z",
"total_added": "5000",
"total_removed": "0",
"locked_amount": "1886.89481861998965",
"locked_amount": "1873.218702435312",
"deposits": [
{
"amount": "5000",
@@ -6882,7 +6882,7 @@
"tranche_end": "2023-06-02T00:00:00.000Z",
"total_added": "1939928.38",
"total_removed": "1709370.7872515768348",
"locked_amount": "163396.8284281057515824046",
"locked_amount": "158090.6912451388393129414",
"deposits": [
{
"amount": "1852091.69",
@@ -40754,7 +40754,7 @@
"tranche_end": "2023-06-05T00:00:00.000Z",
"total_added": "3732368.4671",
"total_removed": "715655.108029600523393",
"locked_amount": "275585.361289865707282073326",
"locked_amount": "267431.675840398797767447499",
"deposits": [
{
"amount": "1998.95815",
@@ -42147,7 +42147,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "15870102.715470999700000001",
"total_removed": "866687.25765937723884852",
"locked_amount": "6276895.5825033304505713155238378505095972",
"locked_amount": "6247983.1374161640607671780970752321127332",
"deposits": [
{
"amount": "16249.93",
@@ -48724,8 +48724,8 @@
"tranche_start": "2021-11-05T00:00:00.000Z",
"tranche_end": "2023-05-05T00:00:00.000Z",
"total_added": "14597706.0446472999",
"total_removed": "6167911.210808830654624182",
"locked_amount": "73344.69712005803295291791238272985",
"total_removed": "6168897.174282186485373182",
"locked_amount": "46652.9124232901388230326056764886",
"deposits": [
{
"amount": "129284.449",
@@ -48979,6 +48979,11 @@
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tx": "0x2c531bd9c61e0a3705f161bba2c03703722f1e41533725684fcccb9176117e0e"
},
{
"amount": "985.963473355830749",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tx": "0x53d67a8df4d069f956ae1eb76d5e099642dcc8d7e40fa9357be0b8ae879b90c4"
},
{
"amount": "1360.32447632896938825",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
@@ -52315,6 +52320,12 @@
"tranche_id": 3,
"tx": "0x2c531bd9c61e0a3705f161bba2c03703722f1e41533725684fcccb9176117e0e"
},
{
"amount": "985.963473355830749",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tranche_id": 3,
"tx": "0x53d67a8df4d069f956ae1eb76d5e099642dcc8d7e40fa9357be0b8ae879b90c4"
},
{
"amount": "1360.32447632896938825",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
@@ -55137,8 +55148,8 @@
}
],
"total_tokens": "359123.469575",
"withdrawn_tokens": "356806.4980412878832315",
"remaining_tokens": "2316.9715337121167685"
"withdrawn_tokens": "357792.4615146437139805",
"remaining_tokens": "1331.0080603562860195"
},
{
"address": "0xBdd412797c1B78535Afc5F71503b91fAbD0160fB",
@@ -56607,7 +56618,7 @@
"tranche_start": "2021-10-05T00:00:00.000Z",
"tranche_end": "2023-04-05T00:00:00.000Z",
"total_added": "5778205.3912159303",
"total_removed": "3480709.486904665102263769",
"total_removed": "3480901.398845846498418769",
"locked_amount": "0",
"deposits": [
{
@@ -56757,6 +56768,11 @@
"user": "0x83b1a48376E045D26420200345414e6b93066396",
"tx": "0xeb193da202cd833a574a524eff7f1dd13a0ee8669e51a7db36984ef4d6735fd6"
},
{
"amount": "191.911941181396155",
"user": "0xBc934494675a6ceB639B9EfEe5b9C0f017D35a75",
"tx": "0xb741f4e653131d11eed34bc9c5f3f8425d23cf054b336f3dc61fbd936b39744a"
},
{
"amount": "219.945520329711288",
"user": "0xafa64cCa337eFEE0AD827F6C2684e69275226e90",
@@ -57779,6 +57795,12 @@
}
],
"withdrawals": [
{
"amount": "191.911941181396155",
"user": "0xBc934494675a6ceB639B9EfEe5b9C0f017D35a75",
"tranche_id": 4,
"tx": "0xb741f4e653131d11eed34bc9c5f3f8425d23cf054b336f3dc61fbd936b39744a"
},
{
"amount": "10509.407528939748325",
"user": "0xBc934494675a6ceB639B9EfEe5b9C0f017D35a75",
@@ -57889,8 +57911,8 @@
}
],
"total_tokens": "110499.5291",
"withdrawn_tokens": "110307.617158818603845",
"remaining_tokens": "191.911941181396155"
"withdrawn_tokens": "110499.5291",
"remaining_tokens": "0"
},
{
"address": "0xdbC5d439F373EB646345e1c67D1d46231ACE7dD3",
@@ -58802,7 +58824,7 @@
"tranche_end": "2023-06-05T00:00:00.000Z",
"total_added": "472355.6199999996",
"total_removed": "44078.8527972103416",
"locked_amount": "43668.075809464076001027650126832",
"locked_amount": "42376.077741542987921938344901044",
"deposits": [
{
"amount": "3000",
@@ -0,0 +1,375 @@
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { MarketState, MarketStateMapping } from '@vegaprotocol/types';
import { addDays, subDays } from 'date-fns';
import {
chainIdQuery,
statisticsQuery,
createDataConnection,
oracleSpecDataConnectionQuery,
createMarketFragment,
marketsQuery,
marketsDataQuery,
createMarketsDataFragment,
assetQuery,
networkParamsQuery,
} from '@vegaprotocol/mock';
import {
addDecimalsFormatNumber,
getDateTimeFormat,
} from '@vegaprotocol/utils';
describe('Closed markets', { tags: '@smoke' }, () => {
const rowSelector =
'[data-testid="tab-closed-markets"] .ag-center-cols-container .ag-row';
const assetsResult = assetQuery();
// @ts-ignore asset definitely exists
const settlementAsset = assetsResult.assetsConnection.edges[0].node;
const settledMarket = createMarketFragment({
id: '0',
state: MarketState.STATE_SETTLED,
marketTimestamps: {
open: subDays(new Date(), 10).toISOString(),
close: subDays(new Date(), 4).toISOString(),
},
tradableInstrument: {
instrument: {
product: {
dataSourceSpecForTradingTermination: {
id: 'market-1-trading-termination-oracle-id',
},
dataSourceSpecForSettlementData: {
id: 'market-1-settlement-data-oracle-id',
},
settlementAsset,
},
},
},
});
const terminatedMarket = createMarketFragment({
id: '1',
state: MarketState.STATE_TRADING_TERMINATED,
marketTimestamps: {
open: subDays(new Date(), 10).toISOString(),
close: null, // market
},
tradableInstrument: {
instrument: {
metadata: {
tags: [
`settlement-expiry-date:${addDays(new Date(), 4).toISOString()}`,
],
},
},
},
});
const delayedSettledMarket = createMarketFragment({
id: '2',
state: MarketState.STATE_TRADING_TERMINATED,
marketTimestamps: {
open: subDays(new Date(), 10).toISOString(),
close: null, // market
},
tradableInstrument: {
instrument: {
metadata: {
tags: [
`settlement-expiry-date:${subDays(new Date(), 2).toISOString()}`,
],
},
},
},
});
const unknownMarket = createMarketFragment({
id: '3',
state: MarketState.STATE_SETTLED,
});
const closedMarketsResult = [
{
node: settledMarket,
},
{
node: terminatedMarket,
},
{
node: delayedSettledMarket,
},
{ node: unknownMarket },
{
node: createMarketFragment({ id: '4', state: MarketState.STATE_PENDING }),
},
{
node: createMarketFragment({ id: '5', state: MarketState.STATE_ACTIVE }),
},
];
const settledMarketData = createMarketsDataFragment({
market: {
id: settledMarket.id,
},
bestBidPrice: '1000',
bestOfferPrice: '2000',
markPrice: '1500',
});
const closedMarketsDataResult = [
{
node: {
data: settledMarketData,
},
},
{
node: {
data: createMarketsDataFragment({
market: {
id: terminatedMarket.id,
},
}),
},
},
{
node: {
data: createMarketsDataFragment({
market: {
id: delayedSettledMarket.id,
},
}),
},
},
{
node: {
data: createMarketsDataFragment({
market: {
id: unknownMarket.id,
},
}),
},
},
];
const specDataConnection = createDataConnection();
before(() => {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
aliasGQLQuery(req, 'NetworkParams', networkParamsQuery());
aliasGQLQuery(
req,
'Markets',
marketsQuery({
marketsConnection: {
edges: closedMarketsResult,
},
})
);
aliasGQLQuery(
req,
'MarketsData',
marketsDataQuery({
marketsConnection: {
edges: closedMarketsDataResult,
},
})
);
aliasGQLQuery(
req,
'OracleSpecDataConnection',
oracleSpecDataConnectionQuery()
);
});
cy.mockSubscription();
cy.visit('/#/markets/all');
cy.get('[data-testid="Closed markets"]').click();
});
it('renders a settled market', () => {
const expectedMarkets = closedMarketsResult.filter((edge) => {
return [
MarketState.STATE_SETTLED,
MarketState.STATE_TRADING_TERMINATED,
].includes(edge.node.state);
});
const product = settledMarket.tradableInstrument.instrument.product;
// rows should be filtered to only include settled/terminated markets
cy.get(rowSelector).should('have.length', expectedMarkets.length);
// check each column in the first row renders correctly
// 6001-MARK-001
cy.get(rowSelector)
.first()
.find('[col-id="code"]')
.should('have.text', settledMarket.tradableInstrument.instrument.code);
// 6001-MARK-002
cy.get(rowSelector)
.first()
.find('[col-id="name"]')
.should('have.text', settledMarket.tradableInstrument.instrument.name);
// 6001-MARK-003
cy.get(rowSelector)
.first()
.find('[col-id="state"]')
.should('have.text', MarketStateMapping[settledMarket.state]);
// 6001-MARK-004
// 6001-MARK-005
// 6001-MARK-009
// 6001-MARK-008
// 6001-MARK-010
cy.get(rowSelector)
.first()
.find('[col-id="settlementDate"]')
.find('[data-testid="link"]')
.should(($el) => {
const href = $el.attr('href');
expect(href).to.match(
new RegExp(
`/oracles/${product.dataSourceSpecForTradingTermination.id}`
)
);
})
.should('have.text', '4 days ago')
.should(
'have.attr',
'title',
getDateTimeFormat().format(
new Date(settledMarket.marketTimestamps.close)
)
);
// 6001-MARK-011
cy.get(rowSelector)
.first()
.find('[col-id="bestBidPrice"]')
.should(
'have.text',
addDecimalsFormatNumber(
settledMarketData.bestBidPrice,
settledMarket.decimalPlaces
)
);
// 6001-MARK-012
cy.get(rowSelector)
.first()
.find('[col-id="bestOfferPrice"]')
.should(
'have.text',
addDecimalsFormatNumber(
settledMarketData.bestOfferPrice,
settledMarket.decimalPlaces
)
);
// 6001-MARK-013
cy.get(rowSelector).first().find('[col-id="markPrice"]').should(
'have.text',
addDecimalsFormatNumber(
settledMarketData.markPrice,
settledMarket.decimalPlaces
)
);
// 6001-MARK-014
// 6001-MARK-015
// 6001-MARK-016
cy.get(rowSelector)
.first()
.find('[col-id="settlementDataOracleId"]')
.find('[data-testid="link"]')
.should(($el) => {
const href = $el.attr('href');
expect(href).to.match(
new RegExp(`/oracles/${product.dataSourceSpecForSettlementData.id}`)
);
})
.should(
'have.text',
addDecimalsFormatNumber(
// @ts-ignore cannot deep un-partial
specDataConnection.externalData.data.data[0].value,
settledMarket.decimalPlaces
)
);
// 6001-MARK-017
cy.get(rowSelector)
.first()
.find('[col-id="realisedPNL"]')
.should('have.text', '-');
// 6001-MARK-018
cy.get(rowSelector)
.first()
.find('[col-id="settlementAsset"]')
.should('have.text', product.settlementAsset.symbol);
// 6001-MARK-020
cy.get(rowSelector)
.first()
.find('[col-id="id"]')
.should('have.text', settledMarket.id);
});
// test market list for market in terminated state
it('renders a terminated market', () => {
cy.get(rowSelector)
.eq(1)
.find('[col-id="state"]')
.should('have.text', MarketStateMapping[terminatedMarket.state]);
// 6001-MARK-006
// 6001-MARK-007
cy.get(rowSelector)
.eq(1)
.find('[col-id="settlementDate"]')
.find('[data-testid="link"]')
.should('have.text', 'Expected in 4 days');
});
it('renders a terminated market which was expected to have settled', () => {
cy.get(rowSelector)
.eq(2)
.find('[col-id="settlementDate"]')
.should('have.class', 'text-danger')
.find('[data-testid="link"]')
.should('have.text', 'Expected 2 days ago');
});
it('renders terminated market which doesnt have settlement date metadata', () => {
cy.get(rowSelector)
.eq(3)
.find('[col-id="settlementDate"]')
.find('[data-testid="link"]')
.should('have.text', 'Unknown');
});
it('can open asset detail dialog', () => {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Asset', assetsResult);
});
cy.get(rowSelector)
.first()
.find('[col-id="settlementAsset"]')
.find('button')
.click();
// 6001-MARK-019
cy.get('[data-testid="dialog-title"]').should(
'have.text',
`Asset details - ${settlementAsset.symbol}`
);
});
});
@@ -101,7 +101,7 @@ describe('deposit actions', { tags: '@smoke' }, () => {
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/');
cy.visit('/#/markets/market-1');
cy.wait('@MarketsCandles');
cy.getByTestId('dialog-close').click();
});
@@ -112,7 +112,6 @@ describe('deposit actions', { tags: '@smoke' }, () => {
'be.visible'
);
cy.contains('[data-testid="deposit"]', 'Deposit to trade').click();
connectEthereumWallet('MetaMask');
cy.getByTestId('deposit-submit').should('be.visible');
});
});
+2 -1
View File
@@ -153,7 +153,7 @@ describe('home', { tags: '@regression' }, () => {
// the choose market overlay is no longer showing
cy.contains('Select a market to get started').should('not.exist');
cy.contains('Loading...').should('not.exist');
cy.url().should('eq', Cypress.config().baseUrl + '/#/markets/market-1');
cy.url().should('eq', Cypress.config().baseUrl + '/#/markets/market-0');
});
});
@@ -172,6 +172,7 @@ describe('home', { tags: '@regression' }, () => {
],
},
};
// @ts-ignore partial deep check failing
const data = marketsDataQuery(override);
cy.mockGQL((req) => {
aliasGQLQuery(req, 'MarketsData', data);
@@ -180,25 +180,21 @@ describe('market info is displayed', { tags: '@smoke' }, () => {
it('oracle displayed', () => {
cy.getByTestId(marketTitle).contains('Oracle').click();
validateMarketDataRow(0, 'Settlement Data Property', 'prices.BTC.value');
validateMarketDataRow(
1,
'Trading Termination Property',
'termination.BTC.value'
);
// check that links to github for oracle proofs are shown
cy.getByTestId(accordionContent)
.getByTestId('oracle-proof-links')
.find(`[data-testid="${externalLink}"]`)
.should('have.attr', 'href')
.and('contain', 'https://github.com/vegaprotocol/well-known');
.getByTestId('provider-name')
.and('contain', 'Another oracle');
cy.getByTestId(accordionContent)
.getByTestId('oracle-spec-links')
.find(`[data-testid="${externalLink}"]`)
.should('have.attr', 'href')
.and('contain', '/oracles');
.getByTestId('signed-proofs')
.and('contain', '1');
cy.getByTestId(accordionContent)
.getByTestId('verified-proofs')
.and('contain', '1');
cy.getByTestId(accordionContent)
.getByTestId('signed-proofs')
.and('contain', '1');
});
it('proposal displayed', () => {
@@ -222,6 +222,7 @@ describe('markets table', { tags: '@smoke' }, () => {
],
},
};
// @ts-ignore partial deep check failing
const market = marketsQuery(override);
aliasGQLQuery(req, 'Market', market);
aliasGQLQuery(req, 'ProposalOfMarket', {
@@ -26,6 +26,7 @@ export function updateOrder(
override?: PartialDeep<OrderUpdateFieldsFragment>
): void {
const update: OrdersUpdateSubscription = orderUpdateSubscription({
// @ts-ignore partial deep check failing
orders: [override],
});
if (!sendOrderUpdate) {
+3
View File
@@ -46,7 +46,9 @@ const marketDataOverride = (
{
node: {
data: {
// @ts-ignore conflict between incoming and outgoing types
trigger: data.trigger,
// @ts-ignore same as above
marketTradingMode: data.tradingMode,
marketState: data.state,
},
@@ -63,6 +65,7 @@ const marketsDataOverride = (
edges: [
{
node: {
// @ts-ignore conflict between incoming and outgoing types
tradingMode: data.tradingMode,
state: data.state,
},
+28 -17
View File
@@ -27,7 +27,10 @@ import { NO_MARKET } from './constants';
import { LiquidityContainer } from '../liquidity/liquidity';
import { useNavigate } from 'react-router-dom';
import type { PinnedAsset } from '@vegaprotocol/accounts';
import { useScreenDimensions } from '@vegaprotocol/react-helpers';
import {
usePaneLayout,
useScreenDimensions,
} from '@vegaprotocol/react-helpers';
import {
useMarketClickHandler,
useMarketLiquidityClickHandler,
@@ -83,15 +86,20 @@ interface BottomPanelProps {
const MarketBottomPanel = memo(
({ marketId, pinnedAsset }: BottomPanelProps) => {
const [sizes, handleOnLayoutChange] = usePaneLayout({ id: 'bottom' });
const { screenSize } = useScreenDimensions();
const onMarketClick = useMarketClickHandler(true);
const onOrderTypeClick = useMarketLiquidityClickHandler(true);
return 'xxxl' === screenSize ? (
<ResizableGrid proportionalLayout minSize={200}>
<ResizableGrid
proportionalLayout
minSize={200}
onChange={handleOnLayoutChange}
>
<ResizableGridPanel
priority={LayoutPriority.Low}
preferredSize="50%"
preferredSize={sizes[0] || '50%'}
minSize={50}
>
<TradeGridChild>
@@ -120,7 +128,7 @@ const MarketBottomPanel = memo(
</ResizableGridPanel>
<ResizableGridPanel
priority={LayoutPriority.Low}
preferredSize="50%"
preferredSize={sizes[1] || '50%'}
minSize={50}
>
<TradeGridChild>
@@ -187,22 +195,29 @@ MarketBottomPanel.displayName = 'MarketBottomPanel';
const MainGrid = memo(
({
marketId,
onSelect,
pinnedAsset,
}: {
marketId: string;
onSelect: (marketId: string, metaKey?: boolean) => void;
pinnedAsset?: PinnedAsset;
}) => {
const navigate = useNavigate();
const [sizes, handleOnLayoutChange] = usePaneLayout({ id: 'top' });
const [sizesMiddle, handleOnMiddleLayoutChange] = usePaneLayout({
id: 'middle',
});
return (
<ResizableGrid vertical>
<ResizableGrid vertical onChange={handleOnLayoutChange}>
<ResizableGridPanel minSize={75} priority={LayoutPriority.High}>
<ResizableGrid proportionalLayout={false} minSize={200}>
<ResizableGrid
proportionalLayout={false}
minSize={200}
onChange={handleOnMiddleLayoutChange}
>
<ResizableGridPanel
priority={LayoutPriority.High}
minSize={200}
preferredSize="50%"
preferredSize={sizesMiddle[0] || '50%'}
>
<TradeGridChild>
<Tabs storageKey="console-trade-grid-main-left">
@@ -220,7 +235,7 @@ const MainGrid = memo(
</ResizableGridPanel>
<ResizableGridPanel
priority={LayoutPriority.Low}
preferredSize={330}
preferredSize={sizesMiddle[1] || 330}
minSize={300}
>
<TradeGridChild>
@@ -239,7 +254,7 @@ const MainGrid = memo(
</ResizableGridPanel>
<ResizableGridPanel
priority={LayoutPriority.Low}
preferredSize={430}
preferredSize={sizesMiddle[2] || 430}
minSize={200}
>
<TradeGridChild>
@@ -257,7 +272,7 @@ const MainGrid = memo(
</ResizableGridPanel>
<ResizableGridPanel
priority={LayoutPriority.Low}
preferredSize="25%"
preferredSize={sizes[1] || '25%'}
minSize={50}
>
<MarketBottomPanel marketId={marketId} pinnedAsset={pinnedAsset} />
@@ -279,11 +294,7 @@ export const TradeGrid = ({
<TradeMarketHeader market={market} onSelect={onSelect} />
<OracleBanner marketId={market?.id || ''} />
</div>
<MainGrid
marketId={market?.id || ''}
onSelect={onSelect}
pinnedAsset={pinnedAsset}
/>
<MainGrid marketId={market?.id || ''} pinnedAsset={pinnedAsset} />
</div>
);
};
@@ -0,0 +1,335 @@
import { act, render, screen, within } from '@testing-library/react';
import { Closed } from './closed';
import { MarketStateMapping } from '@vegaprotocol/types';
import { PositionStatus } from '@vegaprotocol/types';
import { MarketState } from '@vegaprotocol/types';
import { subDays } from 'date-fns';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { OracleSpecDataConnectionQuery } from '@vegaprotocol/oracles';
import { OracleSpecDataConnectionDocument } from '@vegaprotocol/oracles';
import type { VegaWalletContextShape } from '@vegaprotocol/wallet';
import { VegaWalletContext } from '@vegaprotocol/wallet';
import type {
PositionsQuery,
PositionFieldsFragment,
} from '@vegaprotocol/positions';
import { PositionsDocument } from '@vegaprotocol/positions';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import type { MarketsDataQuery, MarketsQuery } from '@vegaprotocol/market-list';
import { MarketsDataDocument } from '@vegaprotocol/market-list';
import { MarketsDocument } from '@vegaprotocol/market-list';
import {
createMarketFragment,
marketsQuery,
marketsDataQuery,
createMarketsDataFragment,
} from '@vegaprotocol/mock';
describe('Closed', () => {
let originalNow: typeof Date.now;
const mockNowTimestamp = 1672531200000;
const settlementDateMetaDate = subDays(
new Date(mockNowTimestamp),
3
).toISOString();
const settlementDateTag = `settlement-expiry-date:${settlementDateMetaDate}`;
const pubKey = 'pubKey';
const marketId = 'market-0';
const settlementDataProperty = 'spec-binding';
const settlementDataId = 'settlement-data-oracle-id';
const market = createMarketFragment({
id: marketId,
state: MarketState.STATE_SETTLED,
tradableInstrument: {
instrument: {
metadata: {
tags: [settlementDateTag],
},
product: {
dataSourceSpecForSettlementData: {
id: settlementDataId,
},
dataSourceSpecBinding: {
settlementDataProperty,
},
},
},
},
});
const marketsMock: MockedResponse<MarketsQuery> = {
request: {
query: MarketsDocument,
},
result: {
data: marketsQuery({
marketsConnection: {
edges: [
{
node: market,
},
],
},
}),
},
};
const marketsData = createMarketsDataFragment({
__typename: 'MarketData',
market: {
__typename: 'Market',
id: marketId,
},
bestBidPrice: '1000',
bestOfferPrice: '2000',
markPrice: '1500',
});
const marketsDataMock: MockedResponse<MarketsDataQuery> = {
request: {
query: MarketsDataDocument,
},
result: {
data: marketsDataQuery({
marketsConnection: {
edges: [
{
node: {
data: marketsData,
},
},
],
},
}),
},
};
// Create mock oracle data
const property = {
__typename: 'Property' as const,
name: settlementDataProperty,
value: '12345',
};
const oracleDataMock: MockedResponse<OracleSpecDataConnectionQuery> = {
request: {
query: OracleSpecDataConnectionDocument,
variables: {
oracleSpecId: settlementDataId,
},
},
result: {
data: {
oracleSpec: {
dataConnection: {
edges: [
{
node: {
externalData: {
data: {
data: [property],
},
},
},
},
],
},
},
},
},
};
// Create mock position
const createPosition = (): PositionFieldsFragment => {
return {
__typename: 'Position' as const,
realisedPNL: '1000',
unrealisedPNL: '2000',
openVolume: '3000',
averageEntryPrice: '100',
updatedAt: new Date().toISOString(),
positionStatus: PositionStatus.POSITION_STATUS_UNSPECIFIED,
lossSocializationAmount: '1000',
market: {
__typename: 'Market',
id: marketId,
},
};
};
const position = createPosition();
const positionsMock: MockedResponse<PositionsQuery> = {
request: {
query: PositionsDocument,
variables: {
partyId: pubKey,
},
},
result: {
data: {
party: {
__typename: 'Party',
id: pubKey,
positionsConnection: {
__typename: 'PositionConnection',
edges: [{ __typename: 'PositionEdge', node: position }],
},
},
},
},
};
beforeAll(() => {
originalNow = Date.now;
Date.now = jest.fn().mockReturnValue(mockNowTimestamp);
});
afterAll(() => {
Date.now = originalNow;
});
it('renders correctly formatted and filtered rows', async () => {
await act(async () => {
render(
<MockedProvider
mocks={[marketsMock, marketsDataMock, positionsMock, oracleDataMock]}
>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
);
});
// screen.debug(document, Infinity);
const headers = screen.getAllByRole('columnheader');
const expectedHeaders = [
'Market',
'Description',
'Status',
'Settlement date',
'Best bid',
'Best offer',
'Mark price',
'Settlement price',
'Realised PNL',
'Settlement asset',
'Market ID',
];
expect(headers).toHaveLength(expectedHeaders.length);
expect(headers.map((h) => h.textContent?.trim())).toEqual(expectedHeaders);
const cells = screen.getAllByRole('gridcell');
const expectedValues = [
market.tradableInstrument.instrument.code,
market.tradableInstrument.instrument.name,
MarketStateMapping[market.state],
'3 days ago',
/* eslint-disable @typescript-eslint/no-non-null-assertion */
addDecimalsFormatNumber(marketsData.bestBidPrice, market.decimalPlaces),
addDecimalsFormatNumber(
marketsData!.bestOfferPrice,
market.decimalPlaces
),
addDecimalsFormatNumber(marketsData!.markPrice, market.decimalPlaces),
/* eslint-enable @typescript-eslint/no-non-null-assertion */
addDecimalsFormatNumber(property.value, market.decimalPlaces),
addDecimalsFormatNumber(position.realisedPNL, market.decimalPlaces),
market.tradableInstrument.instrument.product.settlementAsset.symbol,
market.id,
];
cells.forEach((cell, i) => {
expect(cell).toHaveTextContent(expectedValues[i]);
});
});
it('only renders settled and terminated markets', async () => {
const mixedMarkets = [
{
// inlclude as settled
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'include-0',
state: MarketState.STATE_SETTLED,
}),
},
{
// omit this market
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'discard-0',
state: MarketState.STATE_SUSPENDED,
}),
},
{
// include as terminated
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'include-1',
state: MarketState.STATE_TRADING_TERMINATED,
}),
},
{
// omit this market
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'discard-1',
state: MarketState.STATE_ACTIVE,
}),
},
];
const mixedMarketsMock: MockedResponse<MarketsQuery> = {
request: {
query: MarketsDocument,
},
result: {
data: {
marketsConnection: {
__typename: 'MarketConnection',
edges: mixedMarkets,
},
},
},
};
await act(async () => {
render(
<MockedProvider
mocks={[
mixedMarketsMock,
marketsDataMock,
positionsMock,
oracleDataMock,
]}
>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
);
});
// check that the number of rows in datagrid is 2
const container = within(
document.querySelector('.ag-center-cols-container') as HTMLElement
);
const expectedRows = mixedMarkets.filter((m) => {
return [
MarketState.STATE_SETTLED,
MarketState.STATE_TRADING_TERMINATED,
].includes(m.node.state);
});
// check rows length is correct
const rows = container.getAllByRole('row');
expect(rows).toHaveLength(expectedRows.length);
// check that only included ids are shown
const cells = screen
.getAllByRole('gridcell')
.filter((cell) => cell.getAttribute('col-id') === 'id')
.map((cell) => cell.textContent?.trim());
expect(cells).toEqual(expectedRows.map((m) => m.node.id));
});
});
@@ -0,0 +1,285 @@
import compact from 'lodash/compact';
import { isAfter } from 'date-fns';
import type {
VegaICellRendererParams,
VegaValueFormatterParams,
} from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import { useMemo } from 'react';
import { t } from '@vegaprotocol/i18n';
import { MarketState, MarketStateMapping } from '@vegaprotocol/types';
import {
addDecimalsFormatNumber,
getMarketExpiryDate,
} from '@vegaprotocol/utils';
import { usePositionsQuery } from '@vegaprotocol/positions';
import type { MarketMaybeWithData } from '@vegaprotocol/market-list';
import { closedMarketsWithDataProvider } from '@vegaprotocol/market-list';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
import type { ColDef } from 'ag-grid-community';
import { SettlementDateCell } from './settlement-date-cell';
import { SettlementPriceCell } from './settlement-price-cell';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
type SettlementAsset =
MarketMaybeWithData['tradableInstrument']['instrument']['product']['settlementAsset'];
interface Row {
id: string;
code: string;
name: string;
decimalPlaces: number;
state: MarketState;
metadata: string[];
closeTimestamp: string | null;
bestBidPrice: string | undefined;
bestOfferPrice: string | undefined;
markPrice: string | undefined;
settlementDataOracleId: string;
settlementDataSpecBinding: string;
tradingTerminationOracleId: string;
settlementAsset: SettlementAsset;
realisedPNL: string | undefined;
}
export const Closed = () => {
const { pubKey } = useVegaWallet();
const {
data: marketData,
loading,
error,
reload,
} = useDataProvider({
dataProvider: closedMarketsWithDataProvider,
variables: undefined,
});
const { data: positionData } = usePositionsQuery({
variables: {
partyId: pubKey || '',
},
skip: !pubKey,
});
// find a position for each market and add the realised pnl to
// a normalized object
const rowData = compact(marketData).map((market) => {
const position = positionData?.party?.positionsConnection?.edges?.find(
(edge) => {
return edge.node.market.id === market.id;
}
);
const row: Row = {
id: market.id,
code: market.tradableInstrument.instrument.code,
name: market.tradableInstrument.instrument.name,
decimalPlaces: market.decimalPlaces,
state: market.state,
metadata: market.tradableInstrument.instrument.metadata.tags ?? [],
closeTimestamp: market.marketTimestamps.close,
bestBidPrice: market.data?.bestBidPrice,
bestOfferPrice: market.data?.bestOfferPrice,
markPrice: market.data?.markPrice,
settlementDataOracleId:
market.tradableInstrument.instrument.product
.dataSourceSpecForSettlementData.id,
settlementDataSpecBinding:
market.tradableInstrument.instrument.product.dataSourceSpecBinding
.settlementDataProperty,
tradingTerminationOracleId:
market.tradableInstrument.instrument.product
.dataSourceSpecForTradingTermination.id,
settlementAsset:
market.tradableInstrument.instrument.product.settlementAsset,
realisedPNL: position?.node.realisedPNL,
};
return row;
});
return (
<div className="h-full relative">
<ClosedMarketsDataGrid rowData={rowData} />
<div className="pointer-events-none absolute inset-0">
<AsyncRenderer
loading={loading}
error={error}
data={marketData}
noDataMessage={t('No markets')}
reload={reload}
/>
</div>
</div>
);
};
const ClosedMarketsDataGrid = ({ rowData }: { rowData: Row[] }) => {
const openAssetDialog = useAssetDetailsDialogStore((store) => store.open);
const colDefs = useMemo(() => {
const cols: ColDef[] = [
{
headerName: t('Market'),
field: 'code',
},
{
headerName: t('Description'),
field: 'name',
},
{
headerName: t('Status'),
field: 'state',
valueFormatter: ({ value }: VegaValueFormatterParams<Row, 'state'>) => {
if (!value) return '-';
return MarketStateMapping[value];
},
},
{
headerName: t('Settlement date'),
colId: 'settlementDate', // colId needed if no field property provided otherwise column order is ruined in tests
valueGetter: ({ data }: { data: Row }) => {
return getMarketExpiryDate(data.metadata);
},
cellRenderer: ({ value, data }: { value: Date | null; data: Row }) => {
return (
<SettlementDateCell
oracleSpecId={data.tradingTerminationOracleId}
metaDate={value}
marketState={data.state}
closeTimestamp={data.closeTimestamp}
/>
);
},
cellClassRules: {
'text-danger': ({
value,
data,
}: {
value: Date | null;
data: Row;
}) => {
const date = data.closeTimestamp
? new Date(data.closeTimestamp)
: value;
if (!date) return false;
if (
// expiry has passed and market is not yet settled
isAfter(new Date(), date) &&
data.state !== MarketState.STATE_SETTLED
) {
return true;
}
return false;
},
},
},
{
headerName: t('Best bid'),
field: 'bestBidPrice',
type: 'numericColumn',
cellClass: 'font-mono ag-right-aligned-cell',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'bestBidPrice'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Best offer'),
field: 'bestOfferPrice',
cellClass: 'font-mono ag-right-aligned-cell',
type: 'numericColumn',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'bestOfferPrice'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Mark price'),
field: 'markPrice',
cellClass: 'font-mono ag-right-aligned-cell',
type: 'numericColumn',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'markPrice'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Settlement price'),
type: 'numericColumn',
field: 'settlementDataOracleId',
// 'tradableInstrument.instrument.product.dataSourceSpecForSettlementData.id',
cellRenderer: ({
value,
data,
}: VegaICellRendererParams<Row, 'settlementDataOracleId'>) => (
<SettlementPriceCell
oracleSpecId={value}
decimalPlaces={data?.decimalPlaces ?? 0}
settlementDataSpecBinding={data?.settlementDataSpecBinding}
/>
),
},
{
headerName: t('Realised PNL'),
field: 'realisedPNL',
cellClass: 'font-mono ag-right-aligned-cell',
type: 'numericColumn',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'realisedPNL'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Settlement asset'),
field: 'settlementAsset',
cellRenderer: ({
value,
data,
}: VegaValueFormatterParams<Row, 'settlementAsset'>) => (
<button
className="underline"
onClick={() => {
if (!value) return;
openAssetDialog(value.id);
}}
>
{value ? value.symbol : '-'}
</button>
),
},
{
headerName: t('Market ID'),
field: 'id',
},
];
return cols;
}, [openAssetDialog]);
return (
<AgGrid
style={{ width: '100%', height: '100%' }}
rowData={rowData}
columnDefs={colDefs}
getRowId={({ data }) => data.id}
defaultColDef={{
flex: 1,
resizable: true,
}}
overlayNoRowsTemplate="No data"
/>
);
};
@@ -5,6 +5,7 @@ import { LocalStoragePersistTabs as Tabs, Tab } from '@vegaprotocol/ui-toolkit';
import { Markets } from './markets';
import { Proposed } from './proposed';
import { usePageTitleStore } from '../../stores';
import { Closed } from './closed';
export const MarketsPage = () => {
const { updateTitle } = usePageTitleStore((store) => ({
@@ -21,6 +22,9 @@ export const MarketsPage = () => {
<Tab id="proposed-markets" name={t('Proposed markets')}>
<Proposed />
</Tab>
<Tab id="closed-markets" name={t('Closed markets')}>
<Closed />
</Tab>
</Tabs>
);
};
@@ -12,7 +12,9 @@ export const Proposed = () => {
const externalLink = tokenLink(TOKEN_NEW_MARKET_PROPOSAL);
return (
<>
<ProposalsList />
<div className="min-h-[200px]">
<ProposalsList />
</div>
<ExternalLink className="py-4 px-[11px] text-sm" href={externalLink}>
{t('Propose a new market')}
</ExternalLink>
@@ -0,0 +1,105 @@
import { render, screen } from '@testing-library/react';
import { MarketState } from '@vegaprotocol/types';
import { addDays, subDays } from 'date-fns';
import type { SettlementDataCellProps } from './settlement-date-cell';
import { SettlementDateCell } from './settlement-date-cell';
describe('SettlementDateCell', () => {
let originalNow: typeof Date.now;
const mockNowTimestamp = 1672531200000;
const createProps = (): SettlementDataCellProps => {
return {
oracleSpecId: 'oracle-spec-id',
metaDate: null,
closeTimestamp: null,
marketState: MarketState.STATE_SETTLED,
};
};
beforeAll(() => {
originalNow = Date.now;
Date.now = jest.fn().mockReturnValue(mockNowTimestamp);
});
afterAll(() => {
Date.now = originalNow;
});
it('renders unknown if date cannot be determined', () => {
const props = createProps();
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent('Unknown');
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders using close timestamp if provided', () => {
const daysAgo = 3;
const props = createProps();
props.closeTimestamp = subDays(
new Date(mockNowTimestamp),
daysAgo
).toISOString();
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`${daysAgo} days ago`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders using meta tag date if no close timestamp provided', () => {
const daysAgo = 4;
const props = createProps();
props.metaDate = subDays(new Date(mockNowTimestamp), daysAgo);
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`${daysAgo} days ago`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders past expected settlement date', () => {
const daysAgo = 3;
const props = createProps();
props.metaDate = subDays(new Date(mockNowTimestamp), daysAgo);
props.marketState = MarketState.STATE_TRADING_TERMINATED;
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`Expected ${daysAgo} days ago`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders future expected settlement date', () => {
const daysAgo = 3;
const props = createProps();
props.metaDate = addDays(new Date(mockNowTimestamp), daysAgo);
props.marketState = MarketState.STATE_TRADING_TERMINATED;
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`Expected in ${daysAgo} days`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
});
@@ -0,0 +1,55 @@
import { DApp, EXPLORER_ORACLE, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { MarketState } from '@vegaprotocol/types';
import { Link } from '@vegaprotocol/ui-toolkit';
import { getDateTimeFormat } from '@vegaprotocol/utils';
import { formatDistanceToNowStrict, isAfter } from 'date-fns';
export interface SettlementDataCellProps {
oracleSpecId: string;
metaDate: Date | null;
closeTimestamp: string | null;
marketState: MarketState;
}
export const SettlementDateCell = ({
oracleSpecId,
metaDate,
closeTimestamp,
marketState,
}: SettlementDataCellProps) => {
const linkCreator = useLinks(DApp.Explorer);
const date = closeTimestamp ? new Date(closeTimestamp) : metaDate;
let text = '';
if (!date) {
text = t('Unknown');
} else {
// pass Date.now() to date constructor for easier mocking
const expiryHasPassed = isAfter(new Date(Date.now()), date);
const distance = formatDistanceToNowStrict(date); // X days/mins ago
if (expiryHasPassed) {
if (marketState !== MarketState.STATE_SETTLED) {
text = t('Expected %s ago', distance);
} else {
text = t('%s ago', distance);
}
} else {
text = t('Expected in %s', distance);
}
}
return (
<Link
href={linkCreator(EXPLORER_ORACLE.replace(':id', oracleSpecId))}
className="underline"
target="_blank"
title={
date ? getDateTimeFormat().format(date) : t('Unknown settlement date')
}
>
{text}
</Link>
);
};
@@ -0,0 +1,113 @@
import { render, screen } from '@testing-library/react';
import type { Property } from '@vegaprotocol/types';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { OracleSpecDataConnectionQuery } from '@vegaprotocol/oracles';
import { OracleSpecDataConnectionDocument } from '@vegaprotocol/oracles';
import type { SettlementPriceCellProps } from './settlement-price-cell';
import { SettlementPriceCell } from './settlement-price-cell';
describe('SettlementPriceCell', () => {
const createMock = (
id: string,
property: Property
): MockedResponse<OracleSpecDataConnectionQuery> => {
return {
request: {
query: OracleSpecDataConnectionDocument,
variables: {
oracleSpecId: id,
},
},
result: {
data: {
oracleSpec: {
dataConnection: {
edges: [
{
node: {
externalData: {
data: {
data: [property],
},
},
},
},
],
},
},
},
},
};
};
const createProps = (): SettlementPriceCellProps => {
return {
oracleSpecId: 'oracle-spec-id',
decimalPlaces: 2,
settlementDataSpecBinding: 'settlement-data-spec-binding',
};
};
it('renders fetches and renders the settlment data value', async () => {
const props = createProps();
const property = {
__typename: 'Property' as const,
name: props.settlementDataSpecBinding as string,
value: '1234',
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const mock = createMock(props.oracleSpecId!, property);
render(
<MockedProvider mocks={[mock]}>
<SettlementPriceCell {...props} />
</MockedProvider>
);
expect(screen.getByText('-')).toBeInTheDocument();
const link = await screen.findByRole('link');
expect(link).toHaveTextContent('12.34');
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders "-" if no spec value is found', async () => {
const props = createProps();
const property = {
__typename: 'Property' as const,
name: 'no matching spec binding',
value: '1234',
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const mock = createMock(props.oracleSpecId!, property);
render(
<MockedProvider mocks={[mock]}>
<SettlementPriceCell {...props} />
</MockedProvider>
);
expect(screen.getByText('-')).toBeInTheDocument();
const link = await screen.findByRole('link');
expect(link).toHaveTextContent('-');
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders "-" with no link if oracle spec id is not provided', () => {
const props = createProps();
props.oracleSpecId = undefined;
render(
<MockedProvider mocks={[]}>
<SettlementPriceCell {...props} />
</MockedProvider>
);
expect(screen.getByText('-')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,39 @@
import { DApp, EXPLORER_ORACLE, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { useOracleSpecBindingData } from '@vegaprotocol/oracles';
import { Link } from '@vegaprotocol/ui-toolkit';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
export interface SettlementPriceCellProps {
oracleSpecId: string | undefined;
decimalPlaces: number;
settlementDataSpecBinding: string | undefined;
}
export const SettlementPriceCell = ({
oracleSpecId,
decimalPlaces,
settlementDataSpecBinding,
}: SettlementPriceCellProps) => {
const linkCreator = useLinks(DApp.Explorer);
const { property, loading } = useOracleSpecBindingData(
oracleSpecId,
settlementDataSpecBinding
);
if (!oracleSpecId || loading) {
return <span>-</span>;
}
return (
<Link
href={linkCreator(EXPLORER_ORACLE.replace(':id', oracleSpecId))}
className="underline font-mono"
target="_blank"
>
{property
? addDecimalsFormatNumber(property.value, decimalPlaces)
: t('-')}
</Link>
);
};
@@ -7,6 +7,7 @@ import { WithdrawalsContainer } from './withdrawals-container';
import { FillsContainer } from '@vegaprotocol/fills';
import type { ReactNode } from 'react';
import { useEffect } from 'react';
import { usePaneLayout } from '@vegaprotocol/react-helpers';
import { VegaWalletContainer } from '../../components/vega-wallet-container';
import { DepositsContainer } from './deposits-container';
import { LayoutPriority } from 'allotment';
@@ -34,11 +35,11 @@ export const Portfolio = () => {
const onMarketClick = useMarketClickHandler(true);
const onOrderTypeClick = useMarketLiquidityClickHandler(true);
const [sizes, handleOnLayoutChange] = usePaneLayout({ id: 'portfolio' });
const wrapperClasses = 'h-full max-h-full flex flex-col';
return (
<div className={wrapperClasses}>
<ResizableGrid vertical>
<ResizableGrid vertical onChange={handleOnLayoutChange}>
<ResizableGridPanel minSize={75}>
<PortfolioGridChild>
<Tabs storageKey="console-portfolio-top">
@@ -79,7 +80,7 @@ export const Portfolio = () => {
</ResizableGridPanel>
<ResizableGridPanel
priority={LayoutPriority.Low}
preferredSize={300}
preferredSize={sizes[1] || 300}
minSize={50}
>
<PortfolioGridChild>
@@ -36,7 +36,11 @@ export const Settings = () => {
/>
</div>
<Divider />
<TelemetryApproval isSettingsPage />
<TelemetryApproval
helpText={t(
'Help identify bugs and improve the service by sharing anonymous usage data.'
)}
/>
</RoundedWrapper>
</div>
</div>
+1 -1
View File
@@ -1,6 +1,6 @@
import { t } from '@vegaprotocol/i18n';
export const THROTTLE_UPDATE_TIME = 500;
export const RISK_ACCEPTED_KEY = 'vega-risk-accepted';
export const RISK_ACCEPTED_KEY = 'vega_risk_accepted';
export const MAINNET_WELCOME_HEADER = t(
'Trade cash settled futures on the fully decentralised Vega network.'
);
@@ -39,7 +39,17 @@ const MARKET_A: PartialMarket = {
symbol: 'ABC',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
@@ -115,7 +125,17 @@ const MARKET_B: PartialMarket = {
symbol: 'XYZ',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
@@ -1,9 +1,6 @@
import { BrowserRouter } from 'react-router-dom';
import { render, screen, fireEvent } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing';
import { Networks, useEnvironment } from '@vegaprotocol/environment';
import { RiskNoticeDialog } from './risk-notice-dialog';
import { WelcomeDialog } from './welcome-dialog';
jest.mock('@vegaprotocol/environment');
@@ -14,7 +11,6 @@ const mockEnvDefinitions = {
};
describe('Risk notice dialog', () => {
const introText = 'Regulation may apply to use of this app';
const mockOnClose = jest.fn();
afterEach(() => {
jest.clearAllMocks();
@@ -22,13 +18,12 @@ describe('Risk notice dialog', () => {
it.each`
assertion | network
${'displays'} | ${Networks.MAINNET}
${'displays'} | ${Networks.CUSTOM}
${'displays'} | ${Networks.DEVNET}
${'displays'} | ${Networks.STAGNET3}
${'displays'} | ${Networks.TESTNET}
`(
'$assertion the risk notice on $network',
'$assertion a generic message on $network',
async ({ assertion, network }) => {
// @ts-ignore ignore mock implementation
useEnvironment.mockImplementation(() => ({
@@ -36,27 +31,37 @@ describe('Risk notice dialog', () => {
VEGA_ENV: network,
}));
render(
<MockedProvider>
<WelcomeDialog />
</MockedProvider>,
{ wrapper: BrowserRouter }
);
render(<RiskNoticeDialog onClose={mockOnClose} network={network} />);
expect(screen.queryByText(introText)).toBeInTheDocument();
expect(
screen.getByText(
new RegExp(
`This application for trading on Vega is connected to ${network}`
)
)
).toBeInTheDocument();
const button = screen.getByRole('button', {
name: 'Continue',
});
fireEvent.click(button);
expect(mockOnClose).toHaveBeenCalled();
}
);
it("doesn't display the risk notice when previously acknowledged", () => {
it('displays a risk message for mainnet', () => {
const introText = 'Regulation may apply to use of this app';
const network = Networks.MAINNET;
// @ts-ignore ignore mock implementation
useEnvironment.mockImplementation(() => ({
...mockEnvDefinitions,
VEGA_ENV: Networks.MAINNET,
VEGA_ENV: network,
}));
render(<RiskNoticeDialog onClose={mockOnClose} />);
render(<RiskNoticeDialog onClose={mockOnClose} network={network} />);
expect(screen.queryByText(introText)).toBeInTheDocument();
expect(screen.getByText(introText)).toBeInTheDocument();
const button = screen.getByRole('button', {
name: 'I understand, Continue',
@@ -1,25 +1,100 @@
import { useCallback } from 'react';
import { t } from '@vegaprotocol/i18n';
import { Button } from '@vegaprotocol/ui-toolkit';
import { LocalStorage } from '@vegaprotocol/utils';
import {
Button,
Link,
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { RISK_ACCEPTED_KEY } from '../constants';
import { TelemetryApproval } from './telemetry-approval';
import { Networks, useEnvironment } from '@vegaprotocol/environment';
import { useLocalStorage } from '@vegaprotocol/react-helpers';
interface Props {
onClose: () => void;
network: Networks;
}
export const RiskNoticeDialog = ({ onClose }: Props) => {
const handleAcceptRisk = useCallback(() => {
onClose();
LocalStorage.setItem(RISK_ACCEPTED_KEY, 'true');
}, [onClose]);
export const RiskNoticeDialog = ({ onClose, network }: Props) => {
const [, setValue] = useLocalStorage(RISK_ACCEPTED_KEY);
const handleAcceptRisk = () => {
onClose();
setValue('true');
};
return (
<>
{network === Networks.MAINNET ? (
<MainnetContent />
) : (
<TestnetContent network={network} />
)}
<div className="my-4">
<TelemetryApproval
helpText={t(
'Help identify bugs and improve the service by sharing anonymous usage data. You can change this in your settings at any time.'
)}
/>
</div>
<Button onClick={handleAcceptRisk}>
{network === Networks.MAINNET
? t('I understand, Continue')
: t('Continue')}
</Button>
</>
);
};
const TestnetContent = ({ network }: { network: Networks }) => {
const { VEGA_DOCS_URL, GITHUB_FEEDBACK_URL, VEGA_WALLET_URL } =
useEnvironment();
return (
<>
<p className="mb-4">
{t(
'This application for trading on Vega is connected to %s, meaning you are free to try out trading with virtual assets and no risk.',
[network]
)}
</p>
<p className="mb-4">
{t(
'Your Vega wallet must also be connected to %s, and your Ethereum wallet must be connected to Sepolia.',
[network]
)}
</p>
{VEGA_DOCS_URL && GITHUB_FEEDBACK_URL && VEGA_WALLET_URL && (
<ul className="list-disc pl-4">
<li className="mb-1">
<Link href={VEGA_WALLET_URL} target="_blank">
<span className="underline">{t('Learn about Vega wallet')}</span>{' '}
<VegaIcon name={VegaIconNames.OPEN_EXTERNAL} />
</Link>
</li>
<li className="mb-1">
<Link href={VEGA_DOCS_URL} target="_blank">
<span className="underline">{t('View documentation')}</span>{' '}
<VegaIcon name={VegaIconNames.OPEN_EXTERNAL} />
</Link>
</li>
<li className="mb-1">
<Link href={GITHUB_FEEDBACK_URL} target="_blank">
<span className="underline">{t('Provide feedback')}</span>{' '}
<VegaIcon name={VegaIconNames.OPEN_EXTERNAL} />
</Link>
</li>
</ul>
)}
</>
);
};
const MainnetContent = () => {
return (
<>
<h4 className="text-xl mb-2 mt-4">
{t('Regulation may apply to use of this app')}
</h4>
<p className="text-base mb-6">
<p className="mb-6">
{t(
'This decentralised application allows you to connect to and use publicly available blockchain services operated by third parties that may include trading, financial products, or other services that may be subject to legal and regulatory restrictions in your jurisdiction. This application is a front end only and does not hold any funds or provide any products or services. It is available to anyone with an internet connection via IPFS and other methods, and the ability to access it does not imply any right to use any services or that it is legal for you to do so. By using this application you accept that it is your responsibility to ensure that your use of the application and any blockchain services accessed through it is compliant with applicable laws and regulations in your jusrisdiction.'
)}
@@ -27,15 +102,11 @@ export const RiskNoticeDialog = ({ onClose }: Props) => {
<h4 className="text-xl mb-2">
{t('Technical and financial risk of loss')}
</h4>
<p className="text-base mb-8">
<p className="mb-8">
{t(
'The public blockchain services accessible via this decentralised application are operated by third parties and may carry significant risks including the potential loss of all funds that you deposit or hold with these services. Technical risks include the risk of loss in the event of the failure or compromise of the public blockchain infrastructure or smart contracts that provide any services you use. Financial risks include but are not limited to losses due to volatility, excessive leverage, low liquidity, and your own lack of understanding of the services you use. By using this decentralised application you accept that it is your responsibility to ensure that you understand any services you use and the technical and financial risks inherent in your use. Do not risk what you cannot afford to lose.'
)}
</p>
<Button onClick={handleAcceptRisk}>{t('I understand, Continue')}</Button>
<div className="text-base mt-8">
<TelemetryApproval />
</div>
</>
);
};
@@ -3,7 +3,8 @@ import { TelemetryApproval } from './telemetry-approval';
describe('TelemetryApproval', () => {
it('click on checkbox should be properly handled', () => {
render(<TelemetryApproval />);
const helpText = 'My help text';
render(<TelemetryApproval helpText={helpText} />);
expect(screen.getByRole('checkbox')).toHaveAttribute(
'data-state',
'unchecked'
@@ -15,5 +16,7 @@ describe('TelemetryApproval', () => {
'data-state',
'checked'
);
expect(screen.getByText('Share usage data')).toBeInTheDocument();
expect(screen.getByText(helpText)).toBeInTheDocument();
});
});
@@ -2,11 +2,7 @@ import { Checkbox } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
import { useTelemetryApproval } from '../../lib/hooks/use-telemetry-approval';
export const TelemetryApproval = ({
isSettingsPage,
}: {
isSettingsPage?: boolean;
}) => {
export const TelemetryApproval = ({ helpText }: { helpText: string }) => {
const [isApproved, setIsApproved] = useTelemetryApproval();
return (
<div className="flex flex-col px-2 py-3">
@@ -19,13 +15,7 @@ export const TelemetryApproval = ({
/>
</div>
<div className="text-sm text-vega-light-300 dark:text-vega-dark-300 ml-6">
<span>
{t(
'Help identify bugs and improve the service by sharing anonymous usage data.'
)}
{!isSettingsPage &&
' ' + t('You can change this in your settings at any time.')}
</span>
<span>{helpText}</span>
</div>
</div>
);
@@ -9,8 +9,11 @@ import { RiskNoticeDialog } from './risk-notice-dialog';
import { WelcomeNoticeDialog } from './welcome-notice-dialog';
import { WelcomeLandingDialog } from './welcome-landing-dialog';
import { useGlobalStore } from '../../stores';
import { useEnvironment } from '@vegaprotocol/environment';
import { Networks } from '@vegaprotocol/environment';
export const WelcomeDialog = () => {
const { VEGA_ENV } = useEnvironment();
const { pathname } = useLocation();
let dialogContent: React.ReactNode;
let title = '';
@@ -33,8 +36,10 @@ export const WelcomeDialog = () => {
}, [update, isRiskDialogNeeded]);
if (isRiskDialogNeeded) {
dialogContent = <RiskNoticeDialog onClose={onCloseDialog} />;
title = t('WARNING');
dialogContent = (
<RiskNoticeDialog onClose={onCloseDialog} network={VEGA_ENV} />
);
title = VEGA_ENV === Networks.MAINNET ? t('WARNING') : t('Vega Console');
size = 'medium';
} else if (isWelcomeDialogNeeded && data?.length === 0) {
dialogContent = <WelcomeNoticeDialog />;
@@ -41,7 +41,17 @@ const MARKET_A: PartialMarket = {
symbol: 'ABC',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
@@ -117,7 +127,17 @@ const MARKET_B: PartialMarket = {
symbol: 'XYZ',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
+46 -1
View File
@@ -1,3 +1,7 @@
@import 'ag-grid-community/dist/styles/ag-grid.css';
@import 'ag-grid-community/dist/styles/ag-theme-balham.css';
@import 'ag-grid-community/dist/styles/ag-theme-balham-dark.css';
@tailwind base;
@tailwind components;
@tailwind utilities;
@@ -24,7 +28,8 @@ html.dark {
@apply border-vega-light-200 dark:border-vega-dark-200;
}
/* Styles for charts */
/* PENNANT */
html [data-theme='dark'] {
--pennant-color-danger: theme('colors.vega.pink.DEFAULT');
@@ -71,3 +76,43 @@ html [data-theme='light'] {
--pennant-color-depth-sell-fill: theme('colors.vega.pink.400');
--pennant-color-depth-sell-stroke: theme('colors.vega.pink.550');
}
/* AG GRID - Do not edit without updating other global stylesheets for each app */
.vega-ag-grid .ag-root-wrapper {
border: solid 0px;
}
.vega-ag-grid .ag-react-container {
overflow: hidden;
text-overflow: ellipsis;
}
.vega-ag-grid .ag-cell,
.vega-ag-grid .ag-full-width-row .ag-cell-wrapper.ag-row-group {
line-height: calc(min(var(--ag-line-height, 26px), 26px) - 4px);
}
/* Light variables */
.ag-theme-balham {
--ag-background-color: theme(colors.white);
--ag-border-color: theme(colors.neutral[300]);
--ag-header-background-color: theme(colors.white);
--ag-odd-row-background-color: theme(colors.white);
--ag-header-column-separator-color: theme(colors.neutral[300]);
--ag-row-border-color: theme(colors.white);
--ag-row-hover-color: theme(colors.neutral[100]);
--ag-font-size: 12px;
}
/* Dark variables */
.ag-theme-balham-dark {
--ag-background-color: theme(colors.black);
--ag-border-color: theme(colors.neutral[700]);
--ag-header-background-color: theme(colors.black);
--ag-odd-row-background-color: theme(colors.black);
--ag-header-column-separator-color: theme(colors.neutral[600]);
--ag-row-border-color: theme(colors.black);
--ag-row-hover-color: theme(colors.neutral[800]);
--ag-font-size: 12px;
}
@@ -23,7 +23,7 @@ describe('AccountManager', () => {
data: [],
};
})
.mockImplementationOnce((args) => {
.mockImplementation((args) => {
return {
data: [
{ asset: { id: 'a1' }, party: { id: 't1' } },
@@ -49,7 +49,7 @@ describe('AccountManager', () => {
(helpers.useDataProvider as jest.Mock).mock.calls[0][0].variables
.partyId
).toEqual('partyOne');
await act(() => {
await act(async () => {
rerender(
<AccountManager
partyId="partyTwo"
@@ -66,7 +66,7 @@ describe('AccountManager', () => {
it('update method should return proper result', async () => {
let rerenderer: (ui: React.ReactElement) => void;
await act(() => {
await act(async () => {
const { rerender } = render(
<AccountManager
partyId="partyOne"
@@ -79,7 +79,7 @@ describe('AccountManager', () => {
await waitFor(() => {
expect(screen.getByText('No accounts')).toBeInTheDocument();
});
await act(() => {
await act(async () => {
rerenderer(
<AccountManager
partyId="partyOne"
+1 -1
View File
@@ -22,7 +22,7 @@ import {
} from '@vegaprotocol/ui-toolkit';
import { TooltipCellComponent } from '@vegaprotocol/ui-toolkit';
import {
AgGridDynamic as AgGrid,
AgGridLazy as AgGrid,
CenteredGridCellWrapper,
} from '@vegaprotocol/datagrid';
import { AgGridColumn } from 'ag-grid-react';
+1 -1
View File
@@ -11,7 +11,7 @@ import type {
VegaValueFormatterParams,
} from '@vegaprotocol/datagrid';
import { progressBarCellRendererSelector } from '@vegaprotocol/datagrid';
import { AgGridDynamic as AgGrid, PriceCell } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid, PriceCell } from '@vegaprotocol/datagrid';
import type { ValueFormatterParams } from 'ag-grid-community';
import { accountValuesComparator } from './accounts-table';
+1
View File
@@ -17,6 +17,7 @@ export * from '../market-list/src/lib/market-data.mock';
export * from '../market-list/src/lib/markets-candles.mock';
export * from '../market-list/src/lib/markets-data.mock';
export * from '../market-list/src/lib/markets.mock';
export * from '../oracles/src/lib/oracle-spec-data-connection.mock';
export * from '../orders/src/lib/components/order-data-provider/orders.mock';
export * from '../positions/src/lib/positions.mock';
export * from '../react-helpers/src/hooks/network-params.mock';
-1
View File
@@ -1,4 +1,3 @@
export * from './lib/ag-grid/ag-grid-dynamic';
export * from './lib/ag-grid/ag-grid-lazy';
export * from './lib/ag-grid/use-column-sizes';
@@ -1,50 +0,0 @@
import type { ReactNode } from 'react';
import colors from 'tailwindcss/colors';
import 'ag-grid-community/dist/styles/ag-theme-balham-dark.css';
const agGridDarkVariables = `
.ag-theme-balham-dark {
--ag-background-color: ${colors.black};
--ag-border-color: ${colors.neutral[700]};
--ag-header-background-color: ${colors.black};
--ag-odd-row-background-color: ${colors.black};
--ag-header-column-separator-color: ${colors.neutral[600]};
--ag-row-border-color:${colors.black};
--ag-row-hover-color: ${colors.neutral[800]};
--ag-font-size: 12px;
}
.ag-theme-balham-dark .ag-root-wrapper {
border: 0;
}
.ag-theme-balham-dark .ag-row {
border-width: 1px 0;
border-bottom: 1px solid transparent;
}
.ag-theme-balham-dark .ag-row.no-hover, .ag-theme-balham-dark .ag-row.no-hover:hover {
background: black;
}
.ag-theme-balham-dark .ag-react-container {
overflow: hidden;
text-overflow: ellipsis;
}
.ag-theme-balham-dark .ag-cell, .ag-theme-balham-dark .ag-full-width-row .ag-cell-wrapper.ag-row-group {
line-height: calc(min(var(--ag-line-height, 26px), 26px) - 4px);
}
`;
export const AgGrid = ({
children,
customThemeParams,
}: {
children: ReactNode;
customThemeParams?: string;
}) => (
<>
<style>{agGridDarkVariables}</style>
{customThemeParams && <style>{customThemeParams}</style>}
{children}
</>
);
@@ -1,99 +0,0 @@
import React, { useCallback, useRef } from 'react';
import type {
ReactElement,
ReactNode,
FunctionComponent,
CSSProperties,
} from 'react';
import dynamic from 'next/dynamic';
import type { AgGridReactProps, AgReactUiProps } from 'ag-grid-react';
import type { ColumnResizedEvent } from 'ag-grid-community';
import { AgGridReact } from 'ag-grid-react';
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
import { useColumnSizes } from './use-column-sizes';
import 'ag-grid-community/dist/styles/ag-grid.css';
interface GridProps {
children: ReactNode;
customThemeParams?: string | undefined;
}
const AgGridLightTheme = dynamic<GridProps>(
() => import('./ag-grid-light').then((mod) => mod.AgGrid),
{ ssr: false }
) as FunctionComponent<GridProps>;
const AgGridDarkTheme = dynamic<GridProps>(
() => import('./ag-grid-dark').then((mod) => mod.AgGrid),
{ ssr: false }
) as FunctionComponent<GridProps>;
export const AgGridThemed = ({
id,
style,
className,
gridRef,
customThemeParams,
children,
...props
}: (AgGridReactProps | AgReactUiProps) & {
style?: CSSProperties;
className?: string;
gridRef?: React.ForwardedRef<AgGridReact>;
customThemeParams?: string;
id?: string;
children?: ReactNode[];
}) => {
const containerRef = useRef<HTMLDivElement | null>(null);
const { theme } = useThemeSwitcher();
const [sizes, setValues] = useColumnSizes({ id, container: containerRef });
const defaultProps = {
rowHeight: 22,
headerHeight: 22,
enableCellTextSelection: true,
onColumnResized: useCallback(
(event: ColumnResizedEvent) => {
if (event.source === 'uiColumnDragged' && event.columns) {
setValues(event.columns);
}
},
[setValues]
),
};
const sizedChildren = children.map((child: ReactElement) => {
return {
...child,
props: {
...(child?.props ?? {}),
width: sizes[child?.props.field],
headerName:
(child?.props.headerName || ' - ') +
' ' +
(sizes[child?.props.field] || 'unk'),
},
};
});
return (
<div
className={`${className ?? ''} ${
theme === 'dark' ? 'ag-theme-balham-dark' : 'ag-theme-balham'
}`}
style={style}
ref={containerRef}
>
{theme === 'dark' ? (
<AgGridDarkTheme customThemeParams={customThemeParams}>
<AgGridReact {...defaultProps} {...props} ref={gridRef}>
{sizedChildren}
</AgGridReact>
</AgGridDarkTheme>
) : (
<AgGridLightTheme customThemeParams={customThemeParams}>
<AgGridReact {...defaultProps} {...props} ref={gridRef}>
{sizedChildren}
</AgGridReact>
</AgGridLightTheme>
)}
</div>
);
};
@@ -1,30 +0,0 @@
import * as React from 'react';
import dynamic from 'next/dynamic';
import type {
AgGridReactProps,
AgReactUiProps,
AgGridReact,
} from 'ag-grid-react';
type Props = (AgGridReactProps | AgReactUiProps) & {
style?: React.CSSProperties;
className?: string;
gridRef?: React.Ref<AgGridReact>;
customThemeParams?: string;
id?: string;
};
// https://stackoverflow.com/questions/69433673/nextjs-reactdomserver-does-not-yet-support-suspense
const AgGridDynamicInternal = dynamic<Props>(
() => import('./ag-grid-dynamic-themed').then((mod) => mod.AgGridThemed),
{
ssr: false,
// https://nextjs.org/docs/messages/invalid-dynamic-suspense
// suspense: true
}
);
export const AgGridDynamic = React.forwardRef<AgGridReact, Props>(
(props, ref) => <AgGridDynamicInternal {...props} gridRef={ref} />
);
@@ -1,45 +1,54 @@
import * as React from 'react';
import type { AgGridReactProps, AgReactUiProps } from 'ag-grid-react';
import { AgGridReact } from 'ag-grid-react';
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
import 'ag-grid-community/dist/styles/ag-grid.css';
import classNames from 'classnames';
const AgGridLightTheme = React.lazy(() =>
import('./ag-grid-light').then((module) => ({
default: module.AgGrid,
}))
);
const AgGridDarkTheme = React.lazy(() =>
import('./ag-grid-dark').then((module) => ({
default: module.AgGrid,
}))
);
export const AgGridThemed = React.forwardRef<
AgGridReact,
(AgGridReactProps | AgReactUiProps) & {
style?: React.CSSProperties;
className?: string;
}
>(({ style, className, ...props }, ref) => {
export const AgGridThemed = ({
style,
gridRef,
id,
children,
...props
}: (AgGridReactProps | AgReactUiProps) & {
style?: React.CSSProperties;
gridRef?: React.ForwardedRef<AgGridReact>;
id?: string;
children?: ReactNode[];
}) => {
const containerRef = useRef<HTMLDivElement | null>(null);
const [sizes, setValues] = useColumnSizes({ id, container: containerRef });
const { theme } = useThemeSwitcher();
const defaultProps = {
rowHeight: 22,
headerHeight: 22,
enableCellTextSelection: true,
onColumnResized: useCallback(
(event: ColumnResizedEvent) => {
if (event.source === 'uiColumnDragged' && event.columns) {
setValues(event.columns);
}
},
[setValues]
),
};
const sizedChildren = children.map((child: ReactElement) => {
return {
...child,
props: {
...(child?.props ?? {}),
width: sizes[child?.props.field],
},
};
});
const wrapperClasses = classNames('vega-ag-grid', {
'ag-theme-balham': theme === 'light',
'ag-theme-balham-dark': theme === 'dark',
});
return (
<div
className={`${className ?? ''} ${
theme === 'dark' ? 'ag-theme-balham-dark' : 'ag-theme-balham'
}`}
style={style}
>
{theme === 'dark' ? (
<AgGridDarkTheme>
<AgGridReact {...props} ref={ref} enableCellTextSelection={true} />
</AgGridDarkTheme>
) : (
<AgGridLightTheme>
<AgGridReact {...props} ref={ref} enableCellTextSelection={true} />
</AgGridLightTheme>
)}
<div className={wrapperClasses} style={style} ref={containerRef}>
<AgGridReact {...defaultProps} {...props} ref={gridRef}>
{sizedChildren}
</AgGridReact>
</div>
);
});
};
+11 -5
View File
@@ -1,12 +1,18 @@
import * as React from 'react';
import type { AgGridReact } from 'ag-grid-react';
import { forwardRef, lazy } from 'react';
import type { AgGridReactProps, AgGridReact } from 'ag-grid-react';
export const AgGridLazyInternal = React.lazy(() =>
type Props = AgGridReactProps & {
style?: React.CSSProperties;
gridRef?: React.Ref<AgGridReact>;
id?: string;
};
export const AgGridLazyInternal = lazy(() =>
import('./ag-grid-lazy-themed').then((module) => ({
default: module.AgGridThemed,
}))
);
export const AgGridLazy = React.forwardRef<AgGridReact>((props, ref) => (
<AgGridLazyInternal {...props} ref={ref} />
export const AgGridLazy = forwardRef<AgGridReact, Props>((props, ref) => (
<AgGridLazyInternal {...props} gridRef={ref} />
));
@@ -1,50 +0,0 @@
import type { ReactNode } from 'react';
import colors from 'tailwindcss/colors';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';
const agGridLightVariables = `
.ag-theme-balham {
--ag-background-color: ${colors.white};
--ag-border-color: ${colors.neutral[300]};
--ag-header-background-color: ${colors.white};
--ag-odd-row-background-color: ${colors.white};
--ag-header-column-separator-color: ${colors.neutral[300]};
--ag-row-border-color: ${colors.white};
--ag-row-hover-color: ${colors.neutral[100]};
--ag-font-size: 12px;
}
.ag-theme-balham .ag-root-wrapper {
border: 0;
}
.ag-theme-balham .ag-row {
border-width: 1px 0;
border-bottom: 1px solid transparent;
}
.ag-theme-balham .ag-row.no-hover, .ag-theme-balham .ag-row.no-hover:hover {
background: white;
}
.ag-theme-balham .ag-react-container {
overflow: hidden;
text-overflow: ellipsis;
}
.ag-theme-balham .ag-cell, .ag-theme-balham .ag-full-width-row .ag-cell-wrapper.ag-row-group {
line-height: calc(min(var(--ag-line-height, 26px), 26px) - 4px);
}
`;
export const AgGrid = ({
children,
customThemeParams,
}: {
children: ReactNode;
customThemeParams?: string;
}) => (
<>
<style>{agGridLightVariables}</style>
{customThemeParams && <style>{customThemeParams}</style>}
{children}
</>
);
+11 -1
View File
@@ -35,7 +35,17 @@ export function generateMarket(override?: PartialDeep<Market>): Market {
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
quoteName: 'BTC',
__typename: 'Future',
+1 -1
View File
@@ -8,7 +8,7 @@ import {
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import type { AgGridReact } from 'ag-grid-react';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import type {
VegaICellRendererParams,
VegaValueFormatterParams,
+1
View File
@@ -100,6 +100,7 @@ export const TOKEN_VALIDATOR = '/validators/:id';
// Explorer pages
export const EXPLORER_TX = '/txs/:hash';
export const EXPLORER_ORACLE = '/oracles/:id';
// Etherscan pages
export const ETHERSCAN_ADDRESS = '/address/:hash';
+1 -1
View File
@@ -15,7 +15,7 @@ import { t } from '@vegaprotocol/i18n';
import * as Schema from '@vegaprotocol/types';
import { AgGridColumn } from 'ag-grid-react';
import {
AgGridDynamic as AgGrid,
AgGridLazy as AgGrid,
positiveClassNames,
negativeClassNames,
MarketNameCell,
+11 -1
View File
@@ -78,7 +78,17 @@ export const generateFill = (override?: PartialDeep<Trade>) => {
},
quoteName: '',
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
},
+1 -1
View File
@@ -10,7 +10,7 @@ import type {
TypedDataAgGrid,
} from '@vegaprotocol/datagrid';
import {
AgGridDynamic as AgGrid,
AgGridLazy as AgGrid,
DateRangeFilter,
SetFilter,
} from '@vegaprotocol/datagrid';
+1 -1
View File
@@ -9,7 +9,7 @@ import type {
VegaValueFormatterParams,
TypedDataAgGrid,
} from '@vegaprotocol/datagrid';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid';
import { TooltipCellComponent } from '@vegaprotocol/ui-toolkit';
import type { AgGridReact } from 'ag-grid-react';
import { AgGridColumn } from 'ag-grid-react';
@@ -198,4 +198,4 @@ export function useMarketInfoLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions
}
export type MarketInfoQueryHookResult = ReturnType<typeof useMarketInfoQuery>;
export type MarketInfoLazyQueryHookResult = ReturnType<typeof useMarketInfoLazyQuery>;
export type MarketInfoQueryResult = Apollo.QueryResult<MarketInfoQuery, MarketInfoQueryVariables>;
export type MarketInfoQueryResult = Apollo.QueryResult<MarketInfoQuery, MarketInfoQueryVariables>;
@@ -103,6 +103,7 @@ const MarketInfoAccordion = ({
content: <InsurancePoolInfoPanel market={market} account={a} />,
})),
];
const product = market.tradableInstrument.instrument.product;
const marketSpecPanels = [
{
@@ -113,9 +114,13 @@ const MarketInfoAccordion = ({
title: t('Instrument'),
content: <InstrumentInfoPanel market={market} />,
},
{
title: t('Oracle'),
content: <OracleInfoPanel market={market} />,
product.dataSourceSpecForSettlementData && {
title: t('Settlement Oracle'),
content: <OracleInfoPanel market={market} type="settlementData" />,
},
product.dataSourceSpecForTradingTermination && {
title: t('Termination Oracle'),
content: <OracleInfoPanel market={market} type="termination" />,
},
{
title: t('Settlement asset'),
@@ -26,7 +26,7 @@ import { ConditionOperatorMapping } from '@vegaprotocol/types';
import { MarketTradingModeMapping } from '@vegaprotocol/types';
import { useEnvironment } from '@vegaprotocol/environment';
import type { Provider } from '@vegaprotocol/oracles';
import { useOracleProofs } from '@vegaprotocol/oracles';
import { OracleBasicProfile, useOracleProofs } from '@vegaprotocol/oracles';
import { useDataProvider } from '@vegaprotocol/react-helpers';
type PanelProps = Pick<
@@ -449,49 +449,38 @@ export const LiquidityPriceRangeInfoPanel = ({
export const OracleInfoPanel = ({
market,
...props
}: MarketInfoProps & PanelProps) => {
type,
}: MarketInfoProps &
PanelProps & { type: 'settlementData' | 'termination' }) => {
const product = market.tradableInstrument.instrument.product;
const { VEGA_EXPLORER_URL, ORACLE_PROOFS_URL } = useEnvironment();
const { data } = useOracleProofs(ORACLE_PROOFS_URL);
return (
<MarketInfoTable
data={{
settlementDataProperty:
product.dataSourceSpecBinding.settlementDataProperty,
tradingTerminationProperty:
product.dataSourceSpecBinding.tradingTerminationProperty,
}}
{...props}
>
<div
className="flex flex-col gap-2 mt-4"
<div className="flex flex-col gap-4">
<DataSourceProof
data-testid="oracle-proof-links"
data={
type === 'settlementData'
? product.dataSourceSpecForSettlementData.data
: product.dataSourceSpecForTradingTermination.data
}
providers={data}
type={type}
/>
<ExternalLink
data-testid="oracle-spec-links"
href={`${VEGA_EXPLORER_URL}/oracles/${
type === 'settlementData'
? product.dataSourceSpecForSettlementData.id
: product.dataSourceSpecForTradingTermination.id
}`}
>
<DataSourceProof
data={product.dataSourceSpecForSettlementData.data}
providers={data}
type="settlementData"
/>
<DataSourceProof
data={product.dataSourceSpecForTradingTermination.data}
providers={data}
type="termination"
/>
</div>
<div className="flex flex-col gap-2" data-testid="oracle-spec-links">
<ExternalLink
href={`${VEGA_EXPLORER_URL}/oracles#${product.dataSourceSpecForSettlementData.id}`}
>
{t('View settlement data specification')}
</ExternalLink>
<ExternalLink
href={`${VEGA_EXPLORER_URL}/oracles#${product.dataSourceSpecForTradingTermination.id}`}
>
{t('View termination specification')}
</ExternalLink>
</div>
</MarketInfoTable>
{type === 'settlementData'
? t('View settlement data specification')
: t('View termination specification')}
</ExternalLink>
</div>
);
};
@@ -551,20 +540,13 @@ const OracleLink = ({
providers,
signer,
type,
index,
}: {
providers: Provider[];
signer: SignerKind;
type: 'settlementData' | 'termination';
index: number;
}) => {
const text =
type === 'settlementData'
? t('View settlement oracle details')
: t('View termination oracle details');
const textWithCount = index > 0 ? `${text} (${index + 1})` : text;
const provider = providers.find((p) => {
const signerProviders = providers.filter((p) => {
if (signer.__typename === 'PubKey') {
if (
p.oracle.type === 'public_key' &&
@@ -586,14 +568,19 @@ const OracleLink = ({
return false;
});
if (!provider) {
if (!signerProviders.length) {
return <NoOracleProof type={type} />;
}
return (
<p>
<ExternalLink href={provider.github_link}>{textWithCount}</ExternalLink>
</p>
<div>
{signerProviders.map((provider) => (
<OracleBasicProfile
key={provider.name}
provider={provider}
></OracleBasicProfile>
))}
</div>
);
};
+9 -2
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 MarketFieldsFragment = { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } };
export type MarketFieldsFragment = { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecForSettlementData: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecBinding: { __typename?: 'DataSourceSpecToFutureBinding', settlementDataProperty: string, tradingTerminationProperty: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } };
export type MarketsQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type MarketsQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } } }> } | null };
export type MarketsQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecForSettlementData: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecBinding: { __typename?: 'DataSourceSpecToFutureBinding', settlementDataProperty: string, tradingTerminationProperty: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } } }> } | null };
export const MarketFieldsFragmentDoc = gql`
fragment MarketFields on Market {
@@ -44,6 +44,13 @@ export const MarketFieldsFragmentDoc = gql`
dataSourceSpecForTradingTermination {
id
}
dataSourceSpecForSettlementData {
id
}
dataSourceSpecBinding {
settlementDataProperty
tradingTerminationProperty
}
}
}
}
@@ -8,7 +8,7 @@ import type {
TypedDataAgGrid,
} from '@vegaprotocol/datagrid';
import {
AgGridDynamic as AgGrid,
AgGridLazy as AgGrid,
PriceFlashCell,
MarketNameCell,
SetFilter,
+16 -42
View File
@@ -25,8 +25,10 @@ export const marketsDataQuery = (
return merge(defaultResult, override);
};
const marketsDataFieldsFragments: MarketsDataFieldsFragment[] = [
{
export const createMarketsDataFragment = (
override?: PartialDeep<MarketsDataFieldsFragment>
): MarketsDataFieldsFragment => {
const defaultResult = {
market: {
id: 'market-0',
__typename: 'Market',
@@ -42,56 +44,28 @@ const marketsDataFieldsFragments: MarketsDataFieldsFragment[] = [
markPrice: '4612690058',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
__typename: 'MarketData',
},
{
};
return merge(defaultResult, override);
};
const marketsDataFieldsFragments: MarketsDataFieldsFragment[] = [
createMarketsDataFragment(),
createMarketsDataFragment({
market: {
id: 'market-1',
__typename: 'Market',
},
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
staticMidPrice: '0',
indicativePrice: '0',
bestStaticBidPrice: '0',
bestStaticOfferPrice: '0',
indicativeVolume: '0',
bestBidPrice: '0',
bestOfferPrice: '0',
markPrice: '8441',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
__typename: 'MarketData',
},
{
}),
createMarketsDataFragment({
market: {
id: 'market-2',
__typename: 'Market',
},
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
staticMidPrice: '0',
indicativePrice: '0',
bestStaticBidPrice: '0',
bestStaticOfferPrice: '0',
indicativeVolume: '0',
bestBidPrice: '0',
bestOfferPrice: '0',
markPrice: '4612690058',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET,
__typename: 'MarketData',
},
{
}),
createMarketsDataFragment({
market: {
id: 'market-3',
__typename: 'Market',
},
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
staticMidPrice: '0',
indicativePrice: '0',
bestStaticBidPrice: '0',
bestStaticOfferPrice: '0',
indicativeVolume: '0',
bestBidPrice: '0',
bestOfferPrice: '0',
markPrice: '4612690058',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET,
__typename: 'MarketData',
},
}),
];
+13 -1
View File
@@ -13,7 +13,7 @@ import type { MarketData } from './market-data-provider';
import type { MarketCandles } from './markets-candles-provider';
import { useMemo } from 'react';
import * as Schema from '@vegaprotocol/types';
import { filterAndSortMarkets } from './utils';
import { filterAndSortClosedMarkets, filterAndSortMarkets } from './utils';
import { MarketsDocument } from './__generated__/markets';
import type { Candle } from './market-candles-provider';
@@ -72,6 +72,11 @@ export const activeMarketsProvider = makeDerivedDataProvider<Market[], never>(
([markets]) => filterAndSortMarkets(markets)
);
export const closedMarketsProvider = makeDerivedDataProvider<Market[], never>(
[marketsProvider],
([markets]) => filterAndSortClosedMarkets(markets)
);
export type MarketMaybeWithCandles = Market & { candles?: Candle[] };
const addCandles = <T extends Market>(
@@ -111,6 +116,13 @@ export const marketsWithDataProvider = makeDerivedDataProvider<
addData(parts[0] as Market[], parts[1] as MarketData[])
);
export const closedMarketsWithDataProvider = makeDerivedDataProvider<
MarketMaybeWithData[],
never
>([closedMarketsProvider, marketsDataProvider], (parts) =>
addData(parts[0] as Market[], parts[1] as MarketData[])
);
export type MarketMaybeWithDataAndCandles = MarketMaybeWithData &
MarketMaybeWithCandles;
+7
View File
@@ -31,6 +31,13 @@ fragment MarketFields on Market {
dataSourceSpecForTradingTermination {
id
}
dataSourceSpecForSettlementData {
id
}
dataSourceSpecBinding {
settlementDataProperty
tradingTerminationProperty
}
}
}
}
+27 -77
View File
@@ -22,8 +22,10 @@ export const marketsQuery = (
return merge(defaultResult, override);
};
const marketFieldsFragments: MarketFieldsFragment[] = [
{
export const createMarketFragment = (
override?: PartialDeep<MarketFieldsFragment>
): MarketFieldsFragment => {
const defaultFragment = {
id: 'market-0',
decimalPlaces: 5,
positionDecimalPlaces: 0,
@@ -61,8 +63,18 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
quoteName: 'DAI',
__typename: 'Future',
},
@@ -71,36 +83,20 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
{
};
return merge(defaultFragment, override);
};
const marketFieldsFragments: MarketFieldsFragment[] = [
createMarketFragment({ id: 'market-0' }),
createMarketFragment({
id: 'market-1',
decimalPlaces: 2,
positionDecimalPlaces: 0,
tradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
state: Schema.MarketState.STATE_ACTIVE,
marketTimestamps: {
__typename: 'MarketTimestamps',
close: '',
open: '',
},
fees: {
__typename: 'Fees',
factors: {
__typename: 'FeeFactors',
makerFee: '',
infrastructureFee: '',
liquidityFee: '',
},
},
tradableInstrument: {
instrument: {
id: 'SOLUSD',
name: 'SUSPENDED MARKET',
code: 'SOLUSD',
metadata: {
__typename: 'InstrumentMetadata',
tags: [],
},
product: {
settlementAsset: {
id: 'asset-1',
@@ -109,33 +105,19 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
decimals: 5,
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: 'oracleId',
},
quoteName: 'USD',
__typename: 'Future',
},
__typename: 'Instrument',
},
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
{
}),
createMarketFragment({
id: 'market-2',
decimalPlaces: 5,
positionDecimalPlaces: 0,
tradingMode: Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
state: Schema.MarketState.STATE_SUSPENDED,
marketTimestamps: {
__typename: 'MarketTimestamps',
close: '2022-08-26T11:36:32.252490405Z',
open: null,
},
fees: {
__typename: 'Fees',
factors: {
__typename: 'FeeFactors',
makerFee: '0.0002',
infrastructureFee: '0.0005',
liquidityFee: '0.001',
@@ -143,13 +125,8 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
},
tradableInstrument: {
instrument: {
id: '',
code: 'AAPL.MF21',
name: 'Apple Monthly (30 Jun 2022)',
metadata: {
__typename: 'InstrumentMetadata',
tags: [],
},
product: {
settlementAsset: {
id: 'asset-2',
@@ -158,33 +135,18 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
decimals: 5,
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: 'oracleId',
},
quoteName: 'USDC',
__typename: 'Future',
},
__typename: 'Instrument',
},
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
{
}),
createMarketFragment({
id: 'market-3',
decimalPlaces: 5,
positionDecimalPlaces: 0,
tradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
state: Schema.MarketState.STATE_ACTIVE,
marketTimestamps: {
__typename: 'MarketTimestamps',
close: '2022-08-26T11:36:32.252490405Z',
open: null,
},
fees: {
__typename: 'Fees',
factors: {
__typename: 'FeeFactors',
makerFee: '0.0002',
infrastructureFee: '0.0005',
liquidityFee: '0.001',
@@ -192,13 +154,8 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
},
tradableInstrument: {
instrument: {
id: '',
code: 'ETHBTC.QM21',
name: 'ETHBTC Quarterly (30 Jun 2022)',
metadata: {
__typename: 'InstrumentMetadata',
tags: [],
},
product: {
settlementAsset: {
id: 'asset-3',
@@ -207,16 +164,9 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
decimals: 5,
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: 'oracleId',
},
quoteName: 'BTC',
__typename: 'Future',
},
__typename: 'Instrument',
},
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
}),
];
@@ -43,6 +43,15 @@ export const filterAndSortMarkets = (markets: Market[]) => {
);
};
export const filterAndSortClosedMarkets = (markets: Market[]) => {
return markets.filter((m) => {
return [
MarketState.STATE_SETTLED,
MarketState.STATE_TRADING_TERMINATED,
].includes(m.state);
});
};
export const calcCandleLow = (candles: Candle[]): string | undefined => {
return candles
?.reduce((acc: BigNumber, c) => {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__", "__generated___"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
+28
View File
@@ -0,0 +1,28 @@
const rootMain = require('../../../.storybook/main');
module.exports = {
...rootMain,
core: { ...rootMain.core, builder: 'webpack5' },
stories: [
...rootMain.stories,
'../src/**/*.stories.mdx',
'../src/**/*.stories.@(js|jsx|ts|tsx)',
],
addons: [
...rootMain.addons,
'@nrwl/react/plugins/storybook',
'storybook-addon-themes',
],
webpackFinal: async (config, { configType }) => {
// apply any global webpack configs that might have been specified in .storybook/main.js
if (rootMain.webpackFinal) {
config = await rootMain.webpackFinal(config, { configType });
}
// add your own webpack tweaks if needed
return config;
},
};
@@ -0,0 +1 @@
<link rel="stylesheet" href="https://static.vega.xyz/fonts.css" />
+90
View File
@@ -0,0 +1,90 @@
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
import classNames from 'classnames';
import { useEffect } from 'react';
import '../src/styles.css';
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
backgrounds: { disable: true },
layout: 'fullscreen',
a11y: {
config: {
rules: [
{
// Disabled only for storybook because we display both the dark and light variants of the components on the same page without differentiating the ids, so it will always error.
id: 'duplicate-id-aria',
selector: '[data-testid="form-group"] > label',
},
{
// Disabled because we can't control the radix radio group component and it claims to be accessible to begin with, so hopefully no issues.
id: 'button-name',
selector: '[role=radiogroup] > button',
},
],
},
},
};
export const globalTypes = {
theme: {
name: 'Theme',
description: 'Global theme for components',
defaultValue: 'dark',
toolbar: {
icon: 'circlehollow',
items: [
{ value: 'light', title: 'Light' },
{ value: 'dark', title: 'Dark' },
{ value: 'sideBySide', title: 'Side by side' },
],
showName: true,
},
},
};
const StoryWrapper = ({ children, fill }) => {
const classes = classNames(
'p-4',
'bg-white dark:bg-black',
'text-neutral-800 dark:text-neutral-200',
{
'w-screen h-screen': fill,
}
);
return <div className={classes}>{children}</div>;
};
const ThemeWrapper = (Story, context) => {
const theme = context.parameters.theme || context.globals.theme;
const { setTheme } = useThemeSwitcher();
useEffect(() => {
// in side by side mode a 'dark' class on the html tag will interfere
// making the light 'side' dark, so remove it in that case
if (theme === 'sideBySide') {
document.documentElement.classList.remove('dark');
} else {
setTheme(theme);
}
}, [setTheme, theme]);
return theme === 'sideBySide' ? (
<>
<div className="bg-white text-black">
<StoryWrapper>
<Story />
</StoryWrapper>
</div>
<div className="dark bg-black text-white">
<StoryWrapper>
<Story />
</StoryWrapper>
</div>
</>
) : (
<StoryWrapper fill={true}>
<Story />
</StoryWrapper>
);
};
export const decorators = [ThemeWrapper];
+20
View File
@@ -0,0 +1,20 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"emitDecoratorMetadata": true,
"outDir": ""
},
"files": [
"../../../node_modules/@nrwl/react/typings/styled-jsx.d.ts",
"../../../node_modules/@nrwl/react/typings/cssmodule.d.ts",
"../../../node_modules/@nrwl/react/typings/image.d.ts"
],
"exclude": [
"../**/*.spec.ts",
"../**/*.spec.js",
"../**/*.spec.tsx",
"../**/*.spec.jsx",
"jest.config.ts"
],
"include": ["../src/**/*", "*.js"]
}
+1
View File
@@ -7,4 +7,5 @@ export default {
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/libs/oracles',
setupFilesAfterEnv: ['./src/setup-tests.ts'],
};
+10
View File
@@ -0,0 +1,10 @@
const { join } = require('path');
module.exports = {
plugins: {
tailwindcss: {
config: join(__dirname, 'tailwind.config.js'),
},
autoprefixer: {},
},
};
+38
View File
@@ -38,6 +38,44 @@
"jestConfig": "libs/oracles/jest.config.ts",
"passWithNoTests": true
}
},
"storybook": {
"executor": "@nrwl/storybook:storybook",
"options": {
"uiFramework": "@storybook/react",
"port": 4400,
"config": {
"configFolder": "libs/oracles/.storybook"
}
},
"configurations": {
"ci": {
"quiet": true
}
}
},
"build-storybook": {
"executor": "@nrwl/storybook:build",
"outputs": ["{options.outputPath}"],
"options": {
"uiFramework": "@storybook/react",
"outputPath": "dist/storybook/oracles",
"config": {
"configFolder": "libs/oracles/.storybook"
}
},
"configurations": {
"ci": {
"quiet": true
}
}
},
"build-spec": {
"executor": "@nrwl/workspace:run-commands",
"outputs": [],
"options": {
"command": "yarn tsc --project ./libs/oracles/tsconfig.spec.json"
}
}
}
}
+1 -2
View File
@@ -1,2 +1 @@
export * from './lib/oracle-schema';
export * from './lib/use-oracle-proofs';
export * from './lib';
@@ -0,0 +1,18 @@
query OracleSpecDataConnection($oracleSpecId: ID!) {
oracleSpec(oracleSpecId: $oracleSpecId) {
dataConnection {
edges {
node {
externalData {
data {
data {
name
value
}
}
}
}
}
}
}
}

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