diff --git a/.github/workflows/ci-cd-trigger.yml b/.github/workflows/ci-cd-trigger.yml index fd11dc4de..73c37dd16 100644 --- a/.github/workflows/ci-cd-trigger.yml +++ b/.github/workflows/ci-cd-trigger.yml @@ -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' diff --git a/apps/explorer/src/app/components/assets/assets-table.tsx b/apps/explorer/src/app/components/assets/assets-table.tsx index 6f9afc60b..a8d76beb2 100644 --- a/apps/explorer/src/app/components/assets/assets-table.tsx +++ b/apps/explorer/src/app/components/assets/assets-table.tsx @@ -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'; diff --git a/apps/explorer/src/app/components/markets/market-details.tsx b/apps/explorer/src/app/components/markets/market-details.tsx index 218371b63..3f8c02a00 100644 --- a/apps/explorer/src/app/components/markets/market-details.tsx +++ b/apps/explorer/src/app/components/markets/market-details.tsx @@ -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: ( - - - {t('View settlement data oracle specification')} - - - {t('View termination oracle specification')} - - + + ), + }, + { + title: t('Termination Oracle'), + content: ( + ), }, ]; diff --git a/apps/explorer/src/app/components/markets/markets-table.tsx b/apps/explorer/src/app/components/markets/markets-table.tsx index dd3c52127..d08a2c5fa 100644 --- a/apps/explorer/src/app/components/markets/markets-table.tsx +++ b/apps/explorer/src/app/components/markets/markets-table.tsx @@ -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, diff --git a/apps/explorer/src/app/components/proposals/proposals-table.tsx b/apps/explorer/src/app/components/proposals/proposals-table.tsx index 25aea5de5..e4e092a42 100644 --- a/apps/explorer/src/app/components/proposals/proposals-table.tsx +++ b/apps/explorer/src/app/components/proposals/proposals-table.tsx @@ -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, diff --git a/apps/explorer/src/styles.css b/apps/explorer/src/styles.css index 9a930982b..c7fb57bb3 100644 --- a/apps/explorer/src/styles.css +++ b/apps/explorer/src/styles.css @@ -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; +} diff --git a/apps/governance-e2e/src/fixtures/proposals/new-market.json b/apps/governance-e2e/src/fixtures/proposals/new-market.json index d9875eabb..eb3368324 100644 --- a/apps/governance-e2e/src/fixtures/proposals/new-market.json +++ b/apps/governance-e2e/src/fixtures/proposals/new-market.json @@ -9,7 +9,7 @@ "name": "Token test market", "code": "Token.24h", "future": { - "settlementAsset": "fBTC", + "settlementAsset": "73174a6fb1d5802ba0ac7bd7ab79e0a3a4837b262de0a4e80815a55442692bd0", "quoteName": "fBTC", "dataSourceSpecForSettlementData": { "external": { diff --git a/apps/governance-e2e/src/integration/flow/proposal-details.cy.ts b/apps/governance-e2e/src/integration/flow/proposal-details.cy.ts index 5e9de85ec..611568056 100644 --- a/apps/governance-e2e/src/integration/flow/proposal-details.cy.ts +++ b/apps/governance-e2e/src/integration/flow/proposal-details.cy.ts @@ -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('@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('@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%') diff --git a/apps/governance-e2e/src/integration/flow/proposal-enacted.cy.ts b/apps/governance-e2e/src/integration/flow/proposal-enacted.cy.ts index 5f1fa01d9..293437d45 100644 --- a/apps/governance-e2e/src/integration/flow/proposal-enacted.cy.ts +++ b/apps/governance-e2e/src/integration/flow/proposal-enacted.cy.ts @@ -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') diff --git a/apps/governance-e2e/src/integration/flow/proposal-flow.cy.ts b/apps/governance-e2e/src/integration/flow/proposal-flow.cy.ts index da5278d03..e810e63d4 100644 --- a/apps/governance-e2e/src/integration/flow/proposal-flow.cy.ts +++ b/apps/governance-e2e/src/integration/flow/proposal-flow.cy.ts @@ -84,6 +84,7 @@ context( }); beforeEach('visit governance tab', function () { + cy.clearLocalStorage(); cy.reload(); waitForSpinner(); cy.connectVegaWallet(); diff --git a/apps/governance-e2e/src/integration/flow/proposal-forms.cy.ts b/apps/governance-e2e/src/integration/flow/proposal-forms.cy.ts index 557f6c31e..3855eaf24 100644 --- a/apps/governance-e2e/src/integration/flow/proposal-forms.cy.ts +++ b/apps/governance-e2e/src/integration/flow/proposal-forms.cy.ts @@ -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(); diff --git a/apps/governance-e2e/src/integration/flow/proposal-list.cy.ts b/apps/governance-e2e/src/integration/flow/proposal-list.cy.ts index e6da93eaa..bbae98c34 100644 --- a/apps/governance-e2e/src/integration/flow/proposal-list.cy.ts +++ b/apps/governance-e2e/src/integration/flow/proposal-list.cy.ts @@ -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/); }); }); diff --git a/apps/governance-e2e/src/integration/flow/rewards-flow.cy.ts b/apps/governance-e2e/src/integration/flow/rewards-flow.cy.ts index 2f33aadfa..be874a12e 100644 --- a/apps/governance-e2e/src/integration/flow/rewards-flow.cy.ts +++ b/apps/governance-e2e/src/integration/flow/rewards-flow.cy.ts @@ -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'); }); }); }); diff --git a/apps/governance-e2e/src/integration/flow/staking-flow.cy.ts b/apps/governance-e2e/src/integration/flow/staking-flow.cy.ts index 7722c6c8d..f7683bb31 100644 --- a/apps/governance-e2e/src/integration/flow/staking-flow.cy.ts +++ b/apps/governance-e2e/src/integration/flow/staking-flow.cy.ts @@ -66,7 +66,7 @@ context( beforeEach( 'teardown wallet & drill into a specific validator', function () { - cy.clearAllLocalStorage(); + cy.clearLocalStorage(); cy.reload(); waitForSpinner(); cy.connectVegaWallet(); diff --git a/apps/governance-e2e/src/integration/flow/token-association-flow.cy.ts b/apps/governance-e2e/src/integration/flow/token-association-flow.cy.ts index 9bb79171a..3eb6ce5d6 100644 --- a/apps/governance-e2e/src/integration/flow/token-association-flow.cy.ts +++ b/apps/governance-e2e/src/integration/flow/token-association-flow.cy.ts @@ -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( diff --git a/apps/governance-e2e/src/integration/flow/withdrawal-flow.cy.ts b/apps/governance-e2e/src/integration/flow/withdrawal-flow.cy.ts index ebd2f619b..733899622 100644 --- a/apps/governance-e2e/src/integration/flow/withdrawal-flow.cy.ts +++ b/apps/governance-e2e/src/integration/flow/withdrawal-flow.cy.ts @@ -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); } } ); diff --git a/apps/governance-e2e/src/support/governance.functions.ts b/apps/governance-e2e/src/support/governance.functions.ts index 318d53cdf..d3634c062 100644 --- a/apps/governance-e2e/src/support/governance.functions.ts +++ b/apps/governance-e2e/src/support/governance.functions.ts @@ -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(); } diff --git a/apps/governance-e2e/src/support/wallet-teardown.functions.ts b/apps/governance-e2e/src/support/wallet-teardown.functions.ts index 1560c2233..5c80fca9a 100644 --- a/apps/governance-e2e/src/support/wallet-teardown.functions.ts +++ b/apps/governance-e2e/src/support/wallet-teardown.functions.ts @@ -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 } ); } }); diff --git a/apps/governance/src/components/disconnected-notice/disconnected-notice.spec.tsx b/apps/governance/src/components/disconnected-notice/disconnected-notice.spec.tsx new file mode 100644 index 000000000..f22924342 --- /dev/null +++ b/apps/governance/src/components/disconnected-notice/disconnected-notice.spec.tsx @@ -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( + + ); + const disconnectedNotice = screen.getByTestId('disconnected-notice'); + expect(disconnectedNotice).toBeInTheDocument(); + }); + + it("doesn't render Notification when isDisconnected is false", () => { + render( + + ); + const disconnectedNotice = screen.queryByTestId('disconnected-notice'); + expect(disconnectedNotice).not.toBeInTheDocument(); + }); + + it("doesn't render Notification when correctNetworkChainId is undefined", () => { + render( + + ); + const disconnectedNotice = screen.queryByTestId('disconnected-notice'); + expect(disconnectedNotice).not.toBeInTheDocument(); + }); + + it("doesn't render Notification when correctNetworkChainId is null", () => { + render( + + ); + const disconnectedNotice = screen.queryByTestId('disconnected-notice'); + expect(disconnectedNotice).not.toBeInTheDocument(); + }); +}); diff --git a/apps/governance/src/components/disconnected-notice/disconnected-notice.tsx b/apps/governance/src/components/disconnected-notice/disconnected-notice.tsx new file mode 100644 index 000000000..efd63ceb1 --- /dev/null +++ b/apps/governance/src/components/disconnected-notice/disconnected-notice.tsx @@ -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 ( +
+ +
+ ); +}; diff --git a/apps/governance/src/components/disconnected-notice/index.tsx b/apps/governance/src/components/disconnected-notice/index.tsx new file mode 100644 index 000000000..943ebd09b --- /dev/null +++ b/apps/governance/src/components/disconnected-notice/index.tsx @@ -0,0 +1 @@ +export * from './disconnected-notice'; diff --git a/apps/governance/src/components/eth-wallet/eth-wallet.tsx b/apps/governance/src/components/eth-wallet/eth-wallet.tsx index f095ed20a..ca334a43d 100644 --- a/apps/governance/src/components/eth-wallet/eth-wallet.tsx +++ b/apps/governance/src/components/eth-wallet/eth-wallet.tsx @@ -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 (

{t('ethereumKey')}

+ {account && (
- - {children} - + {children} 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 ( @@ -80,18 +113,5 @@ export const Web3Content = ({ children, appChainId }: Web3ContentProps) => { ); } - if (chainId !== undefined && chainId !== appChainId) { - return ( - -
-

- This app only works on {getChainName(appChainId)} -

- -
-
- ); - } - return children; }; diff --git a/apps/governance/src/contexts/app-state/app-state-context.ts b/apps/governance/src/contexts/app-state/app-state-context.ts index c2b8c3dce..054899d50 100644 --- a/apps/governance/src/contexts/app-state/app-state-context.ts +++ b/apps/governance/src/contexts/app-state/app-state-context.ts @@ -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 = { diff --git a/apps/governance/src/contexts/app-state/app-state-provider.tsx b/apps/governance/src/contexts/app-state/app-state-provider.tsx index 2b65344a9..182a9aee1 100644 --- a/apps/governance/src/contexts/app-state/app-state-provider.tsx +++ b/apps/governance/src/contexts/app-state/app-state-provider.tsx @@ -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, + }; + } } } diff --git a/apps/governance/src/i18n/translations/dev.json b/apps/governance/src/i18n/translations/dev.json index 597361a04..e18e6107d 100644 --- a/apps/governance/src/i18n/translations/dev.json +++ b/apps/governance/src/i18n/translations/dev.json @@ -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." } diff --git a/apps/governance/src/routes/proposals/components/list-asset/list-asset.spec.tsx b/apps/governance/src/routes/proposals/components/list-asset/list-asset.spec.tsx index fa1026151..5cf4dfce3 100644 --- a/apps/governance/src/routes/proposals/components/list-asset/list-asset.spec.tsx +++ b/apps/governance/src/routes/proposals/components/list-asset/list-asset.spec.tsx @@ -56,6 +56,7 @@ const mockAppState: AppState = { ethConnectOverlay: false, transactionOverlay: false, bannerMessage: '', + disconnectNotice: false, }; jest.mock('../../../contexts/app-state/app-state-context', () => ({ diff --git a/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.spec.tsx b/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.spec.tsx index 63d9ca8e1..1b538be80 100644 --- a/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.spec.tsx +++ b/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.spec.tsx @@ -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(); diff --git a/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.tsx b/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.tsx index 36992991f..fd10d8537 100644 --- a/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.tsx +++ b/apps/governance/src/routes/proposals/components/proposal-change-table/proposal-change-table.tsx @@ -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))} {terms?.change.__typename !== 'NewFreeform' ? ( {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) )} ) : null} @@ -54,7 +52,7 @@ export const ProposalChangeTable = ({ proposal }: ProposalChangeTableProps) => { {t('proposedOn')} - {format(new Date(proposal?.datetime), DATE_FORMAT_DETAILED)} + {formatDateWithLocalTimezone(new Date(proposal?.datetime))} {proposal?.rejectionReason ? ( diff --git a/apps/governance/src/routes/proposals/hooks/use-vote-information.spec.ts b/apps/governance/src/routes/proposals/hooks/use-vote-information.spec.ts index 7725d3626..c79bc73fc 100644 --- a/apps/governance/src/routes/proposals/hooks/use-vote-information.spec.ts +++ b/apps/governance/src/routes/proposals/hooks/use-vote-information.spec.ts @@ -19,6 +19,7 @@ const mockAppState: AppState = { ethConnectOverlay: false, transactionOverlay: false, bannerMessage: '', + disconnectNotice: false, }; jest.mock('../../../contexts/app-state/app-state-context', () => ({ diff --git a/apps/governance/src/routes/staking/home/validator-tables/consensus-validators-table.tsx b/apps/governance/src/routes/staking/home/validator-tables/consensus-validators-table.tsx index f09e1944a..388683bac 100644 --- a/apps/governance/src/routes/staking/home/validator-tables/consensus-validators-table.tsx +++ b/apps/governance/src/routes/staking/home/validator-tables/consensus-validators-table.tsx @@ -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 ( -
+
{nodes.length > 0 && ( getRowHeight(params)} defaultColDef={defaultColDef} tooltipShowDelay={0} diff --git a/apps/governance/src/routes/staking/home/validator-tables/shared.tsx b/apps/governance/src/routes/staking/home/validator-tables/shared.tsx index 1388b1cb4..ec8514802 100644 --- a/apps/governance/src/routes/staking/home/validator-tables/shared.tsx +++ b/apps/governance/src/routes/staking/home/validator-tables/shared.tsx @@ -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); diff --git a/apps/governance/src/routes/staking/home/validator-tables/standby-pending-validators-table.tsx b/apps/governance/src/routes/staking/home/validator-tables/standby-pending-validators-table.tsx index 9c7cd5405..b150cfcdb 100644 --- a/apps/governance/src/routes/staking/home/validator-tables/standby-pending-validators-table.tsx +++ b/apps/governance/src/routes/staking/home/validator-tables/standby-pending-validators-table.tsx @@ -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 ( -
+
{ + 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}` + ); + }); +}); diff --git a/apps/trading-e2e/src/integration/deposit.cy.ts b/apps/trading-e2e/src/integration/deposit.cy.ts index 815fd58c7..7be01169f 100644 --- a/apps/trading-e2e/src/integration/deposit.cy.ts +++ b/apps/trading-e2e/src/integration/deposit.cy.ts @@ -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'); }); }); diff --git a/apps/trading-e2e/src/integration/home.cy.ts b/apps/trading-e2e/src/integration/home.cy.ts index 43144738c..7dc59dccc 100644 --- a/apps/trading-e2e/src/integration/home.cy.ts +++ b/apps/trading-e2e/src/integration/home.cy.ts @@ -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); diff --git a/apps/trading-e2e/src/integration/market-info.cy.ts b/apps/trading-e2e/src/integration/market-info.cy.ts index ea34519d1..f507a47ee 100644 --- a/apps/trading-e2e/src/integration/market-info.cy.ts +++ b/apps/trading-e2e/src/integration/market-info.cy.ts @@ -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', () => { diff --git a/apps/trading-e2e/src/integration/markets.cy.ts b/apps/trading-e2e/src/integration/markets.cy.ts index 1ebeb1d32..a189ba737 100644 --- a/apps/trading-e2e/src/integration/markets.cy.ts +++ b/apps/trading-e2e/src/integration/markets.cy.ts @@ -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', { diff --git a/apps/trading-e2e/src/support/order-update-subscription.ts b/apps/trading-e2e/src/support/order-update-subscription.ts index 72aee6961..3d9095324 100644 --- a/apps/trading-e2e/src/support/order-update-subscription.ts +++ b/apps/trading-e2e/src/support/order-update-subscription.ts @@ -26,6 +26,7 @@ export function updateOrder( override?: PartialDeep ): void { const update: OrdersUpdateSubscription = orderUpdateSubscription({ + // @ts-ignore partial deep check failing orders: [override], }); if (!sendOrderUpdate) { diff --git a/apps/trading-e2e/src/support/trading.ts b/apps/trading-e2e/src/support/trading.ts index 8d8202d6d..99691e270 100644 --- a/apps/trading-e2e/src/support/trading.ts +++ b/apps/trading-e2e/src/support/trading.ts @@ -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, }, diff --git a/apps/trading/client-pages/market/trade-grid.tsx b/apps/trading/client-pages/market/trade-grid.tsx index 2630b6e67..41a8e5d9c 100644 --- a/apps/trading/client-pages/market/trade-grid.tsx +++ b/apps/trading/client-pages/market/trade-grid.tsx @@ -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 ? ( - + @@ -120,7 +128,7 @@ const MarketBottomPanel = memo( @@ -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 ( - + - + @@ -220,7 +235,7 @@ const MainGrid = memo( @@ -239,7 +254,7 @@ const MainGrid = memo( @@ -257,7 +272,7 @@ const MainGrid = memo( @@ -279,11 +294,7 @@ export const TradeGrid = ({
- +
); }; diff --git a/apps/trading/client-pages/markets/closed.spec.tsx b/apps/trading/client-pages/markets/closed.spec.tsx new file mode 100644 index 000000000..294ba9009 --- /dev/null +++ b/apps/trading/client-pages/markets/closed.spec.tsx @@ -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 = { + 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 = { + 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 = { + 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 = { + 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( + + + + + + ); + }); + // 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 = { + request: { + query: MarketsDocument, + }, + result: { + data: { + marketsConnection: { + __typename: 'MarketConnection', + edges: mixedMarkets, + }, + }, + }, + }; + await act(async () => { + render( + + + + + + ); + }); + + // 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)); + }); +}); diff --git a/apps/trading/client-pages/markets/closed.tsx b/apps/trading/client-pages/markets/closed.tsx new file mode 100644 index 000000000..6c81e10c4 --- /dev/null +++ b/apps/trading/client-pages/markets/closed.tsx @@ -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 ( +
+ +
+ +
+
+ ); +}; + +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) => { + 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 ( + + ); + }, + 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) => { + 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) => { + 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) => { + 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) => ( + + ), + }, + { + headerName: t('Realised PNL'), + field: 'realisedPNL', + cellClass: 'font-mono ag-right-aligned-cell', + type: 'numericColumn', + valueFormatter: ({ + value, + data, + }: VegaValueFormatterParams) => { + if (!value || !data) return '-'; + return addDecimalsFormatNumber(value, data.decimalPlaces); + }, + }, + { + headerName: t('Settlement asset'), + field: 'settlementAsset', + cellRenderer: ({ + value, + data, + }: VegaValueFormatterParams) => ( + + ), + }, + { + headerName: t('Market ID'), + field: 'id', + }, + ]; + return cols; + }, [openAssetDialog]); + + return ( + data.id} + defaultColDef={{ + flex: 1, + resizable: true, + }} + overlayNoRowsTemplate="No data" + /> + ); +}; diff --git a/apps/trading/client-pages/markets/markets-page.tsx b/apps/trading/client-pages/markets/markets-page.tsx index e2c61dcc0..24e9020c4 100644 --- a/apps/trading/client-pages/markets/markets-page.tsx +++ b/apps/trading/client-pages/markets/markets-page.tsx @@ -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 = () => { + + + ); }; diff --git a/apps/trading/client-pages/markets/proposed.tsx b/apps/trading/client-pages/markets/proposed.tsx index a577e6cfc..3c4a4d529 100644 --- a/apps/trading/client-pages/markets/proposed.tsx +++ b/apps/trading/client-pages/markets/proposed.tsx @@ -12,7 +12,9 @@ export const Proposed = () => { const externalLink = tokenLink(TOKEN_NEW_MARKET_PROPOSAL); return ( <> - +
+ +
{t('Propose a new market')} diff --git a/apps/trading/client-pages/markets/settlement-date-cell.spec.tsx b/apps/trading/client-pages/markets/settlement-date-cell.spec.tsx new file mode 100644 index 000000000..43c6c9552 --- /dev/null +++ b/apps/trading/client-pages/markets/settlement-date-cell.spec.tsx @@ -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(); + + 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(); + + 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(); + + 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(); + + 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(); + + const link = screen.getByRole('link'); + expect(link).toHaveTextContent(`Expected in ${daysAgo} days`); + expect(link).toHaveAttribute( + 'href', + expect.stringContaining(`/oracles/${props.oracleSpecId}`) + ); + }); +}); diff --git a/apps/trading/client-pages/markets/settlement-date-cell.tsx b/apps/trading/client-pages/markets/settlement-date-cell.tsx new file mode 100644 index 000000000..80fb9cf5c --- /dev/null +++ b/apps/trading/client-pages/markets/settlement-date-cell.tsx @@ -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 ( + + {text} + + ); +}; diff --git a/apps/trading/client-pages/markets/settlement-price-cell.spec.tsx b/apps/trading/client-pages/markets/settlement-price-cell.spec.tsx new file mode 100644 index 000000000..cfd1c6ed9 --- /dev/null +++ b/apps/trading/client-pages/markets/settlement-price-cell.spec.tsx @@ -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 => { + 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( + + + + ); + + 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( + + + + ); + + 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( + + + + ); + + expect(screen.getByText('-')).toBeInTheDocument(); + expect(screen.queryByRole('link')).not.toBeInTheDocument(); + }); +}); diff --git a/apps/trading/client-pages/markets/settlement-price-cell.tsx b/apps/trading/client-pages/markets/settlement-price-cell.tsx new file mode 100644 index 000000000..03cf6d6e8 --- /dev/null +++ b/apps/trading/client-pages/markets/settlement-price-cell.tsx @@ -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 -; + } + + return ( + + {property + ? addDecimalsFormatNumber(property.value, decimalPlaces) + : t('-')} + + ); +}; diff --git a/apps/trading/client-pages/portfolio/portfolio.tsx b/apps/trading/client-pages/portfolio/portfolio.tsx index c71fa8f60..51a9820f4 100644 --- a/apps/trading/client-pages/portfolio/portfolio.tsx +++ b/apps/trading/client-pages/portfolio/portfolio.tsx @@ -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 (
- + @@ -79,7 +80,7 @@ export const Portfolio = () => { diff --git a/apps/trading/client-pages/settings/settings.tsx b/apps/trading/client-pages/settings/settings.tsx index cb14ffde2..6a9dd38d0 100644 --- a/apps/trading/client-pages/settings/settings.tsx +++ b/apps/trading/client-pages/settings/settings.tsx @@ -36,7 +36,11 @@ export const Settings = () => { />
- +
diff --git a/apps/trading/components/constants.ts b/apps/trading/components/constants.ts index 5a41d2910..3aa00c63d 100644 --- a/apps/trading/components/constants.ts +++ b/apps/trading/components/constants.ts @@ -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.' ); diff --git a/apps/trading/components/select-market/select-market.spec.tsx b/apps/trading/components/select-market/select-market.spec.tsx index e7fec9a86..4340bb1e5 100644 --- a/apps/trading/components/select-market/select-market.spec.tsx +++ b/apps/trading/components/select-market/select-market.spec.tsx @@ -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: { diff --git a/apps/trading/components/welcome-dialog/risk-notice-dialog.spec.tsx b/apps/trading/components/welcome-dialog/risk-notice-dialog.spec.tsx index 9b476130b..c4a9af049 100644 --- a/apps/trading/components/welcome-dialog/risk-notice-dialog.spec.tsx +++ b/apps/trading/components/welcome-dialog/risk-notice-dialog.spec.tsx @@ -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( - - - , - { wrapper: BrowserRouter } - ); + render(); - 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(); + render(); - expect(screen.queryByText(introText)).toBeInTheDocument(); + expect(screen.getByText(introText)).toBeInTheDocument(); const button = screen.getByRole('button', { name: 'I understand, Continue', diff --git a/apps/trading/components/welcome-dialog/risk-notice-dialog.tsx b/apps/trading/components/welcome-dialog/risk-notice-dialog.tsx index 6c5531b2b..57e9bda43 100644 --- a/apps/trading/components/welcome-dialog/risk-notice-dialog.tsx +++ b/apps/trading/components/welcome-dialog/risk-notice-dialog.tsx @@ -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 ? ( + + ) : ( + + )} +
+ +
+ + + ); +}; + +const TestnetContent = ({ network }: { network: Networks }) => { + const { VEGA_DOCS_URL, GITHUB_FEEDBACK_URL, VEGA_WALLET_URL } = + useEnvironment(); + return ( + <> +

+ {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] + )} +

+

+ {t( + 'Your Vega wallet must also be connected to %s, and your Ethereum wallet must be connected to Sepolia.', + [network] + )} +

+ {VEGA_DOCS_URL && GITHUB_FEEDBACK_URL && VEGA_WALLET_URL && ( +
    +
  • + + {t('Learn about Vega wallet')}{' '} + + +
  • +
  • + + {t('View documentation')}{' '} + + +
  • +
  • + + {t('Provide feedback')}{' '} + + +
  • +
+ )} + + ); +}; + +const MainnetContent = () => { return ( <>

{t('Regulation may apply to use of this app')}

-

+

{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) => {

{t('Technical and financial risk of loss')}

-

+

{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.' )}

- -
- -
); }; diff --git a/apps/trading/components/welcome-dialog/telemetry-approval.spec.tsx b/apps/trading/components/welcome-dialog/telemetry-approval.spec.tsx index dc5ff93a9..3061845aa 100644 --- a/apps/trading/components/welcome-dialog/telemetry-approval.spec.tsx +++ b/apps/trading/components/welcome-dialog/telemetry-approval.spec.tsx @@ -3,7 +3,8 @@ import { TelemetryApproval } from './telemetry-approval'; describe('TelemetryApproval', () => { it('click on checkbox should be properly handled', () => { - render(); + const helpText = 'My help text'; + render(); 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(); }); }); diff --git a/apps/trading/components/welcome-dialog/telemetry-approval.tsx b/apps/trading/components/welcome-dialog/telemetry-approval.tsx index e4464418e..4dbee1cfe 100644 --- a/apps/trading/components/welcome-dialog/telemetry-approval.tsx +++ b/apps/trading/components/welcome-dialog/telemetry-approval.tsx @@ -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 (
@@ -19,13 +15,7 @@ export const TelemetryApproval = ({ />
- - {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.')} - + {helpText}
); diff --git a/apps/trading/components/welcome-dialog/welcome-dialog.tsx b/apps/trading/components/welcome-dialog/welcome-dialog.tsx index 722f02c1a..dd48ed2eb 100644 --- a/apps/trading/components/welcome-dialog/welcome-dialog.tsx +++ b/apps/trading/components/welcome-dialog/welcome-dialog.tsx @@ -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 = ; - title = t('WARNING'); + dialogContent = ( + + ); + title = VEGA_ENV === Networks.MAINNET ? t('WARNING') : t('Vega Console'); size = 'medium'; } else if (isWelcomeDialogNeeded && data?.length === 0) { dialogContent = ; diff --git a/apps/trading/components/welcome-dialog/welcome-landing-dialog.spec.tsx b/apps/trading/components/welcome-dialog/welcome-landing-dialog.spec.tsx index 924aed57e..72f435a5e 100644 --- a/apps/trading/components/welcome-dialog/welcome-landing-dialog.spec.tsx +++ b/apps/trading/components/welcome-dialog/welcome-landing-dialog.spec.tsx @@ -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: { diff --git a/apps/trading/pages/styles.css b/apps/trading/pages/styles.css index 0ed581582..e0663446b 100644 --- a/apps/trading/pages/styles.css +++ b/apps/trading/pages/styles.css @@ -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; +} diff --git a/libs/accounts/src/lib/accounts-manager.spec.tsx b/libs/accounts/src/lib/accounts-manager.spec.tsx index 0cef83081..7f3fce85f 100644 --- a/libs/accounts/src/lib/accounts-manager.spec.tsx +++ b/libs/accounts/src/lib/accounts-manager.spec.tsx @@ -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( { it('update method should return proper result', async () => { let rerenderer: (ui: React.ReactElement) => void; - await act(() => { + await act(async () => { const { rerender } = render( { await waitFor(() => { expect(screen.getByText('No accounts')).toBeInTheDocument(); }); - await act(() => { + await act(async () => { rerenderer( ( - <> - - {customThemeParams && } - {children} - -); diff --git a/libs/datagrid/src/lib/ag-grid/ag-grid-dynamic-themed.tsx b/libs/datagrid/src/lib/ag-grid/ag-grid-dynamic-themed.tsx deleted file mode 100644 index c93d44fc1..000000000 --- a/libs/datagrid/src/lib/ag-grid/ag-grid-dynamic-themed.tsx +++ /dev/null @@ -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( - () => import('./ag-grid-light').then((mod) => mod.AgGrid), - { ssr: false } -) as FunctionComponent; - -const AgGridDarkTheme = dynamic( - () => import('./ag-grid-dark').then((mod) => mod.AgGrid), - { ssr: false } -) as FunctionComponent; - -export const AgGridThemed = ({ - id, - style, - className, - gridRef, - customThemeParams, - children, - ...props -}: (AgGridReactProps | AgReactUiProps) & { - style?: CSSProperties; - className?: string; - gridRef?: React.ForwardedRef; - customThemeParams?: string; - id?: string; - children?: ReactNode[]; -}) => { - const containerRef = useRef(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 ( -
- {theme === 'dark' ? ( - - - {sizedChildren} - - - ) : ( - - - {sizedChildren} - - - )} -
- ); -}; diff --git a/libs/datagrid/src/lib/ag-grid/ag-grid-dynamic.tsx b/libs/datagrid/src/lib/ag-grid/ag-grid-dynamic.tsx deleted file mode 100644 index b3d138fdc..000000000 --- a/libs/datagrid/src/lib/ag-grid/ag-grid-dynamic.tsx +++ /dev/null @@ -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; - customThemeParams?: string; - id?: string; -}; - -// https://stackoverflow.com/questions/69433673/nextjs-reactdomserver-does-not-yet-support-suspense -const AgGridDynamicInternal = dynamic( - () => 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( - (props, ref) => -); diff --git a/libs/datagrid/src/lib/ag-grid/ag-grid-lazy-themed.tsx b/libs/datagrid/src/lib/ag-grid/ag-grid-lazy-themed.tsx index 40b27c308..6a8d46568 100644 --- a/libs/datagrid/src/lib/ag-grid/ag-grid-lazy-themed.tsx +++ b/libs/datagrid/src/lib/ag-grid/ag-grid-lazy-themed.tsx @@ -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; + id?: string; + children?: ReactNode[]; +}) => { + const containerRef = useRef(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 ( -
- {theme === 'dark' ? ( - - - - ) : ( - - - - )} +
+ + {sizedChildren} +
); -}); +}; diff --git a/libs/datagrid/src/lib/ag-grid/ag-grid-lazy.tsx b/libs/datagrid/src/lib/ag-grid/ag-grid-lazy.tsx index 75bc5218b..7e3102135 100644 --- a/libs/datagrid/src/lib/ag-grid/ag-grid-lazy.tsx +++ b/libs/datagrid/src/lib/ag-grid/ag-grid-lazy.tsx @@ -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; + id?: string; +}; + +export const AgGridLazyInternal = lazy(() => import('./ag-grid-lazy-themed').then((module) => ({ default: module.AgGridThemed, })) ); -export const AgGridLazy = React.forwardRef((props, ref) => ( - +export const AgGridLazy = forwardRef((props, ref) => ( + )); diff --git a/libs/datagrid/src/lib/ag-grid/ag-grid-light.tsx b/libs/datagrid/src/lib/ag-grid/ag-grid-light.tsx deleted file mode 100644 index a71f6136a..000000000 --- a/libs/datagrid/src/lib/ag-grid/ag-grid-light.tsx +++ /dev/null @@ -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; -}) => ( - <> - - {customThemeParams && } - {children} - -); diff --git a/libs/deal-ticket/src/test-helpers.ts b/libs/deal-ticket/src/test-helpers.ts index 4f69433fa..2357124e5 100644 --- a/libs/deal-ticket/src/test-helpers.ts +++ b/libs/deal-ticket/src/test-helpers.ts @@ -35,7 +35,17 @@ export function generateMarket(override?: PartialDeep): 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', diff --git a/libs/deposits/src/lib/deposits-table.tsx b/libs/deposits/src/lib/deposits-table.tsx index 792f6029a..798b815ad 100644 --- a/libs/deposits/src/lib/deposits-table.tsx +++ b/libs/deposits/src/lib/deposits-table.tsx @@ -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, diff --git a/libs/environment/src/hooks/use-links.ts b/libs/environment/src/hooks/use-links.ts index 828c95771..674f29c46 100644 --- a/libs/environment/src/hooks/use-links.ts +++ b/libs/environment/src/hooks/use-links.ts @@ -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'; diff --git a/libs/fills/src/lib/fills-table.tsx b/libs/fills/src/lib/fills-table.tsx index 9f0e7167b..1b22473f8 100644 --- a/libs/fills/src/lib/fills-table.tsx +++ b/libs/fills/src/lib/fills-table.tsx @@ -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, diff --git a/libs/fills/src/lib/test-helpers.ts b/libs/fills/src/lib/test-helpers.ts index b9cb91b1f..a9041ab18 100644 --- a/libs/fills/src/lib/test-helpers.ts +++ b/libs/fills/src/lib/test-helpers.ts @@ -78,7 +78,17 @@ export const generateFill = (override?: PartialDeep) => { }, quoteName: '', dataSourceSpecForTradingTermination: { - id: '', + __typename: 'DataSourceSpec', + id: 'oracleId', + }, + dataSourceSpecForSettlementData: { + __typename: 'DataSourceSpec', + id: 'oracleId', + }, + dataSourceSpecBinding: { + __typename: 'DataSourceSpecToFutureBinding', + tradingTerminationProperty: 'trading-termination-property', + settlementDataProperty: 'settlement-data-property', }, }, }, diff --git a/libs/ledger/src/lib/ledger-table.tsx b/libs/ledger/src/lib/ledger-table.tsx index a0ca5c18d..57ceb5581 100644 --- a/libs/ledger/src/lib/ledger-table.tsx +++ b/libs/ledger/src/lib/ledger-table.tsx @@ -10,7 +10,7 @@ import type { TypedDataAgGrid, } from '@vegaprotocol/datagrid'; import { - AgGridDynamic as AgGrid, + AgGridLazy as AgGrid, DateRangeFilter, SetFilter, } from '@vegaprotocol/datagrid'; diff --git a/libs/liquidity/src/lib/liquidity-table.tsx b/libs/liquidity/src/lib/liquidity-table.tsx index 13f834513..e9b408681 100644 --- a/libs/liquidity/src/lib/liquidity-table.tsx +++ b/libs/liquidity/src/lib/liquidity-table.tsx @@ -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'; diff --git a/libs/market-info/src/components/market-info/__generated__/MarketInfo.ts b/libs/market-info/src/components/market-info/__generated__/MarketInfo.ts index 51c75dc13..6825b5d7c 100644 --- a/libs/market-info/src/components/market-info/__generated__/MarketInfo.ts +++ b/libs/market-info/src/components/market-info/__generated__/MarketInfo.ts @@ -198,4 +198,4 @@ export function useMarketInfoLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions } export type MarketInfoQueryHookResult = ReturnType; export type MarketInfoLazyQueryHookResult = ReturnType; -export type MarketInfoQueryResult = Apollo.QueryResult; \ No newline at end of file +export type MarketInfoQueryResult = Apollo.QueryResult; diff --git a/libs/market-info/src/components/market-info/market-info-accordion.tsx b/libs/market-info/src/components/market-info/market-info-accordion.tsx index c6dc747cb..1b8c3cff0 100644 --- a/libs/market-info/src/components/market-info/market-info-accordion.tsx +++ b/libs/market-info/src/components/market-info/market-info-accordion.tsx @@ -103,6 +103,7 @@ const MarketInfoAccordion = ({ content: , })), ]; + const product = market.tradableInstrument.instrument.product; const marketSpecPanels = [ { @@ -113,9 +114,13 @@ const MarketInfoAccordion = ({ title: t('Instrument'), content: , }, - { - title: t('Oracle'), - content: , + product.dataSourceSpecForSettlementData && { + title: t('Settlement Oracle'), + content: , + }, + product.dataSourceSpecForTradingTermination && { + title: t('Termination Oracle'), + content: , }, { title: t('Settlement asset'), diff --git a/libs/market-info/src/components/market-info/market-info-panels.tsx b/libs/market-info/src/components/market-info/market-info-panels.tsx index c965935f2..ccaccc984 100644 --- a/libs/market-info/src/components/market-info/market-info-panels.tsx +++ b/libs/market-info/src/components/market-info/market-info-panels.tsx @@ -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 ( - -
+ + - - -
-
- - {t('View settlement data specification')} - - - {t('View termination specification')} - -
-
+ {type === 'settlementData' + ? t('View settlement data specification') + : t('View termination specification')} + +
); }; @@ -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 ; } return ( -

- {textWithCount} -

+
+ {signerProviders.map((provider) => ( + + ))} +
); }; diff --git a/libs/market-list/src/lib/__generated__/markets.ts b/libs/market-list/src/lib/__generated__/markets.ts index 58a8df387..e238c6f4b 100644 --- a/libs/market-list/src/lib/__generated__/markets.ts +++ b/libs/market-list/src/lib/__generated__/markets.ts @@ -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 | 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 | 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 | 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 | 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 + } } } } diff --git a/libs/market-list/src/lib/components/markets-container/market-list-table.tsx b/libs/market-list/src/lib/components/markets-container/market-list-table.tsx index b3002d283..53e4e928a 100644 --- a/libs/market-list/src/lib/components/markets-container/market-list-table.tsx +++ b/libs/market-list/src/lib/components/markets-container/market-list-table.tsx @@ -8,7 +8,7 @@ import type { TypedDataAgGrid, } from '@vegaprotocol/datagrid'; import { - AgGridDynamic as AgGrid, + AgGridLazy as AgGrid, PriceFlashCell, MarketNameCell, SetFilter, diff --git a/libs/market-list/src/lib/markets-data.mock.ts b/libs/market-list/src/lib/markets-data.mock.ts index 99df096b3..39aab494e 100644 --- a/libs/market-list/src/lib/markets-data.mock.ts +++ b/libs/market-list/src/lib/markets-data.mock.ts @@ -25,8 +25,10 @@ export const marketsDataQuery = ( return merge(defaultResult, override); }; -const marketsDataFieldsFragments: MarketsDataFieldsFragment[] = [ - { +export const createMarketsDataFragment = ( + override?: PartialDeep +): 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', - }, + }), ]; diff --git a/libs/market-list/src/lib/markets-provider.ts b/libs/market-list/src/lib/markets-provider.ts index 253d973ec..ebe2845a4 100644 --- a/libs/market-list/src/lib/markets-provider.ts +++ b/libs/market-list/src/lib/markets-provider.ts @@ -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( ([markets]) => filterAndSortMarkets(markets) ); +export const closedMarketsProvider = makeDerivedDataProvider( + [marketsProvider], + ([markets]) => filterAndSortClosedMarkets(markets) +); + export type MarketMaybeWithCandles = Market & { candles?: Candle[] }; const addCandles = ( @@ -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; diff --git a/libs/market-list/src/lib/markets.graphql b/libs/market-list/src/lib/markets.graphql index 445f6a90c..334023978 100644 --- a/libs/market-list/src/lib/markets.graphql +++ b/libs/market-list/src/lib/markets.graphql @@ -31,6 +31,13 @@ fragment MarketFields on Market { dataSourceSpecForTradingTermination { id } + dataSourceSpecForSettlementData { + id + } + dataSourceSpecBinding { + settlementDataProperty + tradingTerminationProperty + } } } } diff --git a/libs/market-list/src/lib/markets.mock.ts b/libs/market-list/src/lib/markets.mock.ts index 02d4cf013..e8b5ca485 100644 --- a/libs/market-list/src/lib/markets.mock.ts +++ b/libs/market-list/src/lib/markets.mock.ts @@ -22,8 +22,10 @@ export const marketsQuery = ( return merge(defaultResult, override); }; -const marketFieldsFragments: MarketFieldsFragment[] = [ - { +export const createMarketFragment = ( + override?: PartialDeep +): 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', - }, + }), ]; diff --git a/libs/market-list/src/lib/utils/market-utils.ts b/libs/market-list/src/lib/utils/market-utils.ts index e58fc86c1..2af9ec6c0 100644 --- a/libs/market-list/src/lib/utils/market-utils.ts +++ b/libs/market-list/src/lib/utils/market-utils.ts @@ -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) => { diff --git a/libs/oracles/.eslintrc.json b/libs/oracles/.eslintrc.json index 734ddacee..de2a9b877 100644 --- a/libs/oracles/.eslintrc.json +++ b/libs/oracles/.eslintrc.json @@ -1,6 +1,6 @@ { "extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"], - "ignorePatterns": ["!**/*"], + "ignorePatterns": ["!**/*", "__generated__", "__generated___"], "overrides": [ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], diff --git a/libs/oracles/.storybook/main.js b/libs/oracles/.storybook/main.js new file mode 100644 index 000000000..01ae9b323 --- /dev/null +++ b/libs/oracles/.storybook/main.js @@ -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; + }, +}; diff --git a/libs/oracles/.storybook/preview-head.html b/libs/oracles/.storybook/preview-head.html new file mode 100644 index 000000000..dd2e70030 --- /dev/null +++ b/libs/oracles/.storybook/preview-head.html @@ -0,0 +1 @@ + diff --git a/libs/oracles/.storybook/preview.js b/libs/oracles/.storybook/preview.js new file mode 100644 index 000000000..59e6d1d77 --- /dev/null +++ b/libs/oracles/.storybook/preview.js @@ -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
{children}
; +}; + +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' ? ( + <> +
+ + + +
+
+ + + +
+ + ) : ( + + + + ); +}; + +export const decorators = [ThemeWrapper]; diff --git a/libs/oracles/.storybook/tsconfig.json b/libs/oracles/.storybook/tsconfig.json new file mode 100644 index 000000000..a33db6100 --- /dev/null +++ b/libs/oracles/.storybook/tsconfig.json @@ -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"] +} diff --git a/libs/oracles/jest.config.ts b/libs/oracles/jest.config.ts index b08b7a5bc..aadf9082a 100644 --- a/libs/oracles/jest.config.ts +++ b/libs/oracles/jest.config.ts @@ -7,4 +7,5 @@ export default { }, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], coverageDirectory: '../../coverage/libs/oracles', + setupFilesAfterEnv: ['./src/setup-tests.ts'], }; diff --git a/libs/oracles/postcss.config.js b/libs/oracles/postcss.config.js new file mode 100644 index 000000000..cbdd9c22c --- /dev/null +++ b/libs/oracles/postcss.config.js @@ -0,0 +1,10 @@ +const { join } = require('path'); + +module.exports = { + plugins: { + tailwindcss: { + config: join(__dirname, 'tailwind.config.js'), + }, + autoprefixer: {}, + }, +}; diff --git a/libs/oracles/project.json b/libs/oracles/project.json index b796a2027..1b83c0def 100644 --- a/libs/oracles/project.json +++ b/libs/oracles/project.json @@ -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" + } } } } diff --git a/libs/oracles/src/index.ts b/libs/oracles/src/index.ts index ecc267fe3..f41a696fd 100644 --- a/libs/oracles/src/index.ts +++ b/libs/oracles/src/index.ts @@ -1,2 +1 @@ -export * from './lib/oracle-schema'; -export * from './lib/use-oracle-proofs'; +export * from './lib'; diff --git a/libs/oracles/src/lib/OracleSpecDataConnection.graphql b/libs/oracles/src/lib/OracleSpecDataConnection.graphql new file mode 100644 index 000000000..3fe50d671 --- /dev/null +++ b/libs/oracles/src/lib/OracleSpecDataConnection.graphql @@ -0,0 +1,18 @@ +query OracleSpecDataConnection($oracleSpecId: ID!) { + oracleSpec(oracleSpecId: $oracleSpecId) { + dataConnection { + edges { + node { + externalData { + data { + data { + name + value + } + } + } + } + } + } + } +} diff --git a/libs/oracles/src/lib/__generated__/OracleSpecDataConnection.ts b/libs/oracles/src/lib/__generated__/OracleSpecDataConnection.ts new file mode 100644 index 000000000..c977be66d --- /dev/null +++ b/libs/oracles/src/lib/__generated__/OracleSpecDataConnection.ts @@ -0,0 +1,61 @@ +import * as Types from '@vegaprotocol/types'; + +import { gql } from '@apollo/client'; +import * as Apollo from '@apollo/client'; +const defaultOptions = {} as const; +export type OracleSpecDataConnectionQueryVariables = Types.Exact<{ + oracleSpecId: Types.Scalars['ID']; +}>; + + +export type OracleSpecDataConnectionQuery = { __typename?: 'Query', oracleSpec?: { __typename?: 'OracleSpec', dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } } | null }; + + +export const OracleSpecDataConnectionDocument = gql` + query OracleSpecDataConnection($oracleSpecId: ID!) { + oracleSpec(oracleSpecId: $oracleSpecId) { + dataConnection { + edges { + node { + externalData { + data { + data { + name + value + } + } + } + } + } + } + } +} + `; + +/** + * __useOracleSpecDataConnectionQuery__ + * + * To run a query within a React component, call `useOracleSpecDataConnectionQuery` and pass it any options that fit your needs. + * When your component renders, `useOracleSpecDataConnectionQuery` returns an object from Apollo Client that contains loading, error, and data properties + * you can use to render your UI. + * + * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; + * + * @example + * const { data, loading, error } = useOracleSpecDataConnectionQuery({ + * variables: { + * oracleSpecId: // value for 'oracleSpecId' + * }, + * }); + */ +export function useOracleSpecDataConnectionQuery(baseOptions: Apollo.QueryHookOptions) { + const options = {...defaultOptions, ...baseOptions} + return Apollo.useQuery(OracleSpecDataConnectionDocument, options); + } +export function useOracleSpecDataConnectionLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) { + const options = {...defaultOptions, ...baseOptions} + return Apollo.useLazyQuery(OracleSpecDataConnectionDocument, options); + } +export type OracleSpecDataConnectionQueryHookResult = ReturnType; +export type OracleSpecDataConnectionLazyQueryHookResult = ReturnType; +export type OracleSpecDataConnectionQueryResult = Apollo.QueryResult; \ No newline at end of file diff --git a/libs/oracles/src/lib/__generated__/index.ts b/libs/oracles/src/lib/__generated__/index.ts new file mode 100644 index 000000000..c1a71b9a0 --- /dev/null +++ b/libs/oracles/src/lib/__generated__/index.ts @@ -0,0 +1 @@ +export * from './OracleSpecDataConnection'; diff --git a/libs/oracles/src/lib/components/index.ts b/libs/oracles/src/lib/components/index.ts new file mode 100644 index 000000000..8706f7f57 --- /dev/null +++ b/libs/oracles/src/lib/components/index.ts @@ -0,0 +1 @@ +export * from './oracle-basic-profile'; diff --git a/libs/oracles/src/lib/components/oracle-basic-profile/index.ts b/libs/oracles/src/lib/components/oracle-basic-profile/index.ts new file mode 100644 index 000000000..f7202883f --- /dev/null +++ b/libs/oracles/src/lib/components/oracle-basic-profile/index.ts @@ -0,0 +1,2 @@ +export * from './oracle-basic-profile.stories'; +export * from './oracle-basic-profile'; diff --git a/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.spec.tsx b/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.spec.tsx new file mode 100644 index 000000000..1a513e7dd --- /dev/null +++ b/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.spec.tsx @@ -0,0 +1,45 @@ +import { OracleBasicProfile } from './oracle-basic-profile'; +import type { Provider } from '../../oracle-schema'; +import { render, screen } from '@testing-library/react'; + +describe('OracleBasicProfile', () => { + const testProvider = { + name: 'Test oracle', + url: 'https://zombo.com', + description_markdown: + 'Some markdown describing the oracle provider.\n\nTwitter: @FacesPics2\n', + oracle: { + status: 'GOOD', + status_reason: '', + first_verified: '2023-02-28T00:00:00.000Z', + last_verified: '2023-02-28T00:00:00.000Z', + type: 'eth_address', + eth_address: '0xfCEAdAFab14d46e20144F48824d0C09B1a03F2BC', + }, + proofs: [ + { + format: 'signed_message', + available: true, + type: 'eth_address', + eth_address: '0x949AF81E51D57831AE52591d17fBcdd1014a5f52', + message: 'SOMEHEX', + }, + ], + github_link: + 'https://github.com/vegaprotocol/well-known/blob/main/oracle-providers/eth_address-0xfCEAdAFab14d46e20144F48824d0C09B1a03F2BC.toml', + } as Provider; + + it('should render successfully', () => { + const component = ; + expect(component).toBeTruthy(); + }); + + it('should render the name', () => { + render(); + expect(screen.getByTestId('provider-name')).toHaveTextContent( + 'Test oracle' + ); + expect(screen.getByTestId('verified-proofs')).toHaveTextContent('1'); + expect(screen.getByTestId('signed-proofs')).toHaveTextContent('1'); + }); +}); diff --git a/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.stories.tsx b/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.stories.tsx new file mode 100644 index 000000000..4265a3424 --- /dev/null +++ b/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.stories.tsx @@ -0,0 +1,41 @@ +import type { Story, Meta } from '@storybook/react'; +import { OracleBasicProfile } from './oracle-basic-profile'; + +export default { + component: OracleBasicProfile, + title: 'OracleBasicProfile', +} as Meta; + +const Template: Story = (args) => ( + +); + +export const Default = Template.bind({}); + +Default.args = { + provider: { + name: 'Test oracle', + url: 'https://zombo.com', + description_markdown: + 'Some markdown describing the oracle provider.\n\nTwitter: @FacesPics2\n', + oracle: { + status: 'GOOD', + status_reason: '', + first_verified: '2023-02-28T00:00:00.000Z', + last_verified: '2023-02-28T00:00:00.000Z', + type: 'eth_address', + eth_address: '0xfCEAdAFab14d46e20144F48824d0C09B1a03F2BC', + }, + proofs: [ + { + format: 'signed_message', + available: true, + type: 'eth_address', + eth_address: '0x949AF81E51D57831AE52591d17fBcdd1014a5f52', + message: 'SOMEHEX', + }, + ], + github_link: + 'https://github.com/vegaprotocol/well-known/blob/main/oracle-providers/eth_address-0xfCEAdAFab14d46e20144F48824d0C09B1a03F2BC.toml', + }, +}; diff --git a/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.tsx b/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.tsx new file mode 100644 index 000000000..3da3d0ea9 --- /dev/null +++ b/libs/oracles/src/lib/components/oracle-basic-profile/oracle-basic-profile.tsx @@ -0,0 +1,158 @@ +import { t } from '@vegaprotocol/i18n'; +import type { Provider } from '../../oracle-schema'; +import { + ExternalLink, + Icon, + Intent, + Link, + VegaIcon, + VegaIconNames, +} from '@vegaprotocol/ui-toolkit'; +import type { IconName } from '@blueprintjs/icons'; +import { IconNames } from '@blueprintjs/icons'; +import classNames from 'classnames'; + +const getVerifiedStatusIcon = (provider: Provider) => { + const getIconIntent = () => { + switch (provider.oracle.status) { + case 'GOOD': + return { icon: IconNames.TICK_CIRCLE, intent: Intent.Success }; + case 'RETIRED': + return { icon: IconNames.MOON, intent: Intent.None }; + case 'UNKNOWN': + return { icon: IconNames.HELP, intent: Intent.Primary }; + case 'MALICIOUS': + return { icon: IconNames.ERROR, intent: Intent.Danger }; + case 'SUSPICIOUS': + return { icon: IconNames.ERROR, intent: Intent.Danger }; + case 'COMPROMISED': + return { icon: IconNames.ERROR, intent: Intent.Danger }; + default: + return { icon: IconNames.HELP, intent: Intent.Primary }; + } + }; + + if (!provider.oracle.first_verified || !provider.oracle.last_verified) { + return { + message: t('Not verified'), + ...getIconIntent(), + }; + } + + const lastVerified = provider.oracle.last_verified + ? new Date(provider.oracle.last_verified) + : new Date(provider.oracle.first_verified); + return { + ...getIconIntent(), + message: t( + 'Verified since %s', + lastVerified.toLocaleDateString(undefined, { + year: 'numeric', + month: 'long', + }) + ), + }; +}; + +export const OracleBasicProfile = ({ provider }: { provider: Provider }) => { + const { icon, message, intent } = getVerifiedStatusIcon(provider); + + const verifiedProofs = provider.proofs.filter( + (proof) => proof.available === true + ); + + const signedProofs = provider.proofs.filter( + (proof) => proof.format === 'signed_message' && proof.available === true + ); + + const links = provider.proofs + .filter((proof) => proof.format === 'url' && proof.available === true) + .map((proof) => ({ + ...proof, + url: 'url' in proof ? proof.url : '', + icon: getLinkIcon(proof.type), + })); + + return ( + <> + + {provider.url && ( + + + + {provider.name} + + + ({verifiedProofs.length}) + + + + )} + + + + +

{message}

+

+ {t('Involved in %s %s', [ + signedProofs.length.toString(), + signedProofs.length !== 1 ? t('markets') : t('market'), + ])} +

+ {links.length > 0 && ( +
+ {links.map((link) => ( + + + + + + {link.type}{' '} + + + + ))} +
+ )} + + ); +}; + +export const getLinkIcon = (type: string) => { + switch (type) { + case 'twitter': + return VegaIconNames.TWITTER; + case 'github': + return VegaIconNames.GLOBE; + case 'linkedin': + return VegaIconNames.LINKEDIN; + default: + return VegaIconNames.GLOBE; + } +}; diff --git a/libs/oracles/src/lib/index.ts b/libs/oracles/src/lib/index.ts new file mode 100644 index 000000000..e45917945 --- /dev/null +++ b/libs/oracles/src/lib/index.ts @@ -0,0 +1,6 @@ +export * from './__generated__'; +export * from './components'; +export * from './oracle-schema'; +export * from './oracle-spec-data-connection.mock'; +export * from './use-oracle-proofs'; +export * from './use-oracle-spec-binding-data'; diff --git a/libs/oracles/src/lib/oracle-data.json b/libs/oracles/src/lib/oracle-data.json new file mode 100644 index 000000000..284d06d54 --- /dev/null +++ b/libs/oracles/src/lib/oracle-data.json @@ -0,0 +1,73 @@ +[ + { + "name": "Test oracle", + "url": "https://zombo.com", + "description_markdown": "Some markdown describing the oracle provider.\n\nTwitter: @FacesPics2\n", + "oracle": { + "status": "GOOD", + "status_reason": "", + "first_verified": "2023-02-28T00:00:00.000Z", + "last_verified": "2023-02-28T00:00:00.000Z", + "type": "eth_address", + "eth_address": "0xfCEAdAFab14d46e20144F48824d0C09B1a03F2BC" + }, + "proofs": [ + { + "format": "signed_message", + "available": true, + "type": "eth_address", + "eth_address": "0x949AF81E51D57831AE52591d17fBcdd1014a5f52", + "message": "SOMEHEX" + } + ], + "github_link": "https://github.com/vegaprotocol/well-known/blob/main/oracle-providers/eth_address-0xfCEAdAFab14d46e20144F48824d0C09B1a03F2BC.toml" + }, + { + "name": "Vega Admin Oracle for Testnet", + "url": "https://fairground.wtf", + "description_markdown": "The Vega Fairground admin oracle, uses a json file to settle based on Binance Spot price.\nE.g. in case the market is BTC/USDC the spot price for BTC/USDC on Binance will be used.\n\nTwitter: @VegaFairground\n", + "oracle": { + "status": "GOOD", + "status_reason": "", + "first_verified": "2022-01-01T00:00:00.000Z", + "last_verified": "2022-12-31T00:00:00.000Z", + "type": "public_key", + "public_key": "69464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f" + }, + "proofs": [ + { + "format": "url", + "available": true, + "type": "twitter", + "url": "https://twitter.com/vegaprotocol/status/956833487230730241" + }, + { + "format": "url", + "available": true, + "type": "web", + "url": "https://fairground.wtf/" + }, + { + "format": "url", + "available": true, + "type": "github", + "url": "https://github.com" + }, + { + "format": "signed_message", + "available": true, + "type": "public_key", + "public_key": "69464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f", + "message": "SOMEHEX" + }, + { + "format": "signed_message", + "available": true, + "type": "eth_address", + "eth_address": "0x0b38D0e7391CF427d309991A110a84daF37114eF", + "message": "SOMEHEX" + } + ], + "github_link": "https://github.com/vegaprotocol/well-known/blob/main/oracle-providers/public_key-69464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f.toml" + } +] diff --git a/libs/oracles/src/lib/oracle-spec-data-connection.mock.ts b/libs/oracles/src/lib/oracle-spec-data-connection.mock.ts new file mode 100644 index 000000000..3341ec9ce --- /dev/null +++ b/libs/oracles/src/lib/oracle-spec-data-connection.mock.ts @@ -0,0 +1,38 @@ +import merge from 'lodash/merge'; +import type { PartialDeep } from 'type-fest'; +import type { OracleSpecDataConnectionQuery } from './__generated__/OracleSpecDataConnection'; +import type { OracleData } from '@vegaprotocol/types'; + +export function createDataConnection( + override?: PartialDeep +): OracleData { + const defaultDataConnection = { + externalData: { + data: { + broadcastAt: new Date().toISOString(), + data: [ + { + name: 'settlement-data-property', + value: '100', + }, + ], + }, + }, + }; + + return merge(defaultDataConnection, override); +} + +export function oracleSpecDataConnectionQuery( + override?: PartialDeep +): OracleSpecDataConnectionQuery { + const defaultResult = { + oracleSpec: { + dataConnection: { + edges: [{ node: createDataConnection() }], + }, + }, + }; + + return merge(defaultResult, override); +} diff --git a/libs/oracles/src/lib/use-oracle-spec-binding-data.spec.tsx b/libs/oracles/src/lib/use-oracle-spec-binding-data.spec.tsx new file mode 100644 index 000000000..57c19d63e --- /dev/null +++ b/libs/oracles/src/lib/use-oracle-spec-binding-data.spec.tsx @@ -0,0 +1,105 @@ +import { renderHook, waitFor } from '@testing-library/react'; +import type { MockedResponse } from '@apollo/client/testing'; +import { MockedProvider } from '@apollo/client/testing'; +import type { ReactNode } from 'react'; +import { useOracleSpecBindingData } from './use-oracle-spec-binding-data'; +import type { Property } from '@vegaprotocol/types'; +import type { OracleSpecDataConnectionQuery } from './__generated__/OracleSpecDataConnection'; +import { OracleSpecDataConnectionDocument } from './__generated__/OracleSpecDataConnection'; + +describe('useSettlementPrice', () => { + const setup = ( + oracleSpecId: string, + specBinding: string, + mocks: MockedResponse[] + ) => { + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + return renderHook( + () => useOracleSpecBindingData(oracleSpecId, specBinding), + { + wrapper, + } + ); + }; + const createMock = ( + id: string, + property: Property + ): MockedResponse => { + return { + request: { + query: OracleSpecDataConnectionDocument, + variables: { + oracleSpecId: id, + }, + }, + result: { + data: { + oracleSpec: { + dataConnection: { + edges: [ + { + node: { + externalData: { + data: { + data: [property], + }, + }, + }, + }, + ], + }, + }, + }, + }, + }; + }; + + it('should returns the matching value for the spec binding', async () => { + const oracleSpecId = 'oracle-spec-id'; + const specBinding = 'spec-binding'; + const value = '123456'; + const property = { + __typename: 'Property' as const, + name: specBinding, + value, + }; + const mock = createMock(oracleSpecId, property); + + const { result } = setup(oracleSpecId, specBinding, [mock]); + + expect(result.current.property).toEqual(undefined); + expect(result.current.data).toBe(undefined); + expect(result.current.loading).toBe(true); + expect(result.current.error).toBe(undefined); + + await waitFor(() => { + expect(result.current.property).toEqual(property); + expect(result.current.loading).toBe(false); + }); + }); + + it('returns nothing if matching poperty not found', async () => { + const oracleSpecId = 'oracle-spec-id'; + const specBinding = 'spec-binding'; + const value = '123456'; + const property = { + __typename: 'Property' as const, + name: 'does not match', + value, + }; + const mock = createMock(oracleSpecId, property); + + const { result } = setup(oracleSpecId, specBinding, [mock]); + expect(result.current.property).toEqual(undefined); + expect(result.current.data).toBe(undefined); + expect(result.current.loading).toBe(true); + expect(result.current.error).toBe(undefined); + + await waitFor(() => { + expect(result.current.property).toEqual(undefined); + expect(result.current.loading).toBe(false); + }); + }); +}); diff --git a/libs/oracles/src/lib/use-oracle-spec-binding-data.ts b/libs/oracles/src/lib/use-oracle-spec-binding-data.ts new file mode 100644 index 000000000..fa9afac50 --- /dev/null +++ b/libs/oracles/src/lib/use-oracle-spec-binding-data.ts @@ -0,0 +1,26 @@ +import { useOracleSpecDataConnectionQuery } from './__generated__/OracleSpecDataConnection'; + +export const useOracleSpecBindingData = ( + oracleSpecId: string | undefined, + specBinding: string | undefined +) => { + const { data, loading, error } = useOracleSpecDataConnectionQuery({ + variables: { + oracleSpecId: oracleSpecId || '', + }, + skip: !oracleSpecId, + }); + + const dataConnectionEdges = data?.oracleSpec?.dataConnection.edges; + const firstDataConnection = dataConnectionEdges?.[0]?.node; + const property = firstDataConnection?.externalData.data.data?.find( + (d) => d.name === specBinding + ); + + return { + property, + data, + loading, + error, + }; +}; diff --git a/libs/oracles/src/setup-tests.ts b/libs/oracles/src/setup-tests.ts new file mode 100644 index 000000000..68773380a --- /dev/null +++ b/libs/oracles/src/setup-tests.ts @@ -0,0 +1,4 @@ +import '@testing-library/jest-dom'; +import ResizeObserver from 'resize-observer-polyfill'; + +global.ResizeObserver = ResizeObserver; diff --git a/libs/oracles/tailwind.config.js b/libs/oracles/tailwind.config.js new file mode 100644 index 000000000..20447f23e --- /dev/null +++ b/libs/oracles/tailwind.config.js @@ -0,0 +1,18 @@ +const { join } = require('path'); +const { createGlobPatternsForDependencies } = require('@nrwl/next/tailwind'); +const theme = require('../tailwindcss-config/src/theme'); +const vegaCustomClasses = require('../tailwindcss-config/src/vega-custom-classes'); + +module.exports = { + content: [ + join(__dirname, 'src/**/*.{ts,tsx,html,mdx}'), + join(__dirname, 'src/utils/shared.ts'), + join(__dirname, '.storybook/preview.js'), + ...createGlobPatternsForDependencies(__dirname), + ], + darkMode: 'class', + theme: { + extend: theme, + }, + plugins: [vegaCustomClasses], +}; diff --git a/libs/oracles/tsconfig.json b/libs/oracles/tsconfig.json index 4c089585e..36b41cfd5 100644 --- a/libs/oracles/tsconfig.json +++ b/libs/oracles/tsconfig.json @@ -8,11 +8,10 @@ "forceConsistentCasingInFileNames": true, "strict": true, "noImplicitOverride": true, - "noPropertyAccessFromIndexSignature": true, + "noPropertyAccessFromIndexSignature": false, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true }, - "files": [], "include": [], "references": [ { @@ -20,6 +19,9 @@ }, { "path": "./tsconfig.spec.json" + }, + { + "path": "./.storybook/tsconfig.json" } ] } diff --git a/libs/oracles/tsconfig.lib.json b/libs/oracles/tsconfig.lib.json index af84f21cf..6a440c7bd 100644 --- a/libs/oracles/tsconfig.lib.json +++ b/libs/oracles/tsconfig.lib.json @@ -9,7 +9,6 @@ "../../node_modules/@nrwl/react/typings/image.d.ts" ], "exclude": [ - "jest.config.ts", "**/*.spec.ts", "**/*.test.ts", "**/*.spec.tsx", @@ -17,7 +16,12 @@ "**/*.spec.js", "**/*.test.js", "**/*.spec.jsx", - "**/*.test.jsx" + "**/*.test.jsx", + "**/*.stories.ts", + "**/*.stories.js", + "**/*.stories.jsx", + "**/*.stories.tsx", + "jest.config.ts" ], "include": ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx"] } diff --git a/libs/oracles/tsconfig.spec.json b/libs/oracles/tsconfig.spec.json index ff08addd6..ba70e5966 100644 --- a/libs/oracles/tsconfig.spec.json +++ b/libs/oracles/tsconfig.spec.json @@ -3,10 +3,9 @@ "compilerOptions": { "outDir": "../../dist/out-tsc", "module": "commonjs", - "types": ["jest", "node"] + "types": ["jest", "node", "@testing-library/jest-dom"] }, "include": [ - "jest.config.ts", "**/*.test.ts", "**/*.spec.ts", "**/*.test.tsx", @@ -15,6 +14,9 @@ "**/*.spec.js", "**/*.test.jsx", "**/*.spec.jsx", - "**/*.d.ts" + "**/*.d.ts", + "jest.config.ts", + "../../index.d.ts", + "src/lib/use-oracle-spec-binding-data.spec.tsx" ] } diff --git a/libs/orders/src/lib/components/mocks/generate-orders.ts b/libs/orders/src/lib/components/mocks/generate-orders.ts index 9b033885c..a84ec7033 100644 --- a/libs/orders/src/lib/components/mocks/generate-orders.ts +++ b/libs/orders/src/lib/components/mocks/generate-orders.ts @@ -49,7 +49,17 @@ export const generateOrder = (partialOrder?: PartialDeep) => { name: 'XYZ', }, dataSourceSpecForTradingTermination: { - id: '', + __typename: 'DataSourceSpec', + id: 'oracleId', + }, + dataSourceSpecForSettlementData: { + __typename: 'DataSourceSpec', + id: 'oracleId', + }, + dataSourceSpecBinding: { + __typename: 'DataSourceSpecToFutureBinding', + tradingTerminationProperty: 'trading-termination-property', + settlementDataProperty: 'settlement-data-property', }, }, }, diff --git a/libs/orders/src/lib/components/order-list/order-list.tsx b/libs/orders/src/lib/components/order-list/order-list.tsx index 2b55391d9..8c75534d1 100644 --- a/libs/orders/src/lib/components/order-list/order-list.tsx +++ b/libs/orders/src/lib/components/order-list/order-list.tsx @@ -11,7 +11,7 @@ import BigNumber from 'bignumber.js'; import type { ForwardedRef } from 'react'; import { memo, forwardRef } from 'react'; import { - AgGridDynamic as AgGrid, + AgGridLazy as AgGrid, SetFilter, DateRangeFilter, negativeClassNames, diff --git a/libs/positions/src/lib/positions-table.tsx b/libs/positions/src/lib/positions-table.tsx index 152fee096..0d7fc3cf9 100644 --- a/libs/positions/src/lib/positions-table.tsx +++ b/libs/positions/src/lib/positions-table.tsx @@ -10,7 +10,7 @@ import type { } from '@vegaprotocol/datagrid'; import { ProgressBarCell } from '@vegaprotocol/datagrid'; import { - AgGridDynamic as AgGrid, + AgGridLazy as AgGrid, DateRangeFilter, PriceFlashCell, signedNumberCssClass, diff --git a/libs/proposals/src/lib/proposals-list/proposals-list.tsx b/libs/proposals/src/lib/proposals-list/proposals-list.tsx index 6e157ce95..1e421679a 100644 --- a/libs/proposals/src/lib/proposals-list/proposals-list.tsx +++ b/libs/proposals/src/lib/proposals-list/proposals-list.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { AsyncRenderer } from '@vegaprotocol/ui-toolkit'; -import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid'; +import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid'; import { useDataProvider } from '@vegaprotocol/react-helpers'; import { t } from '@vegaprotocol/i18n'; import * as Types from '@vegaprotocol/types'; @@ -9,13 +9,6 @@ import type { AgGridReact } from 'ag-grid-react'; import { useColumnDefs } from './use-column-defs'; import type { ProposalListFieldsFragment } from '../proposals-data-provider/__generated__/Proposals'; -// prevent cutting filter windows by auto-height layout -const CUSTOM_GRID_STYLES = ` - .ag-layout-auto-height { - min-height: 200px !important; - } -`; - export const getNewMarketProposals = (data: ProposalListFieldsFragment[]) => data.filter((proposal) => [ @@ -58,7 +51,6 @@ export const ProposalsList = () => { suppressLoadingOverlay suppressNoRowsOverlay onFilterChanged={onFilterChanged} - customThemeParams={CUSTOM_GRID_STYLES} />
{ + it('should return proper values', () => { + const ret = renderHook(() => usePaneLayout({ id: 'testid' })); + expect(ret.result.current[0]).toStrictEqual([]); + expect(ret.result.current[1]).toStrictEqual(expect.any(Function)); + }); + it('setter should change value', async () => { + const ret = renderHook(() => usePaneLayout({ id: 'testid' })); + await act(() => { + ret.result.current[1]([100, 50, 50]); + }); + await waitFor(() => { + expect(ret.result.current[0]).toStrictEqual(['50%', '25%', '25%']); + }); + }); +}); diff --git a/libs/react-helpers/src/hooks/use-pane-layout.ts b/libs/react-helpers/src/hooks/use-pane-layout.ts new file mode 100644 index 000000000..69832407e --- /dev/null +++ b/libs/react-helpers/src/hooks/use-pane-layout.ts @@ -0,0 +1,47 @@ +import { useCallback } from 'react'; +import debounce from 'lodash/debounce'; +import { create } from 'zustand'; +import { persist } from 'zustand/middleware'; +import { immer } from 'zustand/middleware/immer'; + +const STORAGE_KEY = 'vega_pane_store'; +const PANELS_SET_DEBOUNCE_TIME = 300; + +export const usePaneLayoutStore = create<{ + sizes: Record; + valueSetter: (id: string, value: string[]) => void; +}>()( + persist( + immer((set) => ({ + sizes: {}, + valueSetter: (id, value) => + set((state) => { + state.sizes[id] = value; + return state; + }), + })), + { name: STORAGE_KEY } + ) +); + +interface UsePaneLayoutProps { + id: string; +} +export const usePaneLayout = ({ + id, +}: UsePaneLayoutProps): [string[], (sizes: number[]) => void] => { + const sizes = usePaneLayoutStore((store) => store.sizes[id]) || []; + const valueSetter = usePaneLayoutStore((store) => store.valueSetter); + // eslint-disable-next-line react-hooks/exhaustive-deps + const handleOnChange = useCallback( + debounce((args) => { + if (args.length) { + const all = args.reduce((agg: number, item: number) => agg + item, 0); + const sizesArr = args.map((arg: number) => `${(arg / all) * 100}%`); + valueSetter(id, sizesArr); + } + }, PANELS_SET_DEBOUNCE_TIME), + [valueSetter, id] + ); + return [sizes, handleOnChange]; +}; diff --git a/libs/trades/src/lib/trades-table.tsx b/libs/trades/src/lib/trades-table.tsx index fe1aa9edd..1c06bdea0 100644 --- a/libs/trades/src/lib/trades-table.tsx +++ b/libs/trades/src/lib/trades-table.tsx @@ -5,7 +5,7 @@ import type { VegaICellRendererParams, VegaValueFormatterParams, } from '@vegaprotocol/datagrid'; -import { AgGridDynamic as AgGrid, NumericCell } from '@vegaprotocol/datagrid'; +import { AgGridLazy as AgGrid, NumericCell } from '@vegaprotocol/datagrid'; import { addDecimal, addDecimalsFormatNumber, diff --git a/libs/ui-toolkit/src/components/icon/icons/icon-forum.svg b/libs/ui-toolkit/src/components/icon/icons/icon-forum.svg new file mode 100644 index 000000000..3c91093f7 --- /dev/null +++ b/libs/ui-toolkit/src/components/icon/icons/icon-forum.svg @@ -0,0 +1,3 @@ + + + diff --git a/libs/ui-toolkit/src/components/icon/icons/icon-globe.svg b/libs/ui-toolkit/src/components/icon/icons/icon-globe.svg new file mode 100644 index 000000000..dbb191d13 --- /dev/null +++ b/libs/ui-toolkit/src/components/icon/icons/icon-globe.svg @@ -0,0 +1,3 @@ + + + diff --git a/libs/ui-toolkit/src/components/icon/icons/icon-linkedin.svg b/libs/ui-toolkit/src/components/icon/icons/icon-linkedin.svg new file mode 100644 index 000000000..7532ebce0 --- /dev/null +++ b/libs/ui-toolkit/src/components/icon/icons/icon-linkedin.svg @@ -0,0 +1,3 @@ + + + diff --git a/libs/ui-toolkit/src/components/icon/icons/icon-moon.svg b/libs/ui-toolkit/src/components/icon/icons/icon-moon.svg new file mode 100644 index 000000000..fe7feb598 --- /dev/null +++ b/libs/ui-toolkit/src/components/icon/icons/icon-moon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/libs/ui-toolkit/src/components/icon/icons/icon-question-mark.svg b/libs/ui-toolkit/src/components/icon/icons/icon-question-mark.svg new file mode 100644 index 000000000..db93e84ce --- /dev/null +++ b/libs/ui-toolkit/src/components/icon/icons/icon-question-mark.svg @@ -0,0 +1,3 @@ + + + diff --git a/libs/ui-toolkit/src/components/icon/icons/icon-twitter.svg b/libs/ui-toolkit/src/components/icon/icons/icon-twitter.svg new file mode 100644 index 000000000..d7e656b91 --- /dev/null +++ b/libs/ui-toolkit/src/components/icon/icons/icon-twitter.svg @@ -0,0 +1,3 @@ + + + diff --git a/libs/ui-toolkit/src/components/icon/vega-icons/svg-icons/icon-globe.tsx b/libs/ui-toolkit/src/components/icon/vega-icons/svg-icons/icon-globe.tsx index 64137f532..466499b75 100644 --- a/libs/ui-toolkit/src/components/icon/vega-icons/svg-icons/icon-globe.tsx +++ b/libs/ui-toolkit/src/components/icon/vega-icons/svg-icons/icon-globe.tsx @@ -8,8 +8,8 @@ export const IconGlobe = ({ size = 24 }: { size: number }) => { xmlns="http://www.w3.org/2000/svg" > diff --git a/libs/ui-toolkit/src/components/icon/vega-icons/vega-icon.tsx b/libs/ui-toolkit/src/components/icon/vega-icons/vega-icon.tsx index a5f497278..c82e7e229 100644 --- a/libs/ui-toolkit/src/components/icon/vega-icons/vega-icon.tsx +++ b/libs/ui-toolkit/src/components/icon/vega-icons/vega-icon.tsx @@ -5,7 +5,7 @@ import { VegaIconNameMap } from './vega-icon-record'; export interface VegaIconProps { name: VegaIconNames; - size?: 16 | 24 | 32; + size?: 8 | 10 | 12 | 13 | 14 | 16 | 24 | 32; } export const VegaIcon = ({ size = 16, name }: VegaIconProps) => { diff --git a/libs/utils/src/lib/format/date.ts b/libs/utils/src/lib/format/date.ts index 151d34410..46518d9f2 100644 --- a/libs/utils/src/lib/format/date.ts +++ b/libs/utils/src/lib/format/date.ts @@ -1,5 +1,6 @@ import once from 'lodash/once'; import { getUserLocale } from '../get-user-locale'; +import { utcToZonedTime, format as tzFormat } from 'date-fns-tz'; export const isValidDate = (date: Date) => date instanceof Date && !isNaN(date.getTime()); @@ -51,3 +52,16 @@ export const formatForInput = (date: Date) => { return `${year}-${month}-${day}T${hours}:${minutes}:${secs}`; }; + +/** Format a user's local date and time with the time zone abbreviation */ +export const formatDateWithLocalTimezone = ( + date: Date, + formatStr = 'dd MMMM yyyy HH:mm (z)' +) => { + const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; + const localDatetime = utcToZonedTime(date, userTimeZone); + + return tzFormat(localDatetime, formatStr, { + timeZone: userTimeZone, + }); +}; diff --git a/libs/wallet/src/connect-dialog/connect-dialog.spec.tsx b/libs/wallet/src/connect-dialog/connect-dialog.spec.tsx index f4ca36a07..60aed606c 100644 --- a/libs/wallet/src/connect-dialog/connect-dialog.spec.tsx +++ b/libs/wallet/src/connect-dialog/connect-dialog.spec.tsx @@ -120,7 +120,11 @@ describe('VegaConnectDialog', () => { .mockImplementation(() => Promise.resolve({ success: true, error: null }) ); - + jest + .spyOn(connectors.rest, 'connect') + .mockImplementation(() => + Promise.resolve([{ publicKey: 'pubkey', name: 'test key 1' }]) + ); render(generateJSX()); // Switches to rest form fireEvent.click(await screen.findByText('Hosted Fairground wallet')); @@ -138,10 +142,11 @@ describe('VegaConnectDialog', () => { await act(async () => { fireEvent.submit(screen.getByTestId('rest-connector-form')); }); + await waitFor(() => { + expect(spy).toHaveBeenCalledWith(fields); - expect(spy).toHaveBeenCalledWith(fields); - - expect(mockCloseVegaDialog).toHaveBeenCalled(); + expect(mockCloseVegaDialog).toHaveBeenCalled(); + }); }); it('handles failed connection', async () => { diff --git a/libs/wallet/src/setup-tests.ts b/libs/wallet/src/setup-tests.ts index 7b0828bfa..68773380a 100644 --- a/libs/wallet/src/setup-tests.ts +++ b/libs/wallet/src/setup-tests.ts @@ -1 +1,4 @@ import '@testing-library/jest-dom'; +import ResizeObserver from 'resize-observer-polyfill'; + +global.ResizeObserver = ResizeObserver; diff --git a/libs/withdraws/src/lib/withdraw-form-container.spec.tsx b/libs/withdraws/src/lib/withdraw-form-container.spec.tsx index c1e625909..5ca9483e9 100644 --- a/libs/withdraws/src/lib/withdraw-form-container.spec.tsx +++ b/libs/withdraws/src/lib/withdraw-form-container.spec.tsx @@ -148,7 +148,17 @@ describe('WithdrawFormContainer', () => { decimals: 5, }, dataSourceSpecForTradingTermination: { - id: '', + __typename: 'DataSourceSpec', + id: 'oracleId', + }, + dataSourceSpecForSettlementData: { + __typename: 'DataSourceSpec', + id: 'oracleId', + }, + dataSourceSpecBinding: { + __typename: 'DataSourceSpecToFutureBinding', + tradingTerminationProperty: 'trading-termination-property', + settlementDataProperty: 'settlement-data-property', }, quoteName: 'USD', }, diff --git a/libs/withdraws/src/lib/withdrawals-table.tsx b/libs/withdraws/src/lib/withdrawals-table.tsx index 852ac6406..2d6ed18d7 100644 --- a/libs/withdraws/src/lib/withdrawals-table.tsx +++ b/libs/withdraws/src/lib/withdrawals-table.tsx @@ -10,7 +10,7 @@ import { import { useBottomPlaceholder } from '@vegaprotocol/react-helpers'; import { t } from '@vegaprotocol/i18n'; import { ButtonLink } from '@vegaprotocol/ui-toolkit'; -import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid'; +import { AgGridLazy as AgGrid } from '@vegaprotocol/datagrid'; import type { TypedDataAgGrid, VegaICellRendererParams, diff --git a/nx.json b/nx.json index c0d4efa30..53753cc36 100644 --- a/nx.json +++ b/nx.json @@ -24,7 +24,8 @@ "echo $NX_TENDERMINT_WEBSOCKET_URL", "echo $NX_USE_ENV_OVERRIDES", "echo $NX_ETHEREUM_PROVIDER_URL" - ] + ], + "url": "https://cloud.nx.app" } } }, diff --git a/package.json b/package.json index 35ba287e7..721c29aed 100644 --- a/package.json +++ b/package.json @@ -56,6 +56,7 @@ "classnames": "^2.3.1", "core-js": "^3.6.5", "date-fns": "^2.28.0", + "date-fns-tz": "^2.0.0", "duration-js": "^4.0.0", "ethers": "^5.6.0", "graphql": "^15.7.2", @@ -154,8 +155,8 @@ "autoprefixer": "10.4.8", "babel-jest": "27.5.1", "babel-loader": "8.1.0", - "cypress-mochawesome-reporter": "^3.3.0", "cypress": "^12.9.0", + "cypress-mochawesome-reporter": "^3.3.0", "cypress-real-events": "^1.7.6", "dotenv": "^16.0.1", "eslint": "8.15.0", @@ -195,7 +196,7 @@ "ts-jest": "27.1.4", "ts-node": "10.9.1", "tslib": "^2.0.0", - "type-fest": "^2.12.2", + "type-fest": "^3.8.0", "typescript": "^5.0.4", "url-loader": "^3.0.0" }, diff --git a/yarn.lock b/yarn.lock index 0bfb9d0d5..e7e9b910f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12070,6 +12070,11 @@ dataloader@2.1.0: resolved "https://registry.yarnpkg.com/dataloader/-/dataloader-2.1.0.tgz#c69c538235e85e7ac6c6c444bae8ecabf5de9df7" integrity sha512-qTcEYLen3r7ojZNgVUaRggOI+KM7jrKxXeSHhogh/TWxYMeONEMqY+hmkobiYQozsGIyg9OYVzO4ZIfoB4I0pQ== +date-fns-tz@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/date-fns-tz/-/date-fns-tz-2.0.0.tgz#1b14c386cb8bc16fc56fe333d4fc34ae1d1099d5" + integrity sha512-OAtcLdB9vxSXTWHdT8b398ARImVwQMyjfYGkKD2zaGpHseG2UPHbHjXELReErZFxWdSLph3c2zOaaTyHfOhERQ== + date-fns@^1.27.2: version "1.30.1" resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-1.30.1.tgz#2e71bf0b119153dbb4cc4e88d9ea5acfb50dc05c" @@ -23637,10 +23642,10 @@ type-fest@^0.8.1: resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== -type-fest@^2.12.2: - version "2.19.0" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.19.0.tgz#88068015bb33036a598b952e55e9311a60fd3a9b" - integrity sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA== +type-fest@^3.8.0: + version "3.8.0" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-3.8.0.tgz#ce80d1ca7c7d11c5540560999cbd410cb5b3a385" + integrity sha512-FVNSzGQz9Th+/9R6Lvv7WIAkstylfHN2/JYxkyhhmKFYh9At2DST8t6L6Lref9eYO8PXFTfG9Sg1Agg0K3vq3Q== type-is@~1.6.18: version "1.6.18"