Compare commits

...
Author SHA1 Message Date
Dariusz Majcherczyk c1db25022d test: merge yarn 2023-04-20 19:23:48 +02:00
Sam KeenandDexter b0f1aeedae fix(governance): withdrawals bug (#3443)
Co-authored-by: Dexter <dexter.edwards93@gmail.com>
2023-04-20 17:18:17 +01:00
Joe Tsang da59e83b19 test(governance): e2e tests for rewards pagination (#3473) 2023-04-20 16:48:42 +01:00
Art 360624282d chore(web3): wallet connect v2 (#3324) 2023-04-20 17:20:59 +02:00
Dariusz Majcherczyk 7b4a3850e0 test: merge branch 2023-04-20 16:59:23 +02:00
Dariusz Majcherczyk 3965df8f13 Merge branch 'develop' into test/mocha-reporter-v2 2023-04-20 15:59:00 +02:00
Dariusz Majcherczyk bd7bd1b99e test: revert vegacapsule logs 2023-04-20 15:29:29 +02:00
dexturr 9e054c7c85 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-20 12:09:40 +00:00
m.ray 911e927ab0 fix(wallet): fetch new keys without re-connecting the wallet (#3467) 2023-04-20 13:56:48 +02:00
ArtandMikołaj Młodzikowski e4a51061a3 chore(ci): bump typescript (#3444)
Co-authored-by: Mikołaj Młodzikowski <mikolaj.mlodzikowski@gmail.com>
2023-04-20 11:56:33 +00:00
Dariusz Majcherczyk 008857e346 test: revert back 2023-04-20 11:38:30 +02:00
Bartłomiej Głownia c15051d457 fix(trading): refactor market info accordion to avoid remount on candle reload (#3447) 2023-04-20 11:32:09 +02:00
Sam Keen 460ccdb3a2 feat(governance): associate form associate link (#3468) 2023-04-20 10:16:52 +01:00
dexturr 959fb9cf62 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-20 06:07:00 +00:00
dexturr 2c7170d0e9 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-20 00:15:44 +00:00
Dariusz Majcherczyk e54ceb0807 test: change path 2023-04-19 20:52:23 +02:00
dexturr 8a28a4afd4 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-19 18:07:06 +00:00
Dariusz Majcherczyk bfbb7351c9 test: added report options 2023-04-19 18:53:09 +02:00
Dariusz Majcherczyk 7f4bc4a29a test: retries temporary commented 2023-04-19 18:10:43 +02:00
Dariusz Majcherczyk e5310da67b test: update project name 2023-04-19 17:09:53 +02:00
Dariusz Majcherczyk e5d731e323 test: trigger fail 2023-04-19 13:57:09 +02:00
Dariusz Majcherczyk 05112b19f9 test: update path 2023-04-19 12:22:30 +02:00
Dariusz Majcherczyk 2b66263caf test: update gitignore 2023-04-19 00:26:50 +02:00
Dariusz Majcherczyk fe35f89499 test: mocha reporter for e2e tests 2023-04-19 00:01:40 +02:00
111 changed files with 4277 additions and 2066 deletions
+2 -2
View File
@@ -26,7 +26,7 @@ jobs:
with:
path: node_modules
key: ${{ runner.os }}-cache-node-modules-${{ hashFiles('yarn.lock') }}
# comment out "resotre-keys" if you need to rebuild yarn from 0
# comment out "restore-keys" if you need to rebuild yarn from 0
restore-keys: |
${{ runner.os }}-cache-node-modules-
@@ -50,7 +50,7 @@ jobs:
secrets: inherit
lint-test-build:
timeout-minutes: 20
timeout-minutes: 35
needs: node-modules
runs-on: ubuntu-22.04
name: '(CI) lint + unit test + build'
+5 -3
View File
@@ -20,7 +20,7 @@ jobs:
project: ${{ fromJSON(inputs.projects) }}
name: ${{ matrix.project }}
runs-on: self-hosted-runner
timeout-minutes: 30
timeout-minutes: 40
steps:
# Checks if skip cache was requested
- name: Set skip-nx-cache flag
@@ -91,5 +91,7 @@ jobs:
- uses: actions/upload-artifact@v3
if: ${{ failure() }}
with:
name: logs-${{ matrix.project }}
path: /home/runner/.vegacapsule/testnet/logs
name: test-report-and-logs-${{ matrix.project }}
path: |
/home/runner/.vegacapsule/testnet/logs
frontend-monorepo/apps/trading-e2e/cypress/reports
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
app: ${{ fromJSON(inputs.projects) }}
name: ${{ matrix.app }}
runs-on: ubuntu-22.04
timeout-minutes: 20
timeout-minutes: 25
steps:
- name: Check out code
uses: actions/checkout@v3
+3
View File
@@ -46,3 +46,6 @@ cypress.env.json
# Next.js
.next
#cypress
/apps/trading-e2e/cypress/reports/
+1
View File
@@ -21,6 +21,7 @@ module.exports = defineConfig({
chromeWebSecurity: false,
viewportWidth: 1440,
viewportHeight: 900,
testIsolation: false,
},
env: {
environment: 'CUSTOM',
@@ -60,9 +60,11 @@ export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
<>
<MarketInfoTable
noBorder={false}
data={trigger}
data={{
maxValidPrice: trigger.maxValidPrice,
minValidPrice: trigger.minValidPrice,
}}
decimalPlaces={market.decimalPlaces}
omits={['referencePrice', '__typename']}
/>
<MarketInfoTable
noBorder={false}
+2
View File
@@ -10,11 +10,13 @@ NX_ETHEREUM_CHAIN_ID=1440
NX_ETH_URL_CONNECT=1
NX_ETH_WALLET_MNEMONIC=ozone access unlock valid olympic save include omit supply green clown session
NX_LOCAL_PROVIDER_URL=http://localhost:8545/
NX_ETH_LOCAL_PROVIDER_URL=http://localhost:8545/
NX_VEGA_WALLET_URL=http://localhost:1789
NX_VEGA_DOCS_URL=https://docs.vega.xyz/mainnet
NX_TRANCHES_SERVICE_URL=https://tranches-stagnet3-k8s.ops.vega.xyz
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/test/announcements.json
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
#Test configuration variables
CYPRESS_FAIRGROUND=false
+1
View File
@@ -25,6 +25,7 @@ module.exports = defineConfig({
viewportWidth: 1440,
viewportHeight: 900,
numTestsKeptInMemory: 5,
testIsolation: false,
},
env: {
ethProviderUrl: 'http://localhost:8545/',
@@ -40,18 +40,22 @@ const stakeAddStakeRadioButton = 'add-stake-radio';
const stakeMaximumTokens = 'token-amount-use-maximum';
const vegaWalletAssociatedBalance = 'currency-value';
const vegaWalletStakedBalances = 'vega-wallet-balance-staked-validators';
const ethWalletContainer = 'ethereum-wallet';
const ethWallet = 'ethereum-wallet';
const vegaWallet = 'vega-wallet';
const vegaWalletPublicKeyShort = Cypress.env('vegaWalletPublicKeyShort');
const txTimeout = Cypress.env('txTimeout');
const epochTimeout = Cypress.env('epochTimeout');
const getEthereumWallet = () => cy.get(`[data-testid="${ethWallet}"]:visible`);
const getVegaWallet = () => cy.get(`[data-testid="${vegaWallet}"]:visible`);
context(
'Staking Tab - with eth and vega wallets connected',
{ tags: '@slow' },
function () {
// 2001-STKE-002, 2001-STKE-032
before('visit staking tab and connect vega wallet', function () {
cy.clearAllLocalStorage();
cy.visit('/');
ethereumWalletConnect();
// this is a workaround for #2422 which can be removed once issue is resolved
@@ -187,31 +191,35 @@ context(
.should('contain', 1.0, txTimeout);
closeStakingDialog();
navigateTo(navigation.validators);
cy.get(`[row-id="${0}"]`).within(() => {
cy.getByTestId(stakeValidatorListTotalStake)
.should('have.text', '2.00')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalShare)
.should('have.text', '66.67%')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalStake)
.scrollIntoView()
.should('have.text', '2.00')
.and('be.visible');
});
cy.get(`[row-id="${1}"]`).within(() => {
cy.getByTestId(stakeValidatorListTotalStake)
.scrollIntoView()
.should('have.text', '1.00')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalShare)
.should('have.text', '33.33%')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalStake)
.scrollIntoView()
.should('have.text', '1.00')
.and('be.visible');
});
cy.get(`[row-id="${0}"]`)
.eq(1)
.within(() => {
cy.getByTestId(stakeValidatorListTotalStake)
.should('have.text', '2.00')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalShare)
.should('have.text', '66.67%')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalStake)
.scrollIntoView()
.should('have.text', '2.00')
.and('be.visible');
});
cy.get(`[row-id="${1}"]`)
.eq(1)
.within(() => {
cy.getByTestId(stakeValidatorListTotalStake)
.scrollIntoView()
.should('have.text', '1.00')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalShare)
.should('have.text', '33.33%')
.and('be.visible');
cy.getByTestId(stakeValidatorListTotalStake)
.scrollIntoView()
.should('have.text', '1.00')
.and('be.visible');
});
});
// 2001-STKE-041
@@ -329,11 +337,11 @@ context(
verifyStakedBalance(2.0);
closeStakingDialog();
stakingPageDisassociateAllTokens();
cy.getByTestId(ethWalletContainer).within(() => {
getEthereumWallet().within(() => {
cy.contains(vegaWalletPublicKeyShort, txTimeout).should('not.exist');
});
verifyEthWalletTotalAssociatedBalance('0.0');
cy.getByTestId(vegaWallet).within(() => {
getVegaWallet().within(() => {
cy.getByTestId(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
'0.00'
@@ -357,11 +365,11 @@ context(
verifyStakedBalance(2.0);
closeStakingDialog();
stakingPageDisassociateAllTokens('contract');
cy.getByTestId(ethWalletContainer).within(() => {
getEthereumWallet().within(() => {
cy.contains(vegaWalletPublicKeyShort, txTimeout).should('not.exist');
});
verifyEthWalletTotalAssociatedBalance('0.0');
cy.getByTestId(vegaWallet).within(() => {
getVegaWallet().within(() => {
cy.getByTestId(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
'0.00'
@@ -386,7 +394,7 @@ context(
closeStakingDialog();
stakingPageDisassociateTokens('1');
verifyEthWalletTotalAssociatedBalance('2.0');
cy.getByTestId(vegaWallet).within(() => {
getVegaWallet().within(() => {
cy.getByTestId(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
'2.00'
@@ -453,7 +461,7 @@ context(
verifyUnstakedBalance(0.0);
closeStakingDialog();
stakingPageAssociateTokens('6');
cy.getByTestId(vegaWallet).within(() => {
getVegaWallet().within(() => {
cy.getByTestId(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
'12.00'
@@ -15,7 +15,7 @@ context('Home Page - verify elements on page', { tags: '@smoke' }, function () {
});
});
it.skip('should display announcement banner', function () {
it('should display announcement banner', function () {
cy.getByTestId('app-announcement')
.should('contain.text', 'TEST ANNOUNCEMENT!')
.within(() => {
@@ -45,10 +45,12 @@ context('View functionality with public key', { tags: '@smoke' }, function () {
navigateTo(navigation.proposals);
goToMakeNewProposal('Freeform');
enterUniqueFreeFormProposalBody('50', 'pub key proposal test');
cy.getByTestId('dialog-content').within(() => {
cy.get('h1').should('have.text', 'Transaction failed');
cy.getByTestId('Error').should('have.text', expectedErrorTxt);
});
cy.getByTestId('dialog-content')
.first()
.within(() => {
cy.get('h1').should('have.text', 'Transaction failed');
cy.getByTestId('Error').should('have.text', expectedErrorTxt);
});
});
it('Able to disconnect via banner', function () {
@@ -3,6 +3,7 @@ import {
navigation,
verifyPageHeader,
} from '../../support/common.functions';
import { waitForBeginningOfEpoch } from '../../support/staking.functions';
const viewToggle = '[data-testid="epoch-reward-view-toggle-total"]';
const warning = '[data-testid="callout"]';
@@ -37,6 +38,41 @@ context(
it('should have toggle for seeing total vs individual rewards', function () {
cy.get(viewToggle).should('be.visible');
});
// Skipping due to bug #3471 causing flaky failuress
it.skip('should have option to view go to next and previous page', function () {
waitForBeginningOfEpoch();
cy.getByTestId('page-info')
.should('contain.text', 'Page ')
.invoke('text')
.then(($currentPage) => {
const currentPageNumber = Number($currentPage.slice(5));
cy.getByTestId('goto-next-page').click();
cy.getByTestId('page-info')
.invoke('text')
.then(($newPageNumber) => {
const newPageNumber = Number($newPageNumber.slice(5));
expect(newPageNumber).to.be.greaterThan(currentPageNumber);
cy.getByTestId('goto-previous-page').click();
cy.getByTestId('page-info').should(
'contain.text',
$currentPage
);
});
});
});
it('should have option to go to last and newest page', function () {
waitForBeginningOfEpoch();
cy.getByTestId('goto-last-page').click();
cy.getByTestId('epoch-total-rewards-table')
.last()
.find('h2')
.first()
.should('have.text', 'EPOCH 1');
cy.getByTestId('goto-first-page').click();
cy.get('h2').should('not.contain.text', 'EPOCH 1');
});
});
}
);
@@ -1,7 +1,6 @@
/// <reference types="cypress" />
import {
navigateTo,
navigation,
verifyPageHeader,
verifyTabHighlighted,
@@ -34,8 +33,8 @@ const stakeNumberRegex = /^\d*\.?\d*$/;
context('Validators Page - verify elements on page', function () {
before('navigate to validators page', function () {
cy.visit('/');
navigateTo(navigation.validators);
cy.clearAllLocalStorage();
cy.visit('/validators');
});
describe('with wallets disconnected', { tags: '@smoke' }, function () {
@@ -43,23 +43,25 @@ context(
// 1005-VEST-020 1005-VEST-021
it('Tokens in vesting contract for eth wallet is displayed on wallet window', function () {
cy.getByTestId('vega-in-vesting-contract').within(() => {
cy.getByTestId('currency-title')
.should('contain.text', 'VEGA')
.and('contain.text', 'In vesting contract');
cy.get('[data-testid="currency-value"]:visible').should(
'have.text',
lockedTokensInVestingContract
);
cy.get('[data-testid="currency-locked"]:visible').should(
'have.text',
lockedTokensInVestingContract
);
cy.get('[data-testid="currency-unlocked"]:visible').should(
'have.text',
'0.00'
);
});
cy.get('[data-testid="vega-in-vesting-contract"]:visible').within(
() => {
cy.getByTestId('currency-title')
.should('contain.text', 'VEGA')
.and('contain.text', 'In vesting contract');
cy.get('[data-testid="currency-value"]:visible').should(
'have.text',
lockedTokensInVestingContract
);
cy.get('[data-testid="currency-locked"]:visible').should(
'have.text',
lockedTokensInVestingContract
);
cy.get('[data-testid="currency-unlocked"]:visible').should(
'have.text',
'0.00'
);
}
);
});
// 1005-VEST-022 1005-VEST-023
it('Tokens amount displayed in vesting page', function () {
@@ -17,7 +17,7 @@ const vegaInWallet = '[data-testid="vega-in-wallet"]:visible';
const progressBar = '[data-testid="progress-bar"]:visible';
const currencyLocked = '[data-testid="currency-locked"]:visible';
const currencyUnlocked = '[data-testid="currency-unlocked"]:visible';
const dialog = '[role="dialog"]';
const dialog = '[role="dialog"]:visible';
const dialogHeader = '[data-testid="dialog-title"]';
const dialogCloseBtn = '[data-testid="dialog-close"]';
@@ -68,8 +68,10 @@ context(
it('should have connector list visible', function () {
const connectList = [
'Unknown',
'MetaMask, Brave or other injected web wallet',
'MetaMask',
'Coinbase',
'WalletConnect',
'WalletConnect Legacy',
];
cy.get(connectorList).within(() => {
cy.get('button').each(($btn, i) => {
@@ -7,7 +7,7 @@ const walletContainer = 'aside [data-testid="vega-wallet"]';
const walletHeader = '[data-testid="wallet-header"] h1';
const connectButton = '[data-testid="connect-vega-wallet"]';
const getVegaLink = '[data-testid="link"]';
const dialog = '[role="dialog"]';
const dialog = '[role="dialog"]:visible';
const dialogHeader = '[data-testid="dialog-title"]';
const walletDialogHeader = '[data-testid="wallet-dialog-title"]';
const connectorsList = '[data-testid="connectors-list"]';
@@ -35,6 +35,7 @@ context(
{ tags: '@regression' },
() => {
before('visit token home page', () => {
cy.clearAllLocalStorage();
cy.visit('/');
cy.get(walletContainer, { timeout: 60000 }).should('be.visible');
});
@@ -26,9 +26,11 @@ const topLevelRoutes = [
export function navigateTo(page: navigation) {
if (!topLevelRoutes.includes(page)) {
cy.getByTestId(tokenDropDown, { timeout: 10000 }).eq(0).click();
cy.getByTestId('token-dropdown').within(() => {
cy.get(page).eq(0).click();
});
cy.getByTestId('token-dropdown')
.first()
.within(() => {
cy.get(page).eq(0).click();
});
} else {
return cy.get(navigation.section, { timeout: 10000 }).within(() => {
cy.get(page).eq(0).click();
@@ -184,16 +184,18 @@ export function validateValidatorListTotalStakeAndShare(
) {
cy.contains('Loading...', epochTimeout).should('not.exist');
waitForBeginningOfEpoch();
cy.get(`[row-id="${positionOnList}"]`).within(() => {
cy.getByTestId(stakeValidatorListTotalStake, epochTimeout).should(
'have.text',
expectedTotalStake
);
cy.getByTestId(stakeValidatorListTotalShare, epochTimeout).should(
'have.text',
expectedTotalShare
);
});
cy.get(`[row-id="${positionOnList}"]:visible`)
.eq(1)
.within(() => {
cy.getByTestId(stakeValidatorListTotalStake, epochTimeout).should(
'have.text',
expectedTotalStake
);
cy.getByTestId(stakeValidatorListTotalShare, epochTimeout).should(
'have.text',
expectedTotalShare
);
});
}
export function ensureSpecifiedUnstakedTokensAreAssociated(
@@ -218,13 +220,15 @@ export function ensureSpecifiedUnstakedTokensAreAssociated(
}
export function closeStakingDialog() {
cy.getByTestId('dialog-title').should(
cy.get('[data-testid="dialog-title"]:visible').should(
'contain.text',
'At the beginning of the next epoch'
);
cy.getByTestId('dialog-content').within(() => {
cy.get('a').should('have.text', 'Back to Staking').click();
});
cy.get('[data-testid="dialog-content"]:visible')
.first()
.within(() => {
cy.get('a').should('have.text', 'Back to Staking').click();
});
}
export function validateWalletCurrency(
@@ -9,7 +9,7 @@ import {
import { ethers, Wallet } from 'ethers';
const associatedAmountInWallet = '[data-testid="associated-amount"]:visible';
const vegaWalletContainer = 'aside [data-testid="vega-wallet"]';
const vegaWalletContainer = 'aside [data-testid="vega-wallet"]:visible';
const vegaWalletMnemonic = Cypress.env('vegaWalletMnemonic');
const vegaWalletPubKey = Cypress.env('vegaWalletPublicKey');
const vegaTokenContractAddress = Cypress.env('vegaTokenContractAddress');
+1
View File
@@ -14,6 +14,7 @@ NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_DELEGATIONS_PAGINATION=50
NX_TRANCHES_SERVICE_URL=https://tranches-stagnet3-k8s.ops.vega.xyz
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/main/announcements.json
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
#Test configuration variables
CYPRESS_FAIRGROUND=false
+1
View File
@@ -20,3 +20,4 @@ NX_TRANCHES_SERVICE_URL=https://tranches-stagnet3-k8s.ops.vega.xyz
#Test configuration variables
CYPRESS_FAIRGROUND=false
+47 -8
View File
@@ -17,6 +17,12 @@ import { AppStateProvider } from './contexts/app-state/app-state-provider';
import { ContractsProvider } from './contexts/contracts/contracts-provider';
import { AppRouter } from './routes';
import type { EthereumConfig } from '@vegaprotocol/web3';
import {
createConnectors,
useEthTransactionManager,
useEthWithdrawApprovalsManager,
useWeb3ConnectStore,
} from '@vegaprotocol/web3';
import { Web3Provider } from '@vegaprotocol/web3';
import { VegaWalletDialogs } from './components/vega-wallet-dialogs';
import { VegaWalletProvider } from '@vegaprotocol/wallet';
@@ -27,10 +33,10 @@ import {
NetworkLoader,
useInitializeEnv,
} from '@vegaprotocol/environment';
import { createConnectors } from './lib/web3-connectors';
import { ENV } from './config/env';
import { ENV } from './config';
import type { InMemoryCacheConfig } from '@apollo/client';
import { WithdrawalDialog } from '@vegaprotocol/withdraws';
import { SplashLoader } from './components/splash-loader';
const cache: InMemoryCacheConfig = {
typePolicies: {
@@ -70,20 +76,52 @@ const cache: InMemoryCacheConfig = {
const Web3Container = ({
chainId,
providerUrl,
}: {
chainId: number;
providerUrl: string;
}) => {
const InitializeHandlers = () => {
useEthTransactionManager();
useEthWithdrawApprovalsManager();
return null;
};
const [connectors, initializeConnectors] = useWeb3ConnectStore((store) => [
store.connectors,
store.initialize,
]);
const { ETHEREUM_PROVIDER_URL, ETH_LOCAL_PROVIDER_URL, ETH_WALLET_MNEMONIC } =
useEnvironment();
useEffect(() => {
if (chainId) {
return initializeConnectors(
createConnectors(
ETHEREUM_PROVIDER_URL,
Number(chainId),
ETH_LOCAL_PROVIDER_URL,
ETH_WALLET_MNEMONIC
),
Number(chainId)
);
}
}, [
chainId,
ETHEREUM_PROVIDER_URL,
initializeConnectors,
ETH_LOCAL_PROVIDER_URL,
ETH_WALLET_MNEMONIC,
]);
const sideBar = React.useMemo(() => {
return [<EthWallet />, <VegaWallet />];
}, []);
const Connectors = React.useMemo(() => {
return createConnectors(providerUrl, Number(chainId));
}, [chainId, providerUrl]);
if (connectors.length === 0) {
// Prevent loading when the connectors are not initialized
return <SplashLoader />;
}
return (
<Web3Provider connectors={Connectors}>
<Web3Connector connectors={Connectors} chainId={Number(chainId)}>
<Web3Provider connectors={connectors}>
<Web3Connector connectors={connectors} chainId={Number(chainId)}>
<VegaWalletProvider>
<ContractsProvider>
<AppLoader>
@@ -97,6 +135,7 @@ const Web3Container = ({
<NetworkInfo />
</footer>
</AppLayout>
<InitializeHandlers />
<VegaWalletDialogs />
<TransactionModal />
<WithdrawalDialog />
@@ -26,6 +26,7 @@ import {
import { Loader } from '@vegaprotocol/ui-toolkit';
import colors from 'tailwindcss/colors';
import { useBalances } from '../../lib/balances/balances-store';
import { useWeb3Disconnect } from '@vegaprotocol/web3';
const removeLeadingAddressSymbol = (key: string) => {
if (key && key.length > 2 && key.slice(0, 2) === '0x') {
@@ -184,6 +185,7 @@ export const EthWallet = () => {
const { appDispatch } = useAppState();
const { account, connector } = useWeb3React();
const pendingTxs = usePendingTransactions();
const disconnect = useWeb3Disconnect(connector);
return (
<WalletCard>
@@ -239,7 +241,7 @@ export const EthWallet = () => {
<div className="flex justify-end">
<button
className="underline"
onClick={() => connector.deactivate()}
onClick={() => disconnect()}
data-testid="disconnect-from-eth-wallet-button"
>
{t('disconnect')}
@@ -1,5 +1,10 @@
import { Button, Splash } from '@vegaprotocol/ui-toolkit';
import { getChainName, Web3ConnectDialog } from '@vegaprotocol/web3';
import {
getChainName,
useWeb3ConnectStore,
useWeb3Disconnect,
Web3ConnectDialog,
} from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core';
import type { ReactElement } from 'react';
import { useCallback, useEffect } from 'react';
@@ -51,7 +56,9 @@ interface Web3ContentProps {
}
export const Web3Content = ({ children, appChainId }: Web3ContentProps) => {
const { error, connector, chainId } = useWeb3React();
const { connector, chainId } = useWeb3React();
const error = useWeb3ConnectStore((store) => store.error);
const disconnect = useWeb3Disconnect(connector);
useEffect(() => {
if (connector?.connectEagerly) {
@@ -67,7 +74,7 @@ export const Web3Content = ({ children, appChainId }: Web3ContentProps) => {
<Splash>
<div className="flex flex-col items-center gap-12">
<p className="text-white">Something went wrong: {error.message}</p>
<Button onClick={() => connector.deactivate()}>Disconnect</Button>
<Button onClick={() => disconnect()}>Disconnect</Button>
</div>
</Splash>
);
@@ -80,7 +87,7 @@ export const Web3Content = ({ children, appChainId }: Web3ContentProps) => {
<p className="text-white">
This app only works on {getChainName(appChainId)}
</p>
<Button onClick={() => connector.deactivate()}>Disconnect</Button>
<Button onClick={() => disconnect()}>Disconnect</Button>
</div>
</Splash>
);
@@ -789,5 +789,6 @@
"approvers": "Approvers",
"approval (% validator voting power)": "approval (% validator voting power)",
"67% voting power required": "67% voting power required",
"Token": "Token"
"Token": "Token",
"associateVegaNow": "Associate $VEGA now"
}
+18 -26
View File
@@ -1,20 +1,17 @@
import { ethers } from 'ethers';
import type { Web3ReactHooks } from '@web3-react/core';
import { initializeConnector } from '@web3-react/core';
import { MetaMask } from '@web3-react/metamask';
import { WalletConnect } from '@web3-react/walletconnect';
import type { Connector } from '@web3-react/types';
import { ENV } from '../config/env';
import { UrlConnector } from '@vegaprotocol/web3';
import {
initializeMetaMaskConnector,
initializeWalletConnector,
initializeWalletConnectLegacyConnector,
initializeCoinbaseConnector,
WALLETCONNECT_PROJECT_ID,
initializeUrlConnector,
} from '@vegaprotocol/web3';
const [metamask, metamaskHooks] = initializeConnector<MetaMask>(
(actions) => new MetaMask(actions)
);
const [urlConnector, urlHooks] = initializeConnector<UrlConnector>(
(actions) =>
new UrlConnector(actions, ENV.localProviderUrl, ENV.ethWalletMnemonic)
);
initializeUrlConnector(ENV.localProviderUrl, ENV.ethWalletMnemonic);
export const createDefaultProvider = (providerUrl: string, chainId: number) => {
return new ethers.providers.JsonRpcProvider(providerUrl, chainId);
@@ -24,19 +21,14 @@ export const createConnectors = (providerUrl: string, chainId: number) => {
if (isNaN(chainId)) {
throw new Error('Invalid Ethereum chain ID for environment');
}
const [walletconnect, walletconnectHooks] =
initializeConnector<WalletConnect>(
(actions) =>
new WalletConnect(actions, {
rpc: {
[chainId]: providerUrl,
},
}),
[chainId]
);
return [
ENV.urlConnect ? [urlConnector, urlHooks] : null,
[metamask, metamaskHooks],
[walletconnect, walletconnectHooks],
].filter(Boolean) as [Connector, Web3ReactHooks][];
ENV.urlConnect
? initializeUrlConnector(ENV.localProviderUrl, ENV.ethWalletMnemonic)
: null,
initializeMetaMaskConnector(),
initializeCoinbaseConnector(providerUrl),
initializeWalletConnector(WALLETCONNECT_PROJECT_ID, chainId, providerUrl),
initializeWalletConnectLegacyConnector(chainId, providerUrl),
].filter(Boolean) as unknown as [Connector, Web3ReactHooks][];
};
@@ -13,6 +13,8 @@ import { StakingFormTxStatuses } from './staking-form-tx-statuses';
import {
ButtonLink,
FormGroup,
Intent,
Notification,
Radio,
RadioGroup,
} from '@vegaprotocol/ui-toolkit';
@@ -29,6 +31,7 @@ import type {
DelegateSubmissionBody,
UndelegateSubmissionBody,
} from '@vegaprotocol/wallet';
import Routes from '../../routes';
export enum FormState {
Default,
@@ -191,51 +194,65 @@ export const StakingForm = ({
}, [isDialogVisible]);
return (
<>
<div className="my-8">
<SubHeading title={t('Manage your stake')} />
{formState === FormState.Default &&
availableStakeToAdd.isEqualTo(0) &&
availableStakeToRemove.isEqualTo(0) && (
<div className="mb-4">
{lien.isGreaterThan(0) ? (
<span className="text-vega-pink">
{t('stakeNodeWrongVegaKey')}
</span>
<Notification
intent={Intent.Warning}
message={t('stakeNodeWrongVegaKey')}
/>
) : (
<span className="text-vega-orange">{t('stakeNodeNone')}</span>
<Notification
message={t('stakeNodeNone')}
intent={Intent.Warning}
buttonProps={{
text: t('associateVegaNow'),
action: () => navigate(Routes.ASSOCIATE),
className: 'py-1',
size: 'sm',
}}
/>
)}
</div>
)}
<FormGroup
label={t('Select if you want to add or remove stake')}
labelFor="radio-stake-options"
hideLabel={true}
>
<RadioGroup
name="radio-stake-options"
onChange={(value) => {
// @ts-ignore value does exist on target
setAction(value);
navigate(`?action=${value}`, {
replace: true,
});
}}
value={action}
<div className="mb-8">
<FormGroup
label={t('Select if you want to add or remove stake')}
labelFor="radio-stake-options"
hideLabel={true}
>
<Radio
disabled={availableStakeToAdd.isEqualTo(0)}
value={Actions.Add}
label="Add"
id="add-stake-radio"
/>
<Radio
disabled={availableStakeToRemove.isEqualTo(0)}
value={Actions.Remove}
label="Remove"
id="remove-stake-radio"
/>
</RadioGroup>
</FormGroup>
<RadioGroup
name="radio-stake-options"
onChange={(value) => {
// @ts-ignore value does exist on target
setAction(value);
navigate(`?action=${value}`, {
replace: true,
});
}}
value={action}
>
<Radio
disabled={availableStakeToAdd.isEqualTo(0)}
value={Actions.Add}
label="Add"
id="add-stake-radio"
/>
<Radio
disabled={availableStakeToRemove.isEqualTo(0)}
value={Actions.Remove}
label="Remove"
id="remove-stake-radio"
/>
</RadioGroup>
</FormGroup>
</div>
{action !== undefined && (
// eslint-disable-next-line
<>
@@ -314,6 +331,6 @@ export const StakingForm = ({
toggleDialog={toggleDialog}
error={error}
/>
</>
</div>
);
};
+1 -1
View File
@@ -2,4 +2,4 @@ NX_VEGA_URL=https://api.stagnet3.vega.xyz/graphql
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml
NX_VEGA_NETWORKS='{"TESTNET":"https://multisig-signer.fairground.wtf","MAINNET":"https://multisig-signer.vega.xyz"}'
NX_VEGA_ENV=STAGNET3
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
+3 -1
View File
@@ -9,6 +9,7 @@ import {
} from '@vegaprotocol/environment';
import { AsyncRenderer, Button, Lozenge } from '@vegaprotocol/ui-toolkit';
import type { EthereumConfig } from '@vegaprotocol/web3';
import { useWeb3Disconnect } from '@vegaprotocol/web3';
import { useEthereumConfig, Web3Provider } from '@vegaprotocol/web3';
import { t } from '@vegaprotocol/i18n';
import { ENV } from './config/env';
@@ -34,6 +35,7 @@ const pageWrapperClasses = classnames(
const ConnectedApp = ({ config }: { config: EthereumConfig | null }) => {
const { account, connector } = useWeb3React();
const disconnect = useWeb3Disconnect(connector);
return (
<main className="w-full max-w-3xl px-5 justify-self-center">
<h1>{t('Multisig signer')}</h1>
@@ -41,7 +43,7 @@ const ConnectedApp = ({ config }: { config: EthereumConfig | null }) => {
<p>
Connected to Eth wallet: <Lozenge>{account}</Lozenge>
</p>
<Button onClick={() => connector.deactivate()}>Disconnect</Button>
<Button onClick={() => disconnect()}>Disconnect</Button>
</div>
<ContractDetails config={config} />
<h2>{t('Add or remove signer')}</h2>
@@ -1,5 +1,10 @@
import { useEnvironment } from '@vegaprotocol/environment';
import { getChainName, useEthereumConfig } from '@vegaprotocol/web3';
import {
getChainName,
useEthereumConfig,
useWeb3ConnectStore,
useWeb3Disconnect,
} from '@vegaprotocol/web3';
import { Button, Splash, AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import { Web3ConnectDialog } from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core';
@@ -55,7 +60,9 @@ export const Web3Content = ({
appChainId,
setDialogOpen,
}: Web3ContentProps) => {
const { error, connector, chainId } = useWeb3React();
const { connector, chainId } = useWeb3React();
const error = useWeb3ConnectStore((store) => store.error);
const disconnect = useWeb3Disconnect(connector);
useEffect(() => {
if (connector?.connectEagerly) {
@@ -71,7 +78,7 @@ export const Web3Content = ({
<Splash>
<div className="flex flex-col items-center gap-12">
<p className="text-white">Something went wrong: {error.message}</p>
<Button onClick={() => connector.deactivate()}>Disconnect</Button>
<Button onClick={() => disconnect()}>Disconnect</Button>
</div>
</Splash>
);
@@ -84,7 +91,7 @@ export const Web3Content = ({
<p className="text-white">
This app only works on {getChainName(appChainId)}
</p>
<Button onClick={() => connector.deactivate()}>Disconnect</Button>
<Button onClick={() => disconnect()}>Disconnect</Button>
</div>
</Splash>
);
@@ -1,13 +1,13 @@
import { ethers } from 'ethers';
import type { Web3ReactHooks } from '@web3-react/core';
import { initializeConnector } from '@web3-react/core';
import { MetaMask } from '@web3-react/metamask';
import { WalletConnect } from '@web3-react/walletconnect';
import type { Connector } from '@web3-react/types';
const [metamask, metamaskHooks] = initializeConnector<MetaMask>(
(actions) => new MetaMask(actions)
);
import {
WALLETCONNECT_PROJECT_ID,
initializeCoinbaseConnector,
initializeMetaMaskConnector,
initializeWalletConnectLegacyConnector,
initializeWalletConnector,
} from '@vegaprotocol/web3';
export const createDefaultProvider = (providerUrl: string, chainId: number) => {
return new ethers.providers.JsonRpcProvider(providerUrl, chainId);
@@ -17,18 +17,11 @@ export const createConnectors = (providerUrl: string, chainId: number) => {
if (isNaN(chainId)) {
throw new Error('Invalid Ethereum chain ID for environment');
}
const [walletconnect, walletconnectHooks] =
initializeConnector<WalletConnect>(
(actions) =>
new WalletConnect(actions, {
rpc: {
[chainId]: providerUrl,
},
}),
[chainId]
);
return [
[metamask, metamaskHooks],
[walletconnect, walletconnectHooks],
] as [Connector, Web3ReactHooks][];
initializeMetaMaskConnector(),
initializeCoinbaseConnector(providerUrl),
initializeWalletConnector(WALLETCONNECT_PROJECT_ID, chainId, providerUrl),
initializeWalletConnectLegacyConnector(chainId, providerUrl),
].filter(Boolean) as unknown as [Connector, Web3ReactHooks][];
};
+16 -16
View File
@@ -38,7 +38,7 @@
"tranche_end": "2023-05-20T00:00:00.000Z",
"total_added": "15761.125",
"total_removed": "0",
"locked_amount": "15761.125",
"locked_amount": "15494.9188690682869786625",
"deposits": [
{
"amount": "241.5",
@@ -666,7 +666,7 @@
"tranche_end": "2023-05-06T00:00:00.000Z",
"total_added": "8865",
"total_removed": "362.31015740205",
"locked_amount": "4874.1459548611110345",
"locked_amount": "4578.269739583333005",
"deposits": [
{
"amount": "33",
@@ -4407,7 +4407,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "86666.297",
"total_removed": "0",
"locked_amount": "54491.6293588377368963476",
"locked_amount": "54253.8851505212161988738",
"deposits": [
{
"amount": "86666.297",
@@ -4473,7 +4473,7 @@
"tranche_end": "2023-06-01T00:00:00.000Z",
"total_added": "2500",
"total_removed": "0",
"locked_amount": "583.71664504477005",
"locked_amount": "569.96289300976805",
"deposits": [
{
"amount": "2500",
@@ -4594,7 +4594,7 @@
"tranche_end": "2023-09-01T00:00:00.000Z",
"total_added": "17500",
"total_removed": "0",
"locked_amount": "12791.60329232085475",
"locked_amount": "12696.37350920893675",
"deposits": [
{
"amount": "12500",
@@ -4861,7 +4861,7 @@
"tranche_end": "2023-08-01T00:00:00.000Z",
"total_added": "37500",
"total_removed": "12294.731717775",
"locked_amount": "21442.24553023327125",
"locked_amount": "21234.79943600368125",
"deposits": [
{
"amount": "7500",
@@ -5225,7 +5225,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "129999.45",
"total_removed": "0",
"locked_amount": "54441.912603447519962385",
"locked_amount": "54204.385306806945473172",
"deposits": [
{
"amount": "129999.45",
@@ -5258,7 +5258,7 @@
"tranche_end": "2024-04-01T00:00:00.000Z",
"total_added": "54144.7663",
"total_removed": "0",
"locked_amount": "51407.13764596631692808494",
"locked_amount": "51259.01278091454623854912",
"deposits": [
{
"amount": "54144.7663",
@@ -5291,7 +5291,7 @@
"tranche_end": "2023-09-03T00:00:00.000Z",
"total_added": "62600",
"total_removed": "0",
"locked_amount": "23409.75395104008482",
"locked_amount": "23238.02874809741452",
"deposits": [
{
"amount": "10000",
@@ -5484,7 +5484,7 @@
"tranche_end": "2023-09-17T00:00:00.000Z",
"total_added": "5000",
"total_removed": "0",
"locked_amount": "2061.56947615423635",
"locked_amount": "2047.85340563165885",
"deposits": [
{
"amount": "5000",
@@ -6025,7 +6025,7 @@
"tranche_end": "2023-05-01T00:00:00.000Z",
"total_added": "22500",
"total_removed": "6871.43713545",
"locked_amount": "1428.88322974217355",
"locked_amount": "1304.415573204420675",
"deposits": [
{
"amount": "7500",
@@ -6509,7 +6509,7 @@
"tranche_end": "2023-06-02T00:00:00.000Z",
"total_added": "1939928.38",
"total_removed": "928642.9598472029154",
"locked_amount": "231168.093511598737240552",
"locked_amount": "225846.4546178330654320676",
"deposits": [
{
"amount": "1852091.69",
@@ -40325,7 +40325,7 @@
"tranche_end": "2023-06-05T00:00:00.000Z",
"total_added": "3732368.4671",
"total_removed": "715655.108029600523393",
"locked_amount": "379726.105748070797206746073",
"locked_amount": "371548.694092943839794156471",
"deposits": [
{
"amount": "1998.95815",
@@ -41718,7 +41718,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "15870102.715470999700000001",
"total_removed": "835090.78677275839915352",
"locked_amount": "6646171.9758772447834505578413098637685861",
"locked_amount": "6617175.39918817550807202992275848610786696",
"deposits": [
{
"amount": "16249.93",
@@ -48164,7 +48164,7 @@
"tranche_end": "2023-05-05T00:00:00.000Z",
"total_added": "14597706.0446472999",
"total_removed": "5845111.643096907348272126",
"locked_amount": "414258.305630822730645455902270797",
"locked_amount": "387488.8511763643682805777108705054",
"deposits": [
{
"amount": "129284.449",
@@ -58109,7 +58109,7 @@
"tranche_end": "2023-06-05T00:00:00.000Z",
"total_added": "472355.6199999996",
"total_removed": "43120.0853616251849",
"locked_amount": "60169.7720627409513147623313039",
"locked_amount": "58874.014441908253564521489193296",
"deposits": [
{
"amount": "3000",
+1
View File
@@ -12,6 +12,7 @@ NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_WALLET_URL=http://localhost:1789
NX_ETH_LOCAL_PROVIDER_URL=http://localhost:8545/
NX_ETH_WALLET_MNEMONIC="ozone access unlock valid olympic save include omit supply green clown session"
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
# Expose some env vars to cypress environment for market setup
CYPRESS_ETH_WALLET_MNEMONIC=ozone access unlock valid olympic save include omit supply green clown session
+3
View File
@@ -1,8 +1,10 @@
const { defineConfig } = require('cypress');
module.exports = defineConfig({
reporter: '../../node_modules/cypress-mochawesome-reporter',
e2e: {
setupNodeEvents(on, config) {
require('cypress-mochawesome-reporter/plugin')(on);
require('@cypress/grep/src/plugin')(config);
return config;
},
@@ -23,6 +25,7 @@ module.exports = defineConfig({
responseTimeout: 50000,
requestTimeout: 20000,
retries: 2,
testIsolation: false,
},
env: {
ETHERSCAN_URL: 'https://sepolia.etherscan.io',
@@ -108,18 +108,14 @@ describe('market info is displayed', { tags: '@smoke' }, () => {
it('risk model displayed', () => {
cy.getByTestId(marketTitle).contains('Risk model').click();
validateMarketDataRow(0, 'Typename', 'LogNormalRiskModel');
validateMarketDataRow(1, 'Tau', '0.0001140771161');
validateMarketDataRow(2, 'Risk Aversion Parameter', '0.01');
validateMarketDataRow(0, 'Tau', '0.0001140771161');
validateMarketDataRow(1, 'Risk Aversion Parameter', '0.01');
});
it('risk parameters displayed', () => {
cy.getByTestId(marketTitle).contains('Risk parameters').click();
validateMarketDataRow(0, 'Typename', 'LogNormalModelParams');
validateMarketDataRow(1, 'R', '0.016');
validateMarketDataRow(2, 'Sigma', '0.3');
validateMarketDataRow(0, 'R', '0.016');
validateMarketDataRow(1, 'Sigma', '0.3');
});
it('risk factors displayed', () => {
@@ -0,0 +1,47 @@
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { proposalListQuery, marketUpdateProposal } from '@vegaprotocol/mock';
import * as Schema from '@vegaprotocol/types';
const marketSummaryBlock = 'header-summary';
describe('Market proposal notification', { tags: '@smoke' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_ACTIVE,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockGQL((req) => {
aliasGQLQuery(
req,
'ProposalsList',
proposalListQuery({
proposalsConnection: {
edges: [{ node: marketUpdateProposal }],
},
})
);
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@MarketData');
cy.getByTestId(marketSummaryBlock).should('be.visible');
});
it('should display market proposal notification if proposal found', () => {
cy.getByTestId(marketSummaryBlock).within(() => {
cy.getByTestId('market-proposal-notification').should(
'contain.text',
'Changes have been proposed for this market'
);
cy.getByTestId('market-proposal-notification').within(() => {
cy.getByTestId('external-link').should(
'have.attr',
'href',
`${Cypress.env('VEGA_TOKEN_URL')}/proposals/123`
);
});
});
});
});
@@ -0,0 +1,41 @@
describe('market bottom panel', { tags: '@smoke' }, () => {
before(() => {
cy.clearAllLocalStorage();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@MarketData');
});
it('on xxl screen should be splitted out into two tables', () => {
cy.getByTestId('tab-positions').should('have.attr', 'data-state', 'active');
cy.getByTestId('tab-orders').should('have.attr', 'data-state', 'inactive');
cy.getByTestId('tab-fills').should('have.attr', 'data-state', 'inactive');
cy.getByTestId('tab-accounts').should(
'have.attr',
'data-state',
'inactive'
);
cy.viewport(1801, 1000);
cy.getByTestId('tab-positions').should('have.attr', 'data-state', 'active');
cy.getByTestId('tab-orders').should('have.attr', 'data-state', 'active');
cy.getByTestId('tab-fills').should('have.attr', 'data-state', 'inactive');
cy.getByTestId('tab-accounts').should(
'have.attr',
'data-state',
'inactive'
);
cy.getByTestId('Fills').click();
cy.getByTestId('Collateral').click();
cy.getByTestId('tab-positions').should(
'have.attr',
'data-state',
'inactive'
);
cy.getByTestId('tab-orders').should('have.attr', 'data-state', 'inactive');
cy.getByTestId('tab-fills').should('have.attr', 'data-state', 'active');
cy.getByTestId('tab-accounts').should('have.attr', 'data-state', 'active');
});
});
@@ -1,5 +1,3 @@
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { proposalListQuery, marketUpdateProposal } from '@vegaprotocol/mock';
import * as Schema from '@vegaprotocol/types';
const marketSummaryBlock = 'header-summary';
@@ -15,50 +13,9 @@ const priceChangeValue = 'price-change';
const itemHeader = 'item-header';
const itemValue = 'item-value';
describe('Market proposal notification', { tags: '@smoke' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_ACTIVE,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockGQL((req) => {
aliasGQLQuery(
req,
'ProposalsList',
proposalListQuery({
proposalsConnection: {
edges: [{ node: marketUpdateProposal }],
},
})
);
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@MarketData');
cy.getByTestId(marketSummaryBlock).should('be.visible');
});
it('should display market proposal notification if proposal found', () => {
cy.getByTestId(marketSummaryBlock).within(() => {
cy.getByTestId('market-proposal-notification').should(
'contain.text',
'Changes have been proposed for this market'
);
cy.getByTestId('market-proposal-notification').within(() => {
cy.getByTestId('external-link').should(
'have.attr',
'href',
`${Cypress.env('VEGA_TOKEN_URL')}/proposals/123`
);
});
});
});
});
describe('Market trading page', () => {
before(() => {
cy.clearAllLocalStorage();
cy.mockTradingPage(
Schema.MarketState.STATE_ACTIVE,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
@@ -165,6 +122,7 @@ describe('Market trading page', () => {
});
});
cy.getByTestId('expiry-tooltip')
.eq(0)
.should(
'contain.text',
'This market expires when triggered by its oracle, not on a set date.'
@@ -202,6 +160,7 @@ describe('Market trading page', () => {
'contain.text',
'This market is in auction until it reaches sufficient liquidity.'
)
.eq(0)
.within(() => {
cy.getByTestId('external-link')
.should('have.attr', 'href')
@@ -216,93 +175,4 @@ describe('Market trading page', () => {
});
});
});
describe('market bottom panel', { tags: '@smoke' }, () => {
it('on xxl screen should be splitted out into two tables', () => {
cy.getByTestId('tab-positions').should(
'have.attr',
'data-state',
'active'
);
cy.getByTestId('tab-orders').should(
'have.attr',
'data-state',
'inactive'
);
cy.getByTestId('tab-fills').should('have.attr', 'data-state', 'inactive');
cy.getByTestId('tab-accounts').should(
'have.attr',
'data-state',
'inactive'
);
cy.viewport(1801, 1000);
cy.getByTestId('tab-positions').should(
'have.attr',
'data-state',
'active'
);
cy.getByTestId('tab-orders').should('have.attr', 'data-state', 'active');
cy.getByTestId('tab-fills').should('have.attr', 'data-state', 'inactive');
cy.getByTestId('tab-accounts').should(
'have.attr',
'data-state',
'inactive'
);
cy.getByTestId('Fills').click();
cy.getByTestId('Collateral').click();
cy.getByTestId('tab-positions').should(
'have.attr',
'data-state',
'inactive'
);
cy.getByTestId('tab-orders').should(
'have.attr',
'data-state',
'inactive'
);
cy.getByTestId('tab-fills').should('have.attr', 'data-state', 'active');
cy.getByTestId('tab-accounts').should(
'have.attr',
'data-state',
'active'
);
});
});
});
describe('market states not accepting orders', { tags: '@smoke' }, function () {
//7002-SORD-062
//7002-SORD-063
//7002-SORD-066
const states = [
Schema.MarketState.STATE_REJECTED,
Schema.MarketState.STATE_CANCELLED,
Schema.MarketState.STATE_CLOSED,
Schema.MarketState.STATE_SETTLED,
Schema.MarketState.STATE_TRADING_TERMINATED,
];
states.forEach((marketState) => {
describe(marketState, function () {
beforeEach(function () {
cy.mockTradingPage(marketState);
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/markets/market-0');
});
it('must display that market is not accepting orders', function () {
cy.getByTestId('dealticket-error-message-summary').should(
'have.text',
`This market is ${marketState
.split('_')
.pop()
?.toLowerCase()} and not accepting orders`
);
cy.getByTestId('place-order').should('be.disabled');
});
});
});
});
+70 -77
View File
@@ -1,27 +1,32 @@
import { mockConnectWallet } from '@vegaprotocol/cypress';
beforeEach(() => {
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/');
cy.wait('@Markets');
cy.wait('@MarketsData');
cy.wait('@MarketsCandles');
cy.getByTestId('dialog-close').click();
});
describe('Navbar', { tags: '@smoke' }, () => {
before(() => {
cy.clearAllLocalStorage();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/');
cy.wait('@Markets');
cy.wait('@MarketsData');
cy.wait('@MarketsCandles');
// close welcome dialog
cy.getByTestId('dialog-close').click();
});
describe('Desktop view', { tags: '@smoke' }, () => {
describe('Navbar', () => {
const links = ['Markets', 'Trading', 'Portfolio'];
const hashes = ['#/markets/all', '#/markets/market-1', '#/portfolio'];
const pages = [
{ name: 'Markets', link: '#/markets/all' },
{ name: 'Trading', link: '#/markets' },
{ name: 'Portfolio', link: '#/portfolio' },
];
links.forEach((link, index) => {
it(`${link} should be correctly rendered`, () => {
describe('desktop view', () => {
pages.forEach(({ name, link }) => {
it(`${name} should be correctly rendered`, () => {
cy.get('nav')
.find(`a[data-testid=${link}]:visible`)
.find(`a[data-testid=${name}]:visible`)
.then((element) => {
cy.wrap(element).click();
cy.location('hash').should('equal', hashes[index]);
cy.location('hash').should('contain', link);
});
});
});
@@ -43,73 +48,61 @@ describe('Desktop view', { tags: '@smoke' }, () => {
});
});
});
});
describe('Mobile view', { tags: '@smoke' }, () => {
const viewportHeight = Cypress.config('viewportHeight');
const viewportWidth = Cypress.config('viewportWidth');
before(() => {
// a little hack to keep the viewport size between tests (cypress bug)
Cypress.config({
viewportWidth: 560,
viewportHeight: 890,
describe('mobile view', () => {
const viewportHeight = Cypress.config('viewportHeight');
const viewportWidth = Cypress.config('viewportWidth');
before(() => {
// a little hack to keep the viewport size between tests (cypress bug)
Cypress.config({
viewportWidth: 560,
viewportHeight: 890,
});
cy.viewport(560, 890);
});
cy.viewport(560, 890);
});
describe('wallet drawer', () => {
it('wallet drawer should be correctly rendered', () => {
mockConnectWallet();
cy.connectVegaWallet(true);
cy.getByTestId('connect-vega-wallet-mobile').click();
cy.getByTestId('wallets-drawer').should('be.visible');
cy.getByTestId('wallets-drawer').within((el) => {
cy.wrap(el).get('button').contains('Disconnect').click();
});
cy.getByTestId('wallets-drawer').should('not.be.visible');
});
});
describe('menu drawer', () => {
it('Markets should be correctly rendered', () => {
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').should('be.visible');
cy.getByTestId('menu-drawer').within((el) => {
cy.wrap(el).getByTestId('Markets').click();
cy.location('hash').should('equal', '#/markets/all');
});
});
it('Trading should be correctly rendered', () => {
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').within((el) => {
cy.wrap(el).getByTestId('Trading').click();
cy.location('hash').should('equal', '#/markets/market-1');
});
});
it('Portfolio should be correctly rendered', () => {
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').within((el) => {
cy.wrap(el).getByTestId('Portfolio').click();
cy.location('hash').should('equal', '#/portfolio');
describe('wallet drawer', () => {
it('wallet drawer should be correctly rendered', () => {
mockConnectWallet();
cy.connectVegaWallet(true);
cy.getByTestId('connect-vega-wallet-mobile').click();
cy.getByTestId('wallets-drawer').should('be.visible');
cy.getByTestId('wallets-drawer').within((el) => {
cy.wrap(el).get('button').contains('Disconnect').click();
});
cy.getByTestId('wallets-drawer').should('not.be.visible');
});
});
it('Menu drawer should not be visible until opened', () => {
cy.getByTestId('menu-drawer').should('not.be.visible');
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').should('be.visible');
cy.getByTestId('menu-drawer')
.find('[data-testid="theme-switcher"]')
.should('be.visible');
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').should('not.be.visible');
describe('menu drawer', () => {
pages.forEach(({ name, link }) => {
it(`${name} should be correctly rendered`, () => {
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').should('be.visible');
cy.getByTestId('menu-drawer').within((el) => {
cy.wrap(el).getByTestId(name).click();
cy.location('hash').should('contain', link);
});
});
});
it('Menu drawer should not be visible until opened', () => {
cy.getByTestId('menu-drawer').should('not.be.visible');
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').should('be.visible');
cy.getByTestId('menu-drawer')
.find('[data-testid="theme-switcher"]')
.should('be.visible');
cy.getByTestId('button-menu-drawer').click();
cy.getByTestId('menu-drawer').should('not.be.visible');
});
});
});
after(() => {
// a little hack to keep the viewport size between tests (cypress bug)
Cypress.config({
viewportWidth,
viewportHeight,
after(() => {
// a little hack to keep the viewport size between tests (cypress bug)
Cypress.config({
viewportWidth,
viewportHeight,
});
});
});
});
@@ -1,14 +1,16 @@
import { checkSorting } from '@vegaprotocol/cypress';
beforeEach(() => {
cy.mockTradingPage();
cy.mockWeb3Provider();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/markets/market-0');
});
describe('accounts', { tags: '@smoke' }, () => {
before(() => {
cy.clearAllLocalStorage();
cy.mockTradingPage();
cy.mockWeb3Provider();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/markets/market-0');
cy.wait('@Assets');
});
it('renders accounts', () => {
const tradingAccountRowId = '[row-id="t-0"]';
cy.getByTestId('Collateral').click();
@@ -41,13 +43,21 @@ describe('accounts', { tags: '@smoke' }, () => {
.should('have.text', '100,001.01');
});
it('asset detail should be properly rendered', () => {
cy.getByTestId('Collateral').click();
it('should open asset details dialog when clicked on symbol', () => {
cy.getByTestId('asset').contains('tEURO').click();
cy.get('[data-testid$="_label"]').should('have.length', 16);
cy.get('[data-testid="dialog-content"]:visible').should('exist');
cy.get('[data-testid="dialog-close"]:visible').click();
});
describe('sorting by ag-grid columns should work well', () => {
before(() => {
const dialogs = Cypress.$('[data-testid="dialog-close"]:visible');
if (dialogs.length > 0) {
dialogs.each((btn) => {
cy.wrap(btn).click();
});
}
});
it('sorting by asset', () => {
cy.getByTestId('Collateral').click();
const marketsSortedDefault = ['tBTC', 'tEURO', 'tDAI', 'tBTC'];
@@ -0,0 +1,110 @@
import * as Schema from '@vegaprotocol/types';
import { testOrderSubmission } from '../support/order-validation';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import { createOrder } from '../support/create-order';
describe('must submit order', { tags: '@smoke' }, () => {
// 7002-SORD-039
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places market buy order', () => {
// 7002-SORD-010
// 0003-WTXN-012
// 0003-WTXN-003
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
postOnly: false,
reduceOnly: false,
size: '100',
};
createOrder(order);
testOrderSubmission(order);
});
it('successfully places market sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC,
size: '100',
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order);
});
it('successfully places limit buy order', () => {
// 7002-SORD-017
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GFN,
size: '100',
postOnly: false,
reduceOnly: false,
price: '50000',
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
price: '1.00',
expiresAt: expiresAt.toISOString().substring(0, 16),
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
postOnly: false,
reduceOnly: false,
});
});
});
@@ -0,0 +1,96 @@
import * as Schema from '@vegaprotocol/types';
import { mockConnectWallet } from '@vegaprotocol/cypress';
import {
orderPriceField,
placeOrderBtn,
toggleLimit,
toggleLong,
toggleMarket,
toggleShort,
} from '../support/deal-ticket';
describe('deal ticket basics', { tags: '@smoke' }, () => {
before(() => {
cy.mockTradingPage();
cy.mockSubscription();
cy.clearAllLocalStorage();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('must show place order button and connect wallet if wallet is not connected', () => {
// 0003-WTXN-001
cy.getByTestId('connect-vega-wallet'); // Not connected
cy.getByTestId('order-connect-wallet').should('exist');
cy.getByTestId(placeOrderBtn).should('exist');
cy.getByTestId('deal-ticket-connect-wallet').should('exist');
});
it('must be able to select order direction - long/short', function () {
// 7002-SORD-004
cy.getByTestId(toggleShort).click().children('input').should('be.checked');
cy.getByTestId(toggleLong).click().children('input').should('be.checked');
});
it('must be able to select order type - limit/market', function () {
// 7002-SORD-005
// 7002-SORD-006
// 7002-SORD-007
cy.getByTestId(toggleLimit).click().children('input').should('be.checked');
cy.getByTestId(toggleMarket).click().children('input').should('be.checked');
});
it('order connect vega wallet button should connect', () => {
mockConnectWallet();
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderPriceField).clear().type('101');
cy.getByTestId('order-connect-wallet').click();
cy.getByTestId('dialog-content').should('be.visible');
cy.getByTestId('connectors-list')
.find('[data-testid="connector-jsonRpc"]')
.click();
cy.wait('@walletReq');
cy.getByTestId(placeOrderBtn).should('be.visible');
cy.getByTestId(toggleLimit).children('input').should('be.checked');
cy.getByTestId(orderPriceField).should('have.value', '101');
});
});
describe(
'market states not accepting orders',
{ tags: '@smoke', testIsolation: true },
function () {
//7002-SORD-062
//7002-SORD-063
//7002-SORD-066
const states = [
Schema.MarketState.STATE_REJECTED,
Schema.MarketState.STATE_CANCELLED,
Schema.MarketState.STATE_CLOSED,
Schema.MarketState.STATE_SETTLED,
Schema.MarketState.STATE_TRADING_TERMINATED,
];
states.forEach((marketState) => {
describe(marketState, function () {
beforeEach(function () {
cy.mockTradingPage(marketState);
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/markets/market-0');
});
it('must display that market is not accepting orders', function () {
cy.getByTestId('dealticket-error-message-summary').should(
'have.text',
`This market is ${marketState
.split('_')
.pop()
?.toLowerCase()} and not accepting orders`
);
cy.getByTestId('place-order').should('be.disabled');
});
});
});
}
);
@@ -0,0 +1,92 @@
import {
orderPriceField,
orderSizeField,
orderTIFDropDown,
placeOrderBtn,
toggleLimit,
toggleMarket,
} from '../support/deal-ticket';
describe('deal ticker order validation', { tags: '@smoke' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
describe('limit order', () => {
before(() => {
cy.getByTestId(toggleLimit).click();
});
it('must see the price unit', function () {
// 7002-SORD-018
cy.getByTestId(orderPriceField)
.siblings('label')
.should('have.text', 'Price (DAI)');
});
it('must see warning when placing an order with expiry date in past', () => {
const expiresAt = new Date(Date.now() - 24 * 60 * 60 * 1000);
const expiresAtInputValue = expiresAt.toISOString().substring(0, 16);
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderPriceField).clear().type('0.1');
cy.getByTestId(orderSizeField).clear().type('1');
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_GTT');
cy.log('choosing yesterday');
cy.getByTestId('date-picker-field').type(expiresAtInputValue);
cy.getByTestId(placeOrderBtn).click();
cy.getByTestId('dealticket-error-message-expiry').should(
'have.text',
'The expiry date that you have entered appears to be in the past'
);
});
it('must see warning if price has too many digits after decimal place', function () {
// 7002-SORD-059
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_GTC');
cy.getByTestId(orderSizeField).clear().type('1');
cy.getByTestId(orderPriceField).clear().type('1.123456');
cy.getByTestId('dealticket-error-message-price-limit').should(
'have.text',
'Price accepts up to 5 decimal places'
);
});
});
describe('market order', () => {
before(() => {
cy.getByTestId(toggleMarket).click();
});
it('must not see the price unit', function () {
// 7002-SORD-019
cy.getByTestId(orderPriceField).should('not.exist');
});
it('must warn if order size input has too many digits after the decimal place', function () {
// 7002-SORD-016
cy.getByTestId(orderSizeField).clear().type('1.234');
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-size-market').should(
'have.text',
'Size must be whole numbers for this market'
);
});
it('must warn if order size is set to 0', function () {
cy.getByTestId(orderSizeField).clear().type('0');
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-size-market').should(
'have.text',
'Size cannot be lower than 1'
);
});
});
});
@@ -0,0 +1,173 @@
import * as Schema from '@vegaprotocol/types';
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import {
accountsQuery,
amendGeneralAccountBalance,
estimateOrderQuery,
} from '@vegaprotocol/mock';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import { createOrder } from '../support/create-order';
describe(
'account validation',
{ tags: '@regression', testIsolation: true },
() => {
describe('zero balance error', () => {
beforeEach(() => {
cy.setVegaWallet();
cy.mockTradingPage();
const accounts = accountsQuery();
amendGeneralAccountBalance(accounts, 'market-0', '0');
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Accounts', accounts);
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('should show an error if your balance is zero', () => {
cy.getByTestId('place-order').should('be.disabled');
// 7002-SORD-003
cy.getByTestId('dealticket-error-message-zero-balance').should(
'have.text',
'You need ' +
'tDAI' +
' in your wallet to trade in this market.See all your collateral.Make a deposit'
);
cy.getByTestId('deal-ticket-deposit-dialog-button').should('exist');
});
});
describe('not enough balance warning', () => {
beforeEach(() => {
cy.setVegaWallet();
cy.mockTradingPage();
const accounts = accountsQuery();
amendGeneralAccountBalance(accounts, 'market-0', '100000000');
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Accounts', accounts);
});
cy.mockGQL((req) => {
aliasGQLQuery(req, 'EstimateOrder', estimateOrderQuery());
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('should display info and button for deposit', () => {
// 7002-SORD-003
// warning should show immediately
cy.getByTestId('dealticket-warning-margin').should(
'contain.text',
'You may not have enough margin available to open this position'
);
cy.getByTestId('dealticket-warning-margin').should(
'contain.text',
'You may not have enough margin available to open this position. 2,354.72283 tDAI is currently required. You have only 1,000.01 tDAI available.'
);
cy.getByTestId('deal-ticket-deposit-dialog-button').click();
cy.getByTestId('dialog-content')
.find('h1')
.eq(0)
.should('have.text', 'Deposit');
});
});
describe('must submit order', { tags: '@smoke' }, () => {
// 7002-SORD-039
beforeEach(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('must see a prompt to check connected vega wallet to approve transaction', () => {
// 0003-WTXN-002
cy.mockVegaWalletTransaction(1000);
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
size: '100',
};
createOrder(order);
cy.getByTestId('toast-content').should(
'contain.text',
'Please go to your Vega wallet application and approve or reject the transaction.'
);
});
it('must show error returned by wallet ', () => {
// 0003-WTXN-009
// 0003-WTXN-011
// 0002-WCON-016
// 0003-WTXN-008
//trigger error from the wallet
cy.intercept('POST', 'http://localhost:1789/api/v2/requests', (req) => {
req.on('response', (res) => {
res.send({
jsonrpc: '2.0',
id: '1',
});
});
});
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
size: '100',
};
createOrder(order);
cy.getByTestId('toast-content').should(
'contain.text',
'The connection to your Vega Wallet has been lost.'
);
cy.getByTestId('connect-vega-wallet').click();
cy.getByTestId('dialog-content').should('be.visible');
});
it('must see that the order was rejected by the connected wallet', () => {
// 0003-WTXN-007
//trigger rejection error from the wallet
cy.intercept('POST', 'http://localhost:1789/api/v2/requests', (req) => {
req.alias = 'client.send_transaction';
req.reply({
statusCode: 400,
body: {
jsonrpc: '2.0',
error: {
code: 3001,
data: 'the user rejected the wallet connection',
message: 'User error',
},
id: '0',
},
});
});
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
size: '100',
};
createOrder(order);
cy.getByTestId('toast-content').should(
'contain.text',
'Error occurredthe user rejected the wallet connection'
);
});
});
}
);
@@ -0,0 +1,87 @@
import * as Schema from '@vegaprotocol/types';
import { testOrderSubmission } from '../support/order-validation';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import { createOrder } from '../support/create-order';
const displayTomorrow = () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return tomorrow.toISOString().substring(0, 16);
};
describe(
'must submit order for market in batch auction',
{ tags: '@regression' },
() => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_BATCH_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '50000',
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
postOnly: false,
reduceOnly: false,
price: '1.00',
expiresAt: displayTomorrow(),
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
postOnly: false,
reduceOnly: false,
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
});
});
}
);
@@ -0,0 +1,85 @@
import * as Schema from '@vegaprotocol/types';
import { testOrderSubmission } from '../support/order-validation';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import { createOrder } from '../support/create-order';
const displayTomorrow = () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return tomorrow.toISOString().substring(0, 16);
};
describe(
'must submit order for market in monitoring auction',
{ tags: '@regression' },
() => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
price: '50000',
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
price: '1.00',
expiresAt: displayTomorrow(),
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
});
});
}
);
@@ -0,0 +1,85 @@
import * as Schema from '@vegaprotocol/types';
import { testOrderSubmission } from '../support/order-validation';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import { createOrder } from '../support/create-order';
const displayTomorrow = () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return tomorrow.toISOString().substring(0, 16);
};
describe(
'must submit order for market in opening auction',
{ tags: '@regression' },
() => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_OPENING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '50000',
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
price: '1.00',
expiresAt: displayTomorrow(),
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
});
});
}
);
@@ -0,0 +1,68 @@
import * as Schema from '@vegaprotocol/types';
import {
TIFlist,
orderPriceField,
orderSizeField,
orderTIFDropDown,
placeOrderBtn,
toggleLimit,
toggleMarket,
} from '../support/deal-ticket';
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { accountsQuery } from '@vegaprotocol/mock';
describe('suspended market validation', { tags: '@regression' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
const accounts = accountsQuery();
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Accounts', accounts);
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('should show warning for market order', function () {
cy.getByTestId(toggleMarket).click();
cy.getByTestId(placeOrderBtn).should('not.be.disabled');
cy.getByTestId(placeOrderBtn).click();
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-type').should(
'have.text',
'This market is in auction until it reaches sufficient liquidity. Only limit orders are permitted when market is in auction'
);
});
it('should show info for allowed TIF', function () {
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderPriceField).clear().type('0.1');
cy.getByTestId(orderSizeField).clear().type('1');
cy.getByTestId(placeOrderBtn).should('be.enabled');
cy.getByTestId('dealticket-warning-auction').should(
'have.text',
'Any orders placed now will not trade until the auction ends'
);
});
it('should show warning for not allowed TIF', function () {
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderTIFDropDown).select(
TIFlist.filter((item) => item.code === 'FOK')[0].value
);
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-tif').should(
'have.text',
'This market is in auction until it reaches sufficient liquidity. Until the auction ends, you can only place GFA, GTT, or GTC limit orders'
);
});
});
@@ -1,580 +0,0 @@
import * as Schema from '@vegaprotocol/types';
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { testOrderSubmission } from '../support/order-validation';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import {
accountsQuery,
estimateOrderQuery,
amendGeneralAccountBalance,
} from '@vegaprotocol/mock';
import { createOrder } from '../support/create-order';
const orderSizeField = 'order-size';
const orderPriceField = 'order-price';
const orderTIFDropDown = 'order-tif';
const placeOrderBtn = 'place-order';
const toggleLimit = 'order-type-TYPE_LIMIT';
const toggleMarket = 'order-type-TYPE_MARKET';
const TIFlist = Object.values(Schema.OrderTimeInForce).map((value) => {
return {
code: Schema.OrderTimeInForceCode[value],
value,
text: Schema.OrderTimeInForceMapping[value],
};
});
const displayTomorrow = () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return tomorrow.toISOString().substring(0, 16);
};
describe('must submit order', { tags: '@smoke' }, () => {
// 7002-SORD-039
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places market buy order', () => {
// 7002-SORD-010
// 0003-WTXN-012
// 0003-WTXN-003
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
postOnly: false,
reduceOnly: false,
size: '100',
};
createOrder(order);
testOrderSubmission(order);
});
it('successfully places market sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC,
size: '100',
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order);
});
it('successfully places limit buy order', () => {
// 7002-SORD-017
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GFN,
size: '100',
postOnly: false,
reduceOnly: false,
price: '50000',
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
price: '1.00',
expiresAt: expiresAt.toISOString().substring(0, 16),
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
postOnly: false,
reduceOnly: false,
});
});
});
describe(
'must submit order for market in batch auction',
{ tags: '@regression' },
() => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_BATCH_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '50000',
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
postOnly: false,
reduceOnly: false,
price: '1.00',
expiresAt: displayTomorrow(),
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
postOnly: false,
reduceOnly: false,
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
});
});
}
);
describe(
'must submit order for market in opening auction',
{ tags: '@regression' },
() => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_OPENING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '50000',
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
price: '1.00',
expiresAt: displayTomorrow(),
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
});
});
}
);
describe(
'must submit order for market in monitoring auction',
{ tags: '@regression' },
() => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('successfully places limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
postOnly: false,
reduceOnly: false,
price: '200',
};
createOrder(order);
testOrderSubmission(order, { price: '20000000' });
});
it('successfully places limit sell order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
size: '100',
price: '50000',
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, { price: '5000000000' });
});
it('successfully places GTT limit buy order', () => {
cy.mockVegaWalletTransaction();
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
size: '100',
price: '1.00',
expiresAt: displayTomorrow(),
postOnly: false,
reduceOnly: false,
};
createOrder(order);
testOrderSubmission(order, {
price: '100000',
expiresAt:
new Date(order.expiresAt as string).getTime().toString() + '000000',
});
});
}
);
describe('suspended market validation', { tags: '@regression' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage(
Schema.MarketState.STATE_SUSPENDED,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET
);
const accounts = accountsQuery();
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Accounts', accounts);
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
beforeEach(() => {
cy.setVegaWallet();
});
it('should show warning for market order', function () {
cy.getByTestId(toggleMarket).click();
cy.getByTestId(placeOrderBtn).should('not.be.disabled');
cy.getByTestId(placeOrderBtn).click();
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-type').should(
'have.text',
'This market is in auction until it reaches sufficient liquidity. Only limit orders are permitted when market is in auction'
);
});
it('should show info for allowed TIF', function () {
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderPriceField).clear().type('0.1');
cy.getByTestId(orderSizeField).clear().type('1');
cy.getByTestId(placeOrderBtn).should('be.enabled');
cy.getByTestId('dealticket-warning-auction').should(
'have.text',
'Any orders placed now will not trade until the auction ends'
);
});
it('should show warning for not allowed TIF', function () {
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderTIFDropDown).select(
TIFlist.filter((item) => item.code === 'FOK')[0].value
);
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-tif').should(
'have.text',
'This market is in auction until it reaches sufficient liquidity. Until the auction ends, you can only place GFA, GTT, or GTC limit orders'
);
});
});
describe('account validation', { tags: '@regression' }, () => {
describe('zero balance error', () => {
beforeEach(() => {
cy.setVegaWallet();
cy.mockTradingPage();
const accounts = accountsQuery();
amendGeneralAccountBalance(accounts, 'market-0', '0');
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Accounts', accounts);
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('should show an error if your balance is zero', () => {
cy.getByTestId('place-order').should('be.disabled');
// 7002-SORD-003
cy.getByTestId('dealticket-error-message-zero-balance').should(
'have.text',
'You need ' +
'tDAI' +
' in your wallet to trade in this market.See all your collateral.Make a deposit'
);
cy.getByTestId('deal-ticket-deposit-dialog-button').should('exist');
});
});
describe('not enough balance warning', () => {
beforeEach(() => {
cy.setVegaWallet();
cy.mockTradingPage();
const accounts = accountsQuery();
amendGeneralAccountBalance(accounts, 'market-0', '100000000');
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Accounts', accounts);
});
cy.mockGQL((req) => {
aliasGQLQuery(req, 'EstimateOrder', estimateOrderQuery());
});
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('should display info and button for deposit', () => {
// 7002-SORD-003
// warning should show immediately
cy.getByTestId('dealticket-warning-margin').should(
'contain.text',
'You may not have enough margin available to open this position'
);
cy.getByTestId('dealticket-warning-margin').should(
'contain.text',
'You may not have enough margin available to open this position. 2,354.72283 tDAI is currently required. You have only 1,000.01 tDAI available.'
);
cy.getByTestId('deal-ticket-deposit-dialog-button').click();
cy.getByTestId('dialog-content')
.find('h1')
.eq(0)
.should('have.text', 'Deposit');
});
});
describe('must submit order', { tags: '@smoke' }, () => {
// 7002-SORD-039
beforeEach(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('must see a prompt to check connected vega wallet to approve transaction', () => {
// 0003-WTXN-002
cy.mockVegaWalletTransaction(1000);
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
size: '100',
};
createOrder(order);
cy.getByTestId('toast-content').should(
'contain.text',
'Please go to your Vega wallet application and approve or reject the transaction.'
);
});
it('must show error returned by wallet ', () => {
// 0003-WTXN-009
// 0003-WTXN-011
// 0002-WCON-016
// 0003-WTXN-008
//trigger error from the wallet
cy.intercept('POST', 'http://localhost:1789/api/v2/requests', (req) => {
req.on('response', (res) => {
res.send({
jsonrpc: '2.0',
id: '1',
});
});
});
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
size: '100',
};
createOrder(order);
cy.getByTestId('toast-content').should(
'contain.text',
'The connection to your Vega Wallet has been lost.'
);
cy.getByTestId('connect-vega-wallet').click();
cy.getByTestId('dialog-content').should('be.visible');
});
it('must see that the order was rejected by the connected wallet', () => {
// 0003-WTXN-007
//trigger rejection error from the wallet
cy.intercept('POST', 'http://localhost:1789/api/v2/requests', (req) => {
req.alias = 'client.send_transaction';
req.reply({
statusCode: 400,
body: {
jsonrpc: '2.0',
error: {
code: 3001,
data: 'the user rejected the wallet connection',
message: 'User error',
},
id: '0',
},
});
});
const order: OrderSubmission = {
marketId: 'market-0',
type: Schema.OrderType.TYPE_MARKET,
side: Schema.Side.SIDE_BUY,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_FOK,
size: '100',
};
createOrder(order);
cy.getByTestId('toast-content').should(
'contain.text',
'Error occurredthe user rejected the wallet connection'
);
});
});
});
@@ -0,0 +1,157 @@
import {
TIFlist,
orderTIFDropDown,
toggleLimit,
toggleMarket,
} from '../support/deal-ticket';
describe('time in force validation', { tags: '@smoke' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.clearAllLocalStorage();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('must have market order set up to IOC by default', function () {
// 7002-SORD-030
cy.getByTestId(toggleMarket).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'IOC')[0].text
);
});
it('must have time in force set to GTC for limit order', function () {
// 7002-SORD-031
cy.getByTestId(toggleLimit).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'GTC')[0].text
);
});
it('selections should be remembered', () => {
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_GTT');
cy.getByTestId(toggleMarket).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'IOC')[0].text
);
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_FOK');
cy.getByTestId(toggleLimit).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'GTT')[0].text
);
cy.getByTestId(toggleMarket).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'FOK')[0].text
);
});
describe('limit order', () => {
before(() => {
cy.getByTestId(toggleLimit).click();
});
const validTIF = TIFlist;
validTIF.forEach((tif) => {
// 7002-SORD-023
// 7002-SORD-024
// 7002-SORD-025
// 7002-SORD-026
// 7002-SORD-027
// 7002-SORD-028
it(`must be able to select ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
});
});
});
describe('market order', () => {
before(() => {
cy.getByTestId(toggleMarket).click();
});
const validTIF = TIFlist.filter((tif) => ['FOK', 'IOC'].includes(tif.code));
const invalidTIF = TIFlist.filter(
(tif) => !['FOK', 'IOC'].includes(tif.code)
);
validTIF.forEach((tif) => {
// 7002-SORD-025
// 7002-SORD-026
it(`must be able to select ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
});
});
invalidTIF.forEach((tif) => {
// 7002-SORD-023
// 7002-SORD-024
// 7002-SORD-027
// 7002-SORD-028
it(`must not be able to select ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).should('not.contain', tif.text);
});
});
});
describe('post and reduce - market order', () => {
before(() => {
cy.getByTestId(toggleMarket).click();
});
const validTIF = TIFlist.filter((tif) => ['FOK', 'IOC'].includes(tif.code));
validTIF.forEach((tif) => {
// 7002-SORD-025
// 7002-SORD-026
it(`post and reduce order market for ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
cy.getByTestId('post-only').should('be.disabled');
cy.getByTestId('reduce-only').should('be.enabled');
});
});
});
describe('post and reduce - limit order', () => {
before(() => {
cy.getByTestId(toggleLimit).click();
});
const validTIFLimit = TIFlist.filter((tif) =>
['GFA', 'GFN', 'GTC', 'GTT'].includes(tif.code)
);
validTIFLimit.forEach((tif) => {
it(`post and reduce order for limit ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
cy.getByTestId('post-only').should('be.enabled');
cy.getByTestId('reduce-only').should('be.disabled');
});
});
});
});
@@ -1,329 +0,0 @@
import * as Schema from '@vegaprotocol/types';
import { mockConnectWallet } from '@vegaprotocol/cypress';
const orderSizeField = 'order-size';
const orderPriceField = 'order-price';
const orderTIFDropDown = 'order-tif';
const placeOrderBtn = 'place-order';
const toggleShort = 'order-side-SIDE_SELL';
const toggleLong = 'order-side-SIDE_BUY';
const toggleLimit = 'order-type-TYPE_LIMIT';
const toggleMarket = 'order-type-TYPE_MARKET';
const TIFlist = Object.values(Schema.OrderTimeInForce).map((value) => {
return {
code: Schema.OrderTimeInForceCode[value],
value,
text: Schema.OrderTimeInForceMapping[value],
};
});
describe('time in force default values', () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('must have market order set up to IOC by default', function () {
// 7002-SORD-030
cy.getByTestId(toggleMarket).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'IOC')[0].text
);
});
it('must have time in force set to GTC for limit order', function () {
// 7002-SORD-031
cy.getByTestId(toggleLimit).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'GTC')[0].text
);
});
});
describe('deal ticket validation', { tags: '@smoke' }, () => {
beforeEach(() => {
cy.mockTradingPage();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('must show place order button and connect wallet if wallet is not connected', () => {
// 0003-WTXN-001
cy.getByTestId('connect-vega-wallet'); // Not connected
cy.getByTestId('order-connect-wallet').should('exist');
cy.getByTestId(placeOrderBtn).should('exist');
cy.getByTestId('deal-ticket-connect-wallet').should('exist');
});
it('must be able to select order direction - long/short', function () {
// 7002-SORD-004
cy.getByTestId(toggleShort).click().children('input').should('be.checked');
cy.getByTestId(toggleLong).click().children('input').should('be.checked');
});
it('must be able to select order type - limit/market', function () {
// 7002-SORD-005
// 7002-SORD-006
// 7002-SORD-007
cy.getByTestId(toggleLimit).click().children('input').should('be.checked');
cy.getByTestId(toggleMarket).click().children('input').should('be.checked');
});
it('order connect vega wallet button should connect', () => {
mockConnectWallet();
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderPriceField).clear().type('101');
cy.getByTestId('order-connect-wallet').click();
cy.getByTestId('dialog-content').should('be.visible');
cy.getByTestId('connectors-list')
.find('[data-testid="connector-jsonRpc"]')
.click();
cy.wait('@walletReq');
cy.getByTestId(placeOrderBtn).should('be.visible');
cy.getByTestId(toggleLimit).children('input').should('be.checked');
cy.getByTestId(orderPriceField).should('have.value', '101');
});
});
describe('deal ticket size validation', { tags: '@smoke' }, function () {
beforeEach(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
});
it('must warn if order size input has too many digits after the decimal place', function () {
// 7002-SORD-016
cy.getByTestId('order-type-TYPE_MARKET').click();
cy.getByTestId(orderSizeField).clear().type('1.234');
cy.getByTestId(placeOrderBtn).should('not.be.disabled');
cy.getByTestId(placeOrderBtn).click();
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-size-market').should(
'have.text',
'Size must be whole numbers for this market'
);
});
it('must warn if order size is set to 0', function () {
cy.getByTestId('order-type-TYPE_MARKET').click();
cy.getByTestId(orderSizeField).clear().type('0');
cy.getByTestId(placeOrderBtn).should('not.be.disabled');
cy.getByTestId(placeOrderBtn).click();
cy.getByTestId(placeOrderBtn).should('be.disabled');
cy.getByTestId('dealticket-error-message-size-market').should(
'have.text',
'Size cannot be lower than 1'
);
});
});
describe('limit order validations', { tags: '@smoke' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
cy.getByTestId(toggleLimit).click();
});
beforeEach(() => {
cy.setVegaWallet();
});
it('must see the price unit', function () {
// 7002-SORD-018
cy.getByTestId(orderPriceField)
.siblings('label')
.should('have.text', 'Price (DAI)');
});
it('must see warning when placing an order with expiry date in past', () => {
const expiresAt = new Date(Date.now() - 24 * 60 * 60 * 1000);
const expiresAtInputValue = expiresAt.toISOString().substring(0, 16);
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderPriceField).clear().type('0.1');
cy.getByTestId(orderSizeField).clear().type('1');
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_GTT');
cy.log('choosing yesterday');
cy.getByTestId('date-picker-field').type(expiresAtInputValue);
cy.getByTestId(placeOrderBtn).click();
cy.getByTestId('dealticket-error-message-expiry').should(
'have.text',
'The expiry date that you have entered appears to be in the past'
);
});
it('must see warning if price has too many digits after decimal place', function () {
// 7002-SORD-059
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_GTC');
cy.getByTestId(orderSizeField).clear().type('1');
cy.getByTestId(orderPriceField).clear().type('1.123456');
cy.getByTestId('dealticket-error-message-price-limit').should(
'have.text',
'Price accepts up to 5 decimal places'
);
});
describe('time in force validations', function () {
const validTIF = TIFlist;
validTIF.forEach((tif) => {
// 7002-SORD-023
// 7002-SORD-024
// 7002-SORD-025
// 7002-SORD-026
// 7002-SORD-027
// 7002-SORD-028
it(`must be able to select ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
});
});
it('selections should be remembered', () => {
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_GTT');
cy.getByTestId(toggleMarket).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'IOC')[0].text
);
cy.getByTestId(orderTIFDropDown).select('TIME_IN_FORCE_FOK');
cy.getByTestId(toggleLimit).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'GTT')[0].text
);
cy.getByTestId(toggleMarket).click();
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
TIFlist.filter((item) => item.code === 'FOK')[0].text
);
});
});
});
describe('market order validations', { tags: '@smoke' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
cy.getByTestId(toggleMarket).click();
});
beforeEach(() => {
cy.setVegaWallet();
});
it('must not see the price unit', function () {
// 7002-SORD-019
cy.getByTestId(orderPriceField).should('not.exist');
});
describe('time in force validations', function () {
const validTIF = TIFlist.filter((tif) => ['FOK', 'IOC'].includes(tif.code));
const invalidTIF = TIFlist.filter(
(tif) => !['FOK', 'IOC'].includes(tif.code)
);
validTIF.forEach((tif) => {
// 7002-SORD-025
// 7002-SORD-026
it(`must be able to select ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
});
});
invalidTIF.forEach((tif) => {
// 7002-SORD-023
// 7002-SORD-024
// 7002-SORD-027
// 7002-SORD-028
it(`must not be able to select ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).should('not.contain', tif.text);
});
});
});
});
describe('post and reduce order validations', { tags: '@smoke' }, () => {
before(() => {
cy.setVegaWallet();
cy.mockTradingPage();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
cy.getByTestId(toggleMarket).click();
});
beforeEach(() => {
cy.setVegaWallet();
});
const validTIF = TIFlist.filter((tif) => ['FOK', 'IOC'].includes(tif.code));
validTIF.forEach((tif) => {
// 7002-SORD-025
// 7002-SORD-026
it(`post and reduce order market for ${tif.code}`, function () {
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
cy.getByTestId('post-only').should('be.disabled');
cy.getByTestId('reduce-only').should('be.enabled');
});
});
validTIF.forEach((tif) => {
it(`post and reduce order limit for ${tif.code}`, function () {
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
cy.getByTestId('post-only').should('be.disabled');
cy.getByTestId('reduce-only').should('be.enabled');
});
});
const validTIFLimit = TIFlist.filter((tif) =>
['GFA', 'GFN', 'GTC', 'GTT'].includes(tif.code)
);
validTIFLimit.forEach((tif) => {
it(`post and reduce order for limit ${tif.code}`, function () {
cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderTIFDropDown).select(tif.value);
cy.get(`[data-testid=${orderTIFDropDown}] option:selected`).should(
'have.text',
tif.text
);
cy.getByTestId('post-only').should('be.enabled');
cy.getByTestId('reduce-only').should('be.disabled');
});
});
});
@@ -21,7 +21,7 @@ const cancelOrderBtn = 'cancel';
const cancelAllOrdersBtn = 'cancelAll';
const editOrderBtn = 'edit';
describe('orders list', { tags: '@smoke' }, () => {
describe('orders list', { tags: '@smoke', testIsolation: true }, () => {
beforeEach(() => {
const subscriptionMocks = getSubscriptionMocks();
cy.spy(subscriptionMocks, 'OrdersUpdate');
@@ -89,15 +89,17 @@ describe('orders list', { tags: '@smoke' }, () => {
cy.contains('Partially Filled').click();
cy.getByTestId('Orders').click();
cy.get(`[row-id="${partiallyFilledId}"]`).within(() => {
cy.get(`[col-id='${orderStatus}']`).should(
'have.text',
'Partially Filled'
);
cy.get(`[col-id='${orderRemaining}']`).should('have.text', '7/10');
cy.getByTestId(cancelOrderBtn).should('not.exist');
cy.getByTestId(editOrderBtn).should('not.exist');
});
cy.get(`[row-id="${partiallyFilledId}"]`)
.eq(1)
.within(() => {
cy.get(`[col-id='${orderStatus}']`).should(
'have.text',
'Partially Filled'
);
cy.get(`[col-id='${orderRemaining}']`).should('have.text', '7/10');
cy.getByTestId(cancelOrderBtn).should('not.exist');
cy.getByTestId(editOrderBtn).should('not.exist');
});
});
it('orders are sorted by most recent order', () => {
@@ -424,7 +426,7 @@ describe('amend and cancel order', { tags: '@smoke' }, () => {
.find(`[data-testid="cancel"]`)
.should('have.text', 'Cancel')
.then(($btn) => {
cy.wrap($btn).click();
cy.wrap($btn).click({ force: true });
const order: OrderCancellation = {
orderId: orderId,
marketId: 'market-0',
@@ -445,7 +447,7 @@ describe('amend and cancel order', { tags: '@smoke' }, () => {
cy.get(`[data-testid="cancelAll"]`)
.should('have.text', 'Cancel all')
.then(($btn) => {
cy.wrap($btn).click();
cy.wrap($btn).click({ force: true });
const order: OrderCancellation = {
marketId: 'market-0',
};
@@ -464,7 +466,7 @@ describe('amend and cancel order', { tags: '@smoke' }, () => {
.find('[data-testid="edit"]')
.should('have.text', 'Edit')
.then(($btn) => {
cy.wrap($btn).click();
cy.wrap($btn).click({ force: true });
cy.getByTestId('dialog-title').should('have.text', 'Edit order');
cy.get('#limitPrice').focus().clear().type('0.111111');
cy.getByTestId('edit-order').find('[type="submit"]').click();
@@ -8,7 +8,7 @@ beforeEach(() => {
cy.setVegaWallet();
});
describe('positions', { tags: '@smoke' }, () => {
describe('positions', { tags: '@smoke', testIsolation: true }, () => {
it('renders positions on trading page', () => {
cy.visit('/#/markets/market-0');
cy.getByTestId('Positions').click();
@@ -53,13 +53,17 @@ describe('positions', { tags: '@smoke' }, () => {
'currentLeverage',
'averageEntryPrice',
];
cy.getByTestId('tab-positions').within(() => {
cy.get('[row-id="market-2"]').within(() => {
emptyCells.forEach((cell) => {
cy.get(`[col-id="${cell}"]`).should('contain.text', '-');
});
cy.getByTestId('tab-positions')
.first()
.within(() => {
cy.get('[row-id="market-2"]')
.eq(1)
.within(() => {
emptyCells.forEach((cell) => {
cy.get(`[col-id="${cell}"]`).should('contain.text', '-');
});
});
});
});
});
it('error message should be displayed', () => {
const errors = [
@@ -2,7 +2,7 @@ import { connectEthereumWallet } from '../support/ethereum-wallet';
const connectEthWalletBtn = 'connect-eth-wallet-btn';
describe('ethereum wallet', { tags: '@smoke' }, () => {
describe('ethereum wallet', { tags: '@smoke', testIsolation: true }, () => {
beforeEach(() => {
cy.mockWeb3Provider();
// Using portfolio withdrawals tab is it requires Ethereum wallet connection
@@ -27,7 +27,7 @@ describe('ethereum wallet', { tags: '@smoke' }, () => {
cy.getByTestId('tab-deposits').should('not.be.empty');
});
it('should see an option to cancel the attempted connection', () => {
it('should see QR code modal for WalletConnect', () => {
// 0004-EWAL-003
cy.wait('@NetworkParams');
@@ -36,8 +36,8 @@ describe('ethereum wallet', { tags: '@smoke' }, () => {
cy.getByTestId('connect-eth-wallet-btn').click();
cy.getByTestId('web3-connector-list').should('exist');
cy.getByTestId('web3-connector-WalletConnect').click();
cy.get('#walletconnect-qrcode-text').should('exist');
cy.get('#walletconnect-qrcode-close').click();
// testing if exists rather than visible because of the long loading time
cy.get('w3m-modal').should('exist');
});
it('able to disconnect eth wallet', () => {
@@ -8,103 +8,115 @@ const manageVegaBtn = 'manage-vega-wallet';
const form = 'rest-connector-form';
const dialogContent = 'dialog-content';
describe('connect hosted wallet', { tags: '@smoke' }, () => {
beforeEach(() => {
// Using portfolio page as it requires vega wallet connection
cy.visit('/#/portfolio');
cy.mockTradingPage();
cy.mockSubscription();
cy.get('main[data-testid="/portfolio"]').should('exist');
});
it('can connect', () => {
// 0002-WCON-002
// 0002-WCON-003
// 0002-WCON-039
// 0002-WCON-017
// 0002-WCON-018
// 0002-WCON-019
// Mock authentication
cy.intercept('POST', 'https://wallet.testnet.vega.xyz/api/v1/auth/token', {
body: {
token: 'test-token',
},
describe(
'connect hosted wallet',
{ tags: '@smoke', testIsolation: true },
() => {
beforeEach(() => {
// Using portfolio page as it requires vega wallet connection
cy.visit('/#/portfolio');
cy.mockTradingPage();
cy.mockSubscription();
cy.get('main[data-testid="/portfolio"]').should('exist');
});
// Mock getting keys from wallet
cy.intercept('GET', 'https://wallet.testnet.vega.xyz/api/v1/keys', {
body: {
keys: [
{
algorithm: {
name: 'algo',
version: 1,
},
index: 0,
meta: [],
pub: 'HOSTED_PUBKEY',
tainted: false,
it('can connect', () => {
// 0002-WCON-002
// 0002-WCON-003
// 0002-WCON-039
// 0002-WCON-017
// 0002-WCON-018
// 0002-WCON-019
// Mock authentication
cy.intercept(
'POST',
'https://wallet.testnet.vega.xyz/api/v1/auth/token',
{
body: {
token: 'test-token',
},
],
},
}
);
// Mock getting keys from wallet
cy.intercept('GET', 'https://wallet.testnet.vega.xyz/api/v1/keys', {
body: {
keys: [
{
algorithm: {
name: 'algo',
version: 1,
},
index: 0,
meta: [],
pub: 'HOSTED_PUBKEY',
tainted: false,
},
],
},
});
cy.getByTestId(connectVegaBtn).click();
cy.contains(
'Choose wallet app to connect, or to change port or server URL enter a custom wallet location first'
);
cy.contains('Connect Vega wallet');
cy.contains('Hosted Fairground wallet');
cy.getByTestId('connectors-list')
.find('[data-testid="connector-hosted"]')
.click();
cy.getByTestId(form).find('#wallet').click().type('user');
cy.getByTestId(form).find('#passphrase').click().type('pass');
cy.getByTestId('rest-connector-form').find('button[type=submit]').click();
cy.getByTestId(manageVegaBtn).should('exist');
cy.getByTestId('manage-vega-wallet').click();
cy.getByTestId('keypair-list').should('exist');
});
cy.getByTestId(connectVegaBtn).click();
cy.contains(
'Choose wallet app to connect, or to change port or server URL enter a custom wallet location first'
);
cy.contains('Connect Vega wallet');
cy.contains('Hosted Fairground wallet');
cy.getByTestId('connectors-list')
.find('[data-testid="connector-hosted"]')
.click();
cy.getByTestId(form).find('#wallet').click().type('user');
cy.getByTestId(form).find('#passphrase').click().type('pass');
cy.getByTestId('rest-connector-form').find('button[type=submit]').click();
cy.getByTestId(manageVegaBtn).should('exist');
cy.getByTestId('manage-vega-wallet').click();
cy.getByTestId('keypair-list').should('exist');
});
it('doesnt connect with invalid credentials', () => {
// 0002-WCON-020
it('doesnt connect with invalid credentials', () => {
// 0002-WCON-020
// Mock incorrect username/password
cy.intercept('POST', 'https://wallet.testnet.vega.xyz/api/v1/auth/token', {
body: {
error: 'No wallet',
},
statusCode: 403, // 403 forbidden invalid crednetials
// Mock incorrect username/password
cy.intercept(
'POST',
'https://wallet.testnet.vega.xyz/api/v1/auth/token',
{
body: {
error: 'No wallet',
},
statusCode: 403, // 403 forbidden invalid crednetials
}
);
cy.getByTestId(connectVegaBtn).click();
cy.getByTestId('connectors-list')
.find('[data-testid="connector-hosted"]')
.click();
cy.getByTestId(form).find('#wallet').click().type('invalid name');
cy.getByTestId(form).find('#passphrase').click().type('invalid password');
cy.getByTestId('rest-connector-form').find('button[type=submit]').click();
cy.getByTestId('form-error').should('have.text', 'Invalid credentials');
});
cy.getByTestId(connectVegaBtn).click();
cy.getByTestId('connectors-list')
.find('[data-testid="connector-hosted"]')
.click();
cy.getByTestId(form).find('#wallet').click().type('invalid name');
cy.getByTestId(form).find('#passphrase').click().type('invalid password');
cy.getByTestId('rest-connector-form').find('button[type=submit]').click();
cy.getByTestId('form-error').should('have.text', 'Invalid credentials');
});
it('doesnt connect with empty fields', () => {
cy.getByTestId(connectVegaBtn).click();
cy.getByTestId('connectors-list')
.find('[data-testid="connector-hosted"]')
.click();
it('doesnt connect with empty fields', () => {
cy.getByTestId(connectVegaBtn).click();
cy.getByTestId('connectors-list')
.find('[data-testid="connector-hosted"]')
.click();
cy.getByTestId('rest-connector-form').find('button[type=submit]').click();
cy.getByTestId(form)
.find('#wallet')
.next('[data-testid="input-error-text"]')
.should('have.text', 'Required');
cy.getByTestId(form)
.find('#passphrase')
.next('[data-testid="input-error-text"]')
.should('have.text', 'Required');
});
});
cy.getByTestId('rest-connector-form').find('button[type=submit]').click();
cy.getByTestId(form)
.find('#wallet')
.next('[data-testid="input-error-text"]')
.should('have.text', 'Required');
cy.getByTestId(form)
.find('#passphrase')
.next('[data-testid="input-error-text"]')
.should('have.text', 'Required');
});
}
);
describe('connect vega wallet', { tags: '@smoke' }, () => {
describe('connect vega wallet', { tags: '@smoke', testIsolation: true }, () => {
beforeEach(() => {
// Using portfolio page as it requires vega wallet connection
cy.visit('/#/portfolio');
@@ -88,48 +88,54 @@ describe(
}
);
describe('withdraw actions', { tags: '@regression' }, () => {
beforeEach(() => {
cy.mockWeb3Provider();
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
describe(
'withdraw actions',
{ tags: '@regression', testIsolation: true },
() => {
beforeEach(() => {
cy.mockWeb3Provider();
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/portfolio');
cy.getByTestId(collateralTab).click();
cy.getByTestId(openTransferDialog).click();
cy.visit('/#/portfolio');
cy.getByTestId(collateralTab).click();
cy.getByTestId(openTransferDialog).click();
cy.wait('@Accounts');
cy.wait('@Assets');
cy.mockVegaWalletTransaction();
});
cy.wait('@Accounts');
cy.wait('@Assets');
cy.mockVegaWalletTransaction();
});
it('key to key transfers by select key', function () {
cy.getByTestId(transferForm).should('be.visible');
cy.getByTestId(transferForm).find(toAddressField).select(1);
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId(transferForm).find(amountField).type('1', { delay: 100 });
cy.getByTestId(transferForm).find(submitTransferBtn).click();
cy.getByTestId(toastContent).should(
'contain.text',
'Awaiting confirmation'
);
cy.getByTestId(toastCloseBtn).click();
});
it('key to key transfers by select key', function () {
cy.getByTestId(transferForm).should('be.visible');
cy.getByTestId(transferForm).find(toAddressField).select(1);
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId(transferForm).find(amountField).type('1', { delay: 100 });
cy.getByTestId(transferForm).find(submitTransferBtn).click();
cy.getByTestId(toastContent).should(
'contain.text',
'Awaiting confirmation'
);
cy.getByTestId(toastCloseBtn).click();
});
it('key to key transfers by enter manual key', function () {
cy.getByTestId(transferForm).should('be.visible');
cy.contains('Enter manually').click();
cy.getByTestId(transferForm)
.find(toAddressField)
.type('7f9cf07d3a9905b1a61a1069f7a758855da428bc0f4a97de87f48644bfc25535');
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId(transferForm).find(amountField).type('1', { delay: 100 });
cy.getByTestId(transferForm).find(submitTransferBtn).click();
cy.getByTestId(toastContent).should(
'contain.text',
'Awaiting confirmation'
);
cy.getByTestId(toastCloseBtn).click();
});
});
it('key to key transfers by enter manual key', function () {
cy.getByTestId(transferForm).should('be.visible');
cy.contains('Enter manually').click();
cy.getByTestId(transferForm)
.find(toAddressField)
.type(
'7f9cf07d3a9905b1a61a1069f7a758855da428bc0f4a97de87f48644bfc25535'
);
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId(transferForm).find(amountField).type('1', { delay: 100 });
cy.getByTestId(transferForm).find(submitTransferBtn).click();
cy.getByTestId(toastContent).should(
'contain.text',
'Awaiting confirmation'
);
cy.getByTestId(toastCloseBtn).click();
});
}
);
+51 -45
View File
@@ -70,54 +70,60 @@ describe('withdraw form validation', { tags: '@smoke' }, () => {
});
});
describe('withdraw actions', { tags: '@regression' }, () => {
// this is extremely ugly hack, but setting it properly in contract is too much effort for such simple validation
describe(
'withdraw actions',
{ tags: '@regression', testIsolation: true },
() => {
// this is extremely ugly hack, but setting it properly in contract is too much effort for such simple validation
// 1002-WITH-018
// 1002-WITH-018
const withdrawalThreshold =
Cypress.env('VEGA_ENV') === 'CUSTOM' ? '0.00' : '100.00';
before(() => {
cy.mockWeb3Provider();
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
const withdrawalThreshold =
Cypress.env('VEGA_ENV') === 'CUSTOM' ? '0.00' : '100.00';
before(() => {
cy.mockWeb3Provider();
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/portfolio');
cy.getByTestId('Withdrawals').click();
cy.getByTestId('withdraw-dialog-button').click();
cy.visit('/#/portfolio');
cy.getByTestId('Withdrawals').click();
connectEthereumWallet('MetaMask');
cy.getByTestId('withdraw-dialog-button').click();
cy.wait('@Accounts');
cy.wait('@Assets');
cy.mockVegaWalletTransaction();
});
// It also requires connection Ethereum wallet
connectEthereumWallet('MetaMask');
it('triggers transaction when submitted', () => {
// 1002-WITH-002
// 1002-WITH-003
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId('BALANCE_AVAILABLE_label').should(
'contain.text',
'Balance available'
);
cy.getByTestId('BALANCE_AVAILABLE_value').should(
'have.text',
'1,000.00001'
);
cy.getByTestId('WITHDRAWAL_THRESHOLD_label').should(
'contain.text',
'Delayed withdrawal threshold'
);
cy.getByTestId('WITHDRAWAL_THRESHOLD_value').should(
'contain.text',
withdrawalThreshold
);
cy.getByTestId('DELAY_TIME_label').should('contain.text', 'Delay time');
cy.getByTestId('DELAY_TIME_value').should('have.text', 'None');
cy.get(amountField).clear().type('10');
cy.getByTestId(submitWithdrawBtn).click();
cy.getByTestId('toast').should('contain.text', 'Awaiting confirmation');
});
});
cy.wait('@Accounts');
cy.wait('@Assets');
cy.mockVegaWalletTransaction();
});
it('triggers transaction when submitted', () => {
// 1002-WITH-002
// 1002-WITH-003
selectAsset(ASSET_SEPOLIA_TBTC);
cy.getByTestId('BALANCE_AVAILABLE_label').should(
'contain.text',
'Balance available'
);
cy.getByTestId('BALANCE_AVAILABLE_value').should(
'have.text',
'1,000.00001'
);
cy.getByTestId('WITHDRAWAL_THRESHOLD_label').should(
'contain.text',
'Delayed withdrawal threshold'
);
cy.getByTestId('WITHDRAWAL_THRESHOLD_value').should(
'contain.text',
withdrawalThreshold
);
cy.getByTestId('DELAY_TIME_label').should('contain.text', 'Delay time');
cy.getByTestId('DELAY_TIME_value').should('have.text', 'None');
cy.get(amountField).clear().type('10');
cy.getByTestId(submitWithdrawBtn).click();
cy.getByTestId('toast').should('contain.text', 'Awaiting confirmation');
});
}
);
@@ -0,0 +1,18 @@
import * as Schema from '@vegaprotocol/types';
export const orderSizeField = 'order-size';
export const orderPriceField = 'order-price';
export const orderTIFDropDown = 'order-tif';
export const placeOrderBtn = 'place-order';
export const toggleShort = 'order-side-SIDE_SELL';
export const toggleLong = 'order-side-SIDE_BUY';
export const toggleLimit = 'order-type-TYPE_LIMIT';
export const toggleMarket = 'order-type-TYPE_MARKET';
export const TIFlist = Object.values(Schema.OrderTimeInForce).map((value) => {
return {
code: Schema.OrderTimeInForceCode[value],
value,
text: Schema.OrderTimeInForceMapping[value],
};
});
+1
View File
@@ -2,6 +2,7 @@ import '@vegaprotocol/cypress';
import 'cypress-real-events/support';
import registerCypressGrep from '@cypress/grep';
import { addMockTradingPage } from './trading';
import 'cypress-mochawesome-reporter/register';
registerCypressGrep();
addMockTradingPage();
+2 -1
View File
@@ -11,4 +11,5 @@ NX_VEGA_TOKEN_URL=https://token.fairground.wtf
NX_VEGA_WALLET_URL=http://localhost:1789
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega/releases
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/main/announcements.json
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/main/announcements.json
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
@@ -1,5 +1,5 @@
import { DealTicketContainer } from '@vegaprotocol/deal-ticket';
import { MarketInfoContainer } from '@vegaprotocol/market-info';
import { MarketInfoAccordionContainer } from '@vegaprotocol/market-info';
import { OrderbookContainer } from '@vegaprotocol/market-depth';
import { OrderListContainer } from '@vegaprotocol/orders';
import { FillsContainer } from '@vegaprotocol/fills';
@@ -38,7 +38,7 @@ type MarketDependantView =
| typeof CandlesChartContainer
| typeof DepthChartContainer
| typeof DealTicketContainer
| typeof MarketInfoContainer
| typeof MarketInfoAccordionContainer
| typeof OrderbookContainer
| typeof TradesContainer;
@@ -56,7 +56,7 @@ const TradingViews = {
Depth: requiresMarket(DepthChartContainer),
Liquidity: requiresMarket(LiquidityContainer),
Ticket: requiresMarket(DealTicketContainer),
Info: requiresMarket(MarketInfoContainer),
Info: requiresMarket(MarketInfoAccordionContainer),
Orderbook: requiresMarket(OrderbookContainer),
Trades: requiresMarket(TradesContainer),
Positions: PositionsContainer,
@@ -13,8 +13,7 @@ import type { OnCellClickHandler } from '../../components/select-market';
import { Header, HeaderStat } from '../../components/header';
import { NO_MARKET } from './constants';
import { MarketMarkPrice } from '../../components/market-mark-price';
import { Last24hPriceChange } from '../../components/last-24h-price-change';
import { Last24hVolume } from '../../components/last-24h-volume';
import { Last24hPriceChange, Last24hVolume } from '@vegaprotocol/market-info';
import { MarketState } from '../../components/market-state';
import { HeaderStatMarketTradingMode } from '../../components/market-trading-mode';
import { MarketLiquiditySupplied } from '../../components/liquidity-supplied';
@@ -14,10 +14,9 @@ export const Web3Provider = ({ children }: { children: ReactNode }) => {
const { config, loading, error } = useEthereumConfig();
const { ETHEREUM_PROVIDER_URL, ETH_LOCAL_PROVIDER_URL, ETH_WALLET_MNEMONIC } =
useEnvironment();
const [connectors, initializeConnectors] = useWeb3ConnectStore((store) => [
store.connectors,
store.initialize,
]);
const connectors = useWeb3ConnectStore((store) => store.connectors);
const initializeConnectors = useWeb3ConnectStore((store) => store.initialize);
useEffect(() => {
if (config?.chain_id) {
@@ -14,9 +14,8 @@ import type { CandleClose } from '@vegaprotocol/types';
import type { MarketMaybeWithDataAndCandles } from '@vegaprotocol/market-list';
import { Link } from 'react-router-dom';
import { MarketMarkPrice } from '../market-mark-price';
import { Last24hPriceChange } from '../last-24h-price-change';
import { Last24hPriceChange, Last24hVolume } from '@vegaprotocol/market-info';
import { MarketTradingMode } from '../market-trading-mode';
import { Last24hVolume } from '../last-24h-volume';
import { Links, Routes } from '../../pages/client-router';
const ellipsisClasses = 'whitespace-nowrap overflow-hidden text-ellipsis';
@@ -23,26 +23,44 @@ const generateJsx = (context: VegaWalletContextShape) => {
);
};
it('Not connected', () => {
render(generateJsx({ pubKey: null } as VegaWalletContextShape));
describe('VegaWalletConnectButton', () => {
it('should fire dialog when not connected', () => {
render(generateJsx({ pubKey: null } as VegaWalletContextShape));
const button = screen.getByTestId('connect-vega-wallet');
expect(button).toHaveTextContent('Connect Vega wallet');
fireEvent.click(button);
expect(mockUpdateDialogOpen).toHaveBeenCalled();
});
const button = screen.getByTestId('connect-vega-wallet');
expect(button).toHaveTextContent('Connect Vega wallet');
fireEvent.click(button);
expect(mockUpdateDialogOpen).toHaveBeenCalled();
});
it('Connected', async () => {
const pubKey = { publicKey: '123456__123456', name: 'test' };
render(
generateJsx({
it('should retrieve keys when connected', async () => {
const pubKey = { publicKey: '123456__123456', name: 'test' };
const pubKey2 = { publicKey: '123456__123457', name: 'test2' };
render(
generateJsx({
pubKey: pubKey.publicKey,
pubKeys: [pubKey],
fetchPubKeys: () => Promise.resolve([pubKey, pubKey2]),
} as VegaWalletContextShape)
);
const button = screen.getByTestId('manage-vega-wallet');
expect(button).toHaveTextContent(truncateByChars(pubKey.publicKey));
userEvent.click(button);
expect(mockUpdateDialogOpen).not.toHaveBeenCalled();
});
it('should fetch keys when connected', async () => {
const pubKey = { publicKey: '123456__123456', name: 'test' };
const context = {
pubKey: pubKey.publicKey,
pubKeys: [pubKey],
} as VegaWalletContextShape)
);
} as VegaWalletContextShape;
render(generateJsx(context));
const button = screen.getByTestId('manage-vega-wallet');
expect(button).toHaveTextContent(truncateByChars(pubKey.publicKey));
userEvent.click(button);
expect(mockUpdateDialogOpen).not.toHaveBeenCalled();
const button = screen.getByTestId('manage-vega-wallet');
expect(button).toHaveTextContent(truncateByChars(pubKey.publicKey));
userEvent.click(button);
expect(mockUpdateDialogOpen).not.toHaveBeenCalled();
});
});
@@ -29,7 +29,7 @@ const MobileWalletButton = ({
isConnected?: boolean;
activeKey?: PubKey;
}) => {
const { pubKeys, selectPubKey, disconnect } = useVegaWallet();
const { pubKeys, selectPubKey, disconnect, fetchPubKeys } = useVegaWallet();
const openVegaWalletDialog = useVegaWalletDialogStore(
(store) => store.openVegaWalletDialog
);
@@ -46,9 +46,12 @@ const MobileWalletButton = ({
openVegaWalletDialog();
setDrawerOpen(false);
} else {
if (fetchPubKeys) {
fetchPubKeys();
}
setDrawerOpen(!drawerOpen);
}
}, [drawerOpen, isConnected, openVegaWalletDialog]);
}, [drawerOpen, fetchPubKeys, isConnected, openVegaWalletDialog]);
const iconClass = drawerOpen
? 'hidden'
@@ -145,8 +148,14 @@ export const VegaWalletConnectButton = () => {
(store) => store.openVegaWalletDialog
);
const openTransferDialog = useTransferDialog((store) => store.open);
const { pubKey, pubKeys, selectPubKey, disconnect, isReadOnly } =
useVegaWallet();
const {
pubKey,
pubKeys,
selectPubKey,
disconnect,
isReadOnly,
fetchPubKeys,
} = useVegaWallet();
const isConnected = pubKey !== null;
const activeKey = useMemo(() => {
@@ -162,7 +171,12 @@ export const VegaWalletConnectButton = () => {
trigger={
<DropdownMenuTrigger
data-testid="manage-vega-wallet"
onClick={() => setDropdownOpen((curr) => !curr)}
onClick={() => {
if (fetchPubKeys) {
fetchPubKeys();
}
setDropdownOpen(!dropdownOpen);
}}
>
{activeKey && (
<span className="uppercase">{activeKey.name}</span>
+2 -1
View File
@@ -33,6 +33,7 @@ import { ViewingBanner } from '../components/viewing-banner';
import { Banner } from '../components/banner';
import { AppLoader, DynamicLoader } from '../components/app-loader';
import { Navbar } from '../components/navbar';
import { ENV } from '../lib/config';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import { activeOrdersProvider } from '@vegaprotocol/orders';
@@ -144,7 +145,7 @@ const PartyData = () => {
const MaybeConnectEagerly = () => {
useVegaEagerConnect(Connectors);
useEthereumEagerConnect();
useEthereumEagerConnect(ENV.dsn);
const { pubKey, connect } = useVegaWallet();
const [searchParams] = useSearchParams();
@@ -10,14 +10,15 @@ declare global {
export const addConnectPublicKey = () => {
Cypress.Commands.add('connectPublicKey', (publicKey) => {
cy.getByTestId('connect-vega-wallet').then((connectWallet) => {
if (connectWallet.length) {
cy.get('aside [data-testid="connect-vega-wallet"]').click();
cy.getByTestId('connector-view').should('be.visible').click();
cy.getByTestId('address').click();
cy.getByTestId('address').type(publicKey);
cy.getByTestId('connect').click();
}
});
const connectVegaWaletBtn = Cypress.$(
`[data-testid="connect-vega-wallet"]`
);
if (connectVegaWaletBtn.length > 0) {
cy.get('aside [data-testid="connect-vega-wallet"]').click();
cy.getByTestId('connector-view').should('be.visible').click();
cy.getByTestId('address').click();
cy.getByTestId('address').type(publicKey);
cy.getByTestId('connect').click();
}
});
};
@@ -33,19 +33,27 @@ export function addVegaWalletConnect() {
Cypress.Commands.add('connectVegaWallet', (isMobile) => {
mockConnectWallet();
cy.highlight(`Connecting Vega Wallet`);
cy.get(
`[data-testid=connect-vega-wallet${isMobile ? '-mobile' : ''}]:visible`
).click();
cy.get('[data-testid=connectors-list]')
.find('[data-testid="connector-jsonRpc"]')
.click();
cy.wait('@walletReq');
cy.get('[data-testid=dialog-content]').should(
'contain.text',
'Successfully connected'
);
cy.getByTestId('dialog-close').click();
cy.get('[data-testid=dialog-content]').should('not.exist');
const connectVegaWalletButton = `[data-testid=connect-vega-wallet${
isMobile ? '-mobile' : ''
}]:visible`;
cy.get(connectVegaWalletButton).then((btn) => {
if (btn.length === 0) {
cy.log('could not find the button, perhaps already connected');
return;
}
cy.wrap(btn).click();
cy.get('[data-testid=connectors-list]')
.find('[data-testid="connector-jsonRpc"]')
.click();
cy.wait('@walletReq');
cy.get('[data-testid=dialog-content]').should(
'contain.text',
'Successfully connected'
);
cy.getByTestId('dialog-close').click();
cy.get('[data-testid=dialog-content]').should('not.exist');
});
});
}
+6
View File
@@ -19,6 +19,12 @@ const mockSocketServer = Cypress.env('VEGA_URL')
? new Server(Cypress.env('VEGA_URL').replace('http', 'ws'))
: null;
// DO NOT REMOVE: PASSTHROUGH for walletconnect
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const relayServer = new Server('wss://relay.walletconnect.com', {
mock: false,
});
export function addMockSubscription() {
Cypress.Commands.add(
'mockSubscription',
+2 -1
View File
@@ -18,6 +18,7 @@
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
"noFallthroughCasesInSwitch": true,
"sourceMap": false
}
}
+4 -2
View File
@@ -3,11 +3,13 @@ export const negativeClassNames = 'text-vega-pink dark:text-vega-pink';
const isPositive = ({ value }: { value: string | bigint | number }) =>
!!value &&
((typeof value === 'string' && !value.startsWith('-')) || value > 0);
((typeof value === 'string' && !value.startsWith('-')) ||
((typeof value === 'number' || typeof value === 'bigint') && value > 0));
const isNegative = ({ value }: { value: string | bigint | number }) =>
!!value &&
((typeof value === 'string' && value.startsWith('-')) || value < 0);
((typeof value === 'string' && value.startsWith('-')) ||
((typeof value === 'number' || typeof value === 'bigint') && value < 0));
export const signedNumberCssClass = (value: string | bigint | number) => {
if (isPositive({ value })) {
+8 -1
View File
@@ -1,6 +1,7 @@
import type { StateCreator } from 'zustand';
import { act } from 'react-dom/test-utils';
const { create: actualCreate } = jest.requireActual('zustand'); // if using jest
const { create: actualCreate, useStore: actualUseStore } =
jest.requireActual('zustand'); // if using jest
// a variable to hold reset functions for all stores declared in the app
const storeResetFns = new Set<() => void>();
@@ -15,7 +16,13 @@ export const create =
return store;
};
export const createStore = create;
export const useStore = actualUseStore;
// Reset all stores after each test run
beforeEach(() => {
act(() => storeResetFns.forEach((resetFn) => resetFn()));
});
// also export default as web3-react internals import and use zustand as the default import
export default create;
@@ -16,19 +16,18 @@ export const useInitialMargin = (
order?: OrderSubmissionBody['orderSubmission']
) => {
const { pubKey } = useVegaWallet();
const commonVariables = { marketId, partyId: pubKey || '' };
const { data: marketData } = useDataProvider({
dataProvider: marketDataProvider,
variables: { marketId },
});
const { data: activeVolumeAndMargin } = useDataProvider({
dataProvider: volumeAndMarginProvider,
variables: commonVariables,
variables: { marketId, partyId: pubKey || '' },
skip: !pubKey,
});
const { data: marketInfo } = useDataProvider({
dataProvider: marketInfoProvider,
variables: commonVariables,
variables: { marketId },
});
let totalMargin = '0';
let margin = '0';
+3 -1
View File
@@ -35,6 +35,7 @@ import {
ETHEREUM_EAGER_CONNECT,
useWeb3ConnectStore,
getChainName,
useWeb3Disconnect,
} from '@vegaprotocol/web3';
import type { DepositBalances } from './use-deposit-balances';
import { FaucetNotification } from './faucet-notification';
@@ -448,11 +449,12 @@ const DisconnectEthereumButton = ({
}) => {
const { connector } = useWeb3React();
const [, , removeEagerConnector] = useLocalStorage(ETHEREUM_EAGER_CONNECT);
const disconnect = useWeb3Disconnect(connector);
return (
<ButtonLink
onClick={() => {
connector.deactivate();
disconnect();
removeEagerConnector();
onDisconnect();
}}
+2
View File
@@ -1,2 +1,4 @@
export * from './market-info';
export * from './last-24h-price-change';
export * from './last-24h-volume';
export * from './fees-breakdown';
@@ -9,7 +9,6 @@ import { PriceChangeCell } from '@vegaprotocol/datagrid';
import * as Schema from '@vegaprotocol/types';
import type { CandleClose } from '@vegaprotocol/types';
import { marketCandlesProvider } from '@vegaprotocol/market-list';
import { THROTTLE_UPDATE_TIME } from '../constants';
interface Props {
marketId?: string;
@@ -28,18 +27,15 @@ export const Last24hPriceChange = ({
}: Props) => {
const [ref, inView] = useInView({ root: inViewRoot?.current });
const yesterday = useYesterday();
const { data, error } = useThrottledDataProvider(
{
dataProvider: marketCandlesProvider,
variables: {
marketId: marketId || '',
interval: Schema.Interval.INTERVAL_I1H,
since: new Date(yesterday).toISOString(),
},
skip: !marketId || !inView,
const { data, error } = useThrottledDataProvider({
dataProvider: marketCandlesProvider,
variables: {
marketId: marketId || '',
interval: Schema.Interval.INTERVAL_I1H,
since: new Date(yesterday).toISOString(),
},
THROTTLE_UPDATE_TIME
);
skip: !marketId || !inView,
});
const candles =
data
@@ -10,7 +10,6 @@ import {
useYesterday,
} from '@vegaprotocol/react-helpers';
import * as Schema from '@vegaprotocol/types';
import { THROTTLE_UPDATE_TIME } from '../constants';
interface Props {
marketId?: string;
@@ -30,18 +29,15 @@ export const Last24hVolume = ({
const yesterday = useYesterday();
const [ref, inView] = useInView({ root: inViewRoot?.current });
const { data } = useThrottledDataProvider(
{
dataProvider: marketCandlesProvider,
variables: {
marketId: marketId || '',
interval: Schema.Interval.INTERVAL_I1H,
since: new Date(yesterday).toISOString(),
},
skip: !(inView && marketId),
const { data } = useThrottledDataProvider({
dataProvider: marketCandlesProvider,
variables: {
marketId: marketId || '',
interval: Schema.Interval.INTERVAL_I1H,
since: new Date(yesterday).toISOString(),
},
THROTTLE_UPDATE_TIME
);
skip: !(inView && marketId),
});
const candleVolume = data ? calcCandleVolume(data) : initialValue;
return (
<span ref={ref}>
@@ -1,5 +1,5 @@
export * from './info-key-value-table';
export * from './info-market';
export * from './market-info-accordion';
export * from './tooltip-mapping';
export * from './__generated__/MarketInfo';
export * from './market-info-data-provider';
@@ -17,7 +17,7 @@ import { tooltipMapping } from './tooltip-mapping';
import type { ReactNode } from 'react';
interface RowProps {
field: string;
value: unknown;
value: ReactNode;
decimalPlaces?: number;
asPercentage?: boolean;
unformatted?: boolean;
@@ -36,8 +36,8 @@ const Row = ({
}: RowProps) => {
const className = 'text-black dark:text-white text-sm !px-0';
const getFormattedValue = (value: unknown) => {
if (typeof value !== 'string' && typeof value !== 'number') return null;
const getFormattedValue = (value: ReactNode) => {
if (typeof value !== 'string' && typeof value !== 'number') return value;
if (unformatted || isNaN(Number(value))) {
return value;
}
@@ -50,7 +50,7 @@ const Row = ({
return `${formatNumber(Number(value))} ${assetSymbol}`;
};
const formattedValue: string | number | null = getFormattedValue(value);
const formattedValue = getFormattedValue(value);
if (!formattedValue) return null;
return (
@@ -70,11 +70,10 @@ const Row = ({
};
export interface MarketInfoTableProps {
data: unknown;
data: Record<string, ReactNode> | null | undefined;
decimalPlaces?: number;
asPercentage?: boolean;
unformatted?: boolean;
omits?: string[];
children?: ReactNode;
assetSymbol?: string;
noBorder?: boolean;
@@ -85,7 +84,6 @@ export const MarketInfoTable = ({
decimalPlaces,
asPercentage,
unformatted,
omits = ['__typename'],
children,
assetSymbol,
noBorder,
@@ -96,20 +94,18 @@ export const MarketInfoTable = ({
return (
<>
<KeyValueTable>
{Object.entries(data)
.filter(([key]) => !omits.includes(key))
.map(([key, value]) => (
<Row
key={key}
field={key}
value={value}
decimalPlaces={decimalPlaces}
assetSymbol={assetSymbol}
asPercentage={asPercentage}
unformatted={unformatted}
noBorder={noBorder}
/>
))}
{Object.entries(data).map(([key, value]) => (
<Row
key={key}
field={key}
value={value}
decimalPlaces={decimalPlaces}
assetSymbol={assetSymbol}
asPercentage={asPercentage}
unformatted={unformatted}
noBorder={noBorder}
/>
))}
</KeyValueTable>
<div className="flex flex-col gap-2">{children}</div>
</>
@@ -1,7 +1,7 @@
import { useEnvironment } from '@vegaprotocol/environment';
import { removePaginationWrapper, TokenLinks } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider, useYesterday } from '@vegaprotocol/react-helpers';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import * as Schema from '@vegaprotocol/types';
import {
Accordion,
@@ -11,12 +11,11 @@ import {
Splash,
TinyScroll,
} from '@vegaprotocol/ui-toolkit';
import { useMemo } from 'react';
import { generatePath, Link } from 'react-router-dom';
import { marketInfoWithDataAndCandlesProvider } from './market-info-data-provider';
import { marketInfoProvider } from './market-info-data-provider';
import type { MarketInfoWithDataAndCandles } from './market-info-data-provider';
import type { MarketInfo } from './market-info-data-provider';
import { MarketProposalNotification } from '@vegaprotocol/proposals';
import {
CurrentFeesInfoPanel,
@@ -37,8 +36,8 @@ import {
SettlementAssetInfoPanel,
} from './market-info-panels';
export interface InfoProps {
market: MarketInfoWithDataAndCandles;
export interface MarketInfoAccordionProps {
market: MarketInfo;
onSelect?: (id: string, metaKey?: boolean) => void;
}
@@ -46,34 +45,21 @@ export interface MarketInfoContainerProps {
marketId: string;
onSelect?: (id: string, metaKey?: boolean) => void;
}
export const MarketInfoContainer = ({
export const MarketInfoAccordionContainer = ({
marketId,
onSelect,
}: MarketInfoContainerProps) => {
const yesterday = useYesterday();
const yTimestamp = useMemo(() => {
return new Date(yesterday).toISOString();
}, [yesterday]);
const variables = useMemo(
() => ({
marketId,
since: yTimestamp,
interval: Schema.Interval.INTERVAL_I1H,
}),
[marketId, yTimestamp]
);
const { data, loading, error, reload } = useDataProvider({
dataProvider: marketInfoWithDataAndCandlesProvider,
dataProvider: marketInfoProvider,
skipUpdates: true,
variables,
variables: { marketId },
});
return (
<AsyncRenderer data={data} loading={loading} error={error} reload={reload}>
{data ? (
<TinyScroll className="h-full overflow-auto">
<Info market={data} onSelect={onSelect} />
<MarketInfoAccordion market={data} onSelect={onSelect} />
</TinyScroll>
) : (
<Splash>
@@ -84,7 +70,10 @@ export const MarketInfoContainer = ({
);
};
export const Info = ({ market, onSelect }: InfoProps) => {
const MarketInfoAccordion = ({
market,
onSelect,
}: MarketInfoAccordionProps) => {
const { VEGA_TOKEN_URL } = useEnvironment();
const headerClassName = 'uppercase text-lg';
@@ -3,15 +3,8 @@ import type {
MarketInfoQuery,
MarketInfoQueryVariables,
} from './__generated__/MarketInfo';
import {
marketDataProvider,
marketCandlesProvider,
} from '@vegaprotocol/market-list';
import type {
MarketData,
Candle,
MarketCandlesQueryVariables,
} from '@vegaprotocol/market-list';
import { marketDataProvider } from '@vegaprotocol/market-list';
import type { MarketData, Candle } from '@vegaprotocol/market-list';
import { MarketInfoDocument } from './__generated__/MarketInfo';
export type MarketInfo = NonNullable<MarketInfoQuery['market']>;
@@ -49,20 +42,3 @@ export const marketInfoWithDataProvider = makeDerivedDataProvider<
}
);
});
export const marketInfoWithDataAndCandlesProvider = makeDerivedDataProvider<
MarketInfoWithDataAndCandles,
never,
MarketCandlesQueryVariables
>([marketInfoProvider, marketDataProvider, marketCandlesProvider], (parts) => {
const market: MarketInfo | null = parts[0];
const marketData: MarketData | null = parts[1];
const candles: Candle[] | null = parts[2];
return (
market && {
...market,
data: marketData || undefined,
candles: candles || undefined,
}
);
});
@@ -3,8 +3,8 @@ import { useMemo } from 'react';
import { AssetDetailsTable, useAssetDataProvider } from '@vegaprotocol/assets';
import { t } from '@vegaprotocol/i18n';
import {
calcCandleVolume,
totalFeesPercentage,
marketDataProvider,
} from '@vegaprotocol/market-list';
import { ExternalLink, Splash } from '@vegaprotocol/ui-toolkit';
import {
@@ -18,8 +18,8 @@ import { MarketInfoTable } from './info-key-value-table';
import type {
MarketInfo,
MarketInfoWithData,
MarketInfoWithDataAndCandles,
} from './market-info-data-provider';
import { Last24hVolume } from '../last-24h-volume';
import BigNumber from 'bignumber.js';
import type { DataSourceDefinition, SignerKind } from '@vegaprotocol/types';
import { ConditionOperatorMapping } from '@vegaprotocol/types';
@@ -27,6 +27,7 @@ import { MarketTradingModeMapping } from '@vegaprotocol/types';
import { useEnvironment } from '@vegaprotocol/environment';
import type { Provider } from '@vegaprotocol/oracles';
import { useOracleProofs } from '@vegaprotocol/oracles';
import { useDataProvider } from '@vegaprotocol/react-helpers';
type PanelProps = Pick<
ComponentProps<typeof MarketInfoTable>,
@@ -37,14 +38,6 @@ type MarketInfoProps = {
market: MarketInfo;
};
type MarketInfoWithDataProps = {
market: MarketInfoWithData;
};
type MarketInfoWithDataAndCandlesProps = {
market: MarketInfoWithDataAndCandles;
};
export const CurrentFeesInfoPanel = ({
market,
...props
@@ -52,7 +45,9 @@ export const CurrentFeesInfoPanel = ({
<>
<MarketInfoTable
data={{
...market.fees.factors,
makerFee: market.fees.factors.makerFee,
infrastructureFee: market.fees.factors.infrastructureFee,
liquidityFee: market.fees.factors.liquidityFee,
totalFees: totalFeesPercentage(market.fees.factors),
}}
asPercentage={true}
@@ -69,18 +64,22 @@ export const CurrentFeesInfoPanel = ({
export const MarketPriceInfoPanel = ({
market,
...props
}: MarketInfoWithDataProps & PanelProps) => {
}: MarketInfoProps & PanelProps) => {
const assetSymbol =
market?.tradableInstrument.instrument.product?.settlementAsset.symbol || '';
const quoteUnit =
market?.tradableInstrument.instrument.product?.quoteName || '';
const { data } = useDataProvider({
dataProvider: marketDataProvider,
variables: { marketId: market.id },
});
return (
<>
<MarketInfoTable
data={{
markPrice: market.data?.markPrice,
bestBidPrice: market.data?.bestBidPrice,
bestOfferPrice: market.data?.bestOfferPrice,
markPrice: data?.markPrice,
bestBidPrice: data?.bestBidPrice,
bestOfferPrice: data?.bestOfferPrice,
quoteUnit: market.tradableInstrument.instrument.product.quoteName,
}}
decimalPlaces={market.decimalPlaces}
@@ -99,8 +98,11 @@ export const MarketPriceInfoPanel = ({
export const MarketVolumeInfoPanel = ({
market,
...props
}: MarketInfoWithDataAndCandlesProps & PanelProps) => {
const last24hourVolume = market.candles && calcCandleVolume(market.candles);
}: MarketInfoProps & PanelProps) => {
const { data } = useDataProvider({
dataProvider: marketDataProvider,
variables: { marketId: market.id },
});
const dash = (value: string | undefined) =>
value && value !== '0' ? value : '-';
@@ -108,12 +110,17 @@ export const MarketVolumeInfoPanel = ({
return (
<MarketInfoTable
data={{
'24hourVolume': dash(last24hourVolume),
openInterest: dash(market.data?.openInterest),
bestBidVolume: dash(market.data?.bestBidVolume),
bestOfferVolume: dash(market.data?.bestOfferVolume),
bestStaticBidVolume: dash(market.data?.bestStaticBidVolume),
bestStaticOfferVolume: dash(market.data?.bestStaticOfferVolume),
'24hourVolume': (
<Last24hVolume
marketId={market.id}
positionDecimalPlaces={market.positionDecimalPlaces}
/>
),
openInterest: dash(data?.openInterest),
bestBidVolume: dash(data?.bestBidVolume),
bestOfferVolume: dash(data?.bestOfferVolume),
bestStaticBidVolume: dash(data?.bestStaticBidVolume),
bestStaticOfferVolume: dash(data?.bestStaticOfferVolume),
}}
decimalPlaces={market.positionDecimalPlaces}
{...props}
@@ -176,7 +183,7 @@ export const InstrumentInfoPanel = ({
marketName: market.tradableInstrument.instrument.name,
code: market.tradableInstrument.instrument.code,
productType: market.tradableInstrument.instrument.product.__typename,
...market.tradableInstrument.instrument.product,
quoteName: market.tradableInstrument.instrument.product.quoteName,
}}
{...props}
/>
@@ -239,38 +246,52 @@ export const MetadataInfoPanel = ({
export const RiskModelInfoPanel = ({
market,
...props
}: MarketInfoProps & PanelProps) => (
<MarketInfoTable
data={market.tradableInstrument.riskModel}
unformatted={true}
omits={[]}
{...props}
/>
);
}: MarketInfoProps & PanelProps) => {
if (market.tradableInstrument.riskModel.__typename !== 'LogNormalRiskModel') {
return null;
}
const { tau, riskAversionParameter } = market.tradableInstrument.riskModel;
return (
<MarketInfoTable
data={{ tau, riskAversionParameter }}
unformatted
{...props}
/>
);
};
export const RiskParametersInfoPanel = ({
market,
...props
}: MarketInfoProps & PanelProps) => (
<MarketInfoTable
data={market.tradableInstrument.riskModel.params}
unformatted={true}
omits={[]}
{...props}
/>
);
}: MarketInfoProps & PanelProps) => {
if (market.tradableInstrument.riskModel.__typename === 'LogNormalRiskModel') {
const { r, sigma, mu } = market.tradableInstrument.riskModel.params;
return <MarketInfoTable data={{ r, sigma, mu }} unformatted {...props} />;
}
if (market.tradableInstrument.riskModel.__typename === 'SimpleRiskModel') {
const { factorLong, factorShort } =
market.tradableInstrument.riskModel.params;
return (
<MarketInfoTable
data={{ factorLong, factorShort }}
unformatted
{...props}
/>
);
}
return null;
};
export const RiskFactorsInfoPanel = ({
market,
...props
}: MarketInfoProps & PanelProps) => (
<MarketInfoTable
data={market.riskFactors}
unformatted={true}
omits={['market', '__typename']}
{...props}
/>
);
}: MarketInfoProps & PanelProps) => {
if (!market.riskFactors) {
return null;
}
const { short, long } = market.riskFactors;
return <MarketInfoTable data={{ short, long }} unformatted {...props} />;
};
export const PriceMonitoringBoundsInfoPanel = ({
market,
@@ -278,13 +299,17 @@ export const PriceMonitoringBoundsInfoPanel = ({
...props
}: {
triggerIndex: number;
} & MarketInfoWithDataProps &
} & MarketInfoProps &
PanelProps) => {
const { data } = useDataProvider({
dataProvider: marketDataProvider,
variables: { marketId: market.id },
});
const quoteUnit =
market?.tradableInstrument.instrument.product?.quoteName || '';
const trigger =
market.priceMonitoringSettings?.parameters?.triggers?.[triggerIndex];
const bounds = market.data?.priceMonitoringBounds?.[triggerIndex];
const bounds = data?.priceMonitoringBounds?.[triggerIndex];
if (!trigger) {
console.error(
`Could not find data for trigger ${triggerIndex} (market id: ${market.id})`
@@ -334,7 +359,11 @@ export const LiquidityMonitoringParametersInfoPanel = ({
<MarketInfoTable
data={{
triggeringRatio: market.liquidityMonitoringParameters.triggeringRatio,
...market.liquidityMonitoringParameters.targetStakeParameters,
timeWindow:
market.liquidityMonitoringParameters.targetStakeParameters.timeWindow,
scalingFactor:
market.liquidityMonitoringParameters.targetStakeParameters
.scalingFactor,
}}
{...props}
/>
@@ -343,17 +372,21 @@ export const LiquidityMonitoringParametersInfoPanel = ({
export const LiquidityInfoPanel = ({
market,
...props
}: MarketInfoWithDataProps & PanelProps) => {
}: MarketInfoProps & PanelProps) => {
const assetDecimals =
market.tradableInstrument.instrument.product.settlementAsset.decimals;
const assetSymbol =
market?.tradableInstrument.instrument.product?.settlementAsset.symbol || '';
const { data } = useDataProvider({
dataProvider: marketDataProvider,
variables: { marketId: market.id },
});
return (
<MarketInfoTable
data={{
targetStake: market.data && market.data.targetStake,
suppliedStake: market.data && market.data?.suppliedStake,
marketValueProxy: market.data && market.data.marketValueProxy,
targetStake: data?.targetStake,
suppliedStake: data?.suppliedStake,
marketValueProxy: data?.marketValueProxy,
}}
decimalPlaces={assetDecimals}
assetSymbol={assetSymbol}
@@ -365,12 +398,16 @@ export const LiquidityInfoPanel = ({
export const LiquidityPriceRangeInfoPanel = ({
market,
...props
}: MarketInfoWithDataProps & PanelProps) => {
}: MarketInfoProps & PanelProps) => {
const quoteUnit =
market?.tradableInstrument.instrument.product?.quoteName || '';
const liquidityPriceRange = formatNumberPercentage(
new BigNumber(market.lpPriceRange).times(100)
);
const { data } = useDataProvider({
dataProvider: marketDataProvider,
variables: { marketId: market.id },
});
return (
<>
<p className="text-xs mb-4">
@@ -386,20 +423,20 @@ export const LiquidityPriceRangeInfoPanel = ({
data={{
liquidityPriceRange: `${liquidityPriceRange} of mid price`,
lowestPrice:
market.data?.midPrice &&
data?.midPrice &&
`${addDecimalsFormatNumber(
new BigNumber(1)
.minus(market.lpPriceRange)
.times(market.data.midPrice)
.times(data.midPrice)
.toString(),
market.decimalPlaces
)} ${quoteUnit}`,
highestPrice:
market.data?.midPrice &&
data?.midPrice &&
`${addDecimalsFormatNumber(
new BigNumber(1)
.plus(market.lpPriceRange)
.times(market.data.midPrice)
.times(data.midPrice)
.toString(),
market.decimalPlaces
)} ${quoteUnit}`,
@@ -418,7 +455,15 @@ export const OracleInfoPanel = ({
const { VEGA_EXPLORER_URL, ORACLE_PROOFS_URL } = useEnvironment();
const { data } = useOracleProofs(ORACLE_PROOFS_URL);
return (
<MarketInfoTable data={product.dataSourceSpecBinding} {...props}>
<MarketInfoTable
data={{
settlementDataProperty:
product.dataSourceSpecBinding.settlementDataProperty,
tradingTerminationProperty:
product.dataSourceSpecBinding.tradingTerminationProperty,
}}
{...props}
>
<div
className="flex flex-col gap-2 mt-4"
data-testid="oracle-proof-links"
@@ -354,10 +354,10 @@ export const volumeAndMarginProvider = makeDerivedDataProvider<
partyId,
marketId,
}),
(callback, client, variables) =>
marketDataProvider(callback, client, { marketId: variables.marketId }),
(callback, client, variables) =>
marketInfoProvider(callback, client, { marketId: variables.marketId }),
(callback, client, { marketId }) =>
marketDataProvider(callback, client, { marketId }),
(callback, client, { marketId }) =>
marketInfoProvider(callback, client, { marketId }),
openVolumeDataProvider,
],
(data) => {
@@ -6,7 +6,7 @@ import { MockedProvider } from '@apollo/client/testing';
type Data = number;
type Delta = number;
type Variables = { partyId: string };
type Variables = { partyId: string; marketIds?: string[] };
const unsubscribe = jest.fn();
const reload = jest.fn();
@@ -156,6 +156,121 @@ describe('useDataProvider hook', () => {
expect(insert.mock.calls[1][0].insertionData).toEqual(insertionData);
});
it('calls dataProvider with updated variables if skip switched to true', async () => {
const { rerender } = render({
dataProvider,
variables: { partyId: '' },
skip: true,
});
expect(dataProvider).toBeCalledTimes(0);
rerender({
dataProvider,
variables,
});
expect(dataProvider).toBeCalledTimes(1);
expect(dataProvider.mock.calls[0][2]).toEqual(variables);
});
it('uses same data provider when rerendered with equal variables', async () => {
const { rerender } = render({
dataProvider,
variables: { ...variables, marketIds: ['a', 'b'] },
});
expect(dataProvider).toBeCalledTimes(1);
rerender({
dataProvider,
variables: { ...variables, marketIds: ['b', 'a'] },
});
expect(dataProvider).toBeCalledTimes(1);
rerender({
dataProvider,
variables: { ...variables },
});
expect(dataProvider).toBeCalledTimes(2);
});
it('calls new update and insert when replaced', async () => {
const { rerender } = render({
dataProvider,
update,
insert,
variables,
});
const data = 0;
const delta = 0;
const insertionData = 0;
const callback = dataProvider.mock.calls[0][0];
await act(async () => {
callback({ ...updateCallbackPayload, data });
});
const newUpdate = jest.fn();
const newInsert = jest.fn();
expect(update).toBeCalledTimes(2);
expect(insert).toBeCalledTimes(0);
rerender({ dataProvider, update: newUpdate, insert: newInsert, variables });
await act(async () => {
callback({
...updateCallbackPayload,
data: data,
delta,
isUpdate: true,
});
});
expect(newUpdate).toBeCalledTimes(1);
await act(async () => {
callback({
...updateCallbackPayload,
data,
insertionData,
isInsert: true,
});
});
expect(newUpdate).toBeCalledTimes(2);
expect(newInsert).toBeCalledTimes(1);
expect(update).toBeCalledTimes(2);
expect(insert).toBeCalledTimes(0);
});
it('skip updates if skipUpdates is true', async () => {
const { result, rerender } = render({
dataProvider,
update,
variables,
skipUpdates: true,
});
expect(update).toBeCalledTimes(1);
let data = 0;
const delta = 1;
const callback = dataProvider.mock.calls[0][0];
await act(async () => {
callback({ ...updateCallbackPayload, data });
});
expect(update).toBeCalledTimes(2);
expect(result.current.data).toEqual(data);
await act(async () => {
callback({
...updateCallbackPayload,
data: data + delta,
delta,
isUpdate: true,
});
});
expect(update).toBeCalledTimes(2);
expect(result.current.data).toEqual(data);
rerender({ dataProvider, variables, update });
expect(update).toBeCalledTimes(2);
await act(async () => {
callback({
...updateCallbackPayload,
data: (data = data + delta),
delta,
isUpdate: true,
});
});
expect(update).toBeCalledTimes(3);
expect(result.current.data).toEqual(data);
expect(dataProvider).toBeCalledTimes(1);
});
it('change data provider instance on variables change', async () => {
const { result, rerender } = render({ dataProvider, update, variables });
const callback = dataProvider.mock.calls[0][0];
@@ -63,6 +63,9 @@ export const useDataProvider = <
const reloadRef = useRef<((force?: boolean) => void) | undefined>(undefined);
const loadRef = useRef<Load<Data> | undefined>(undefined);
const variablesRef = useRef<Variables>(props.variables);
const updateRef = useRef(update);
const insertRef = useRef(insert);
const skipUpdatesRef = useRef(skipUpdates);
const variables = useMemo(() => {
if (
!isEqualWith(
@@ -91,54 +94,69 @@ export const useDataProvider = <
}
return Promise.reject();
}, []);
const callback = useCallback<UpdateCallback<Data, Delta>>(
(args) => {
const {
data,
delta,
error,
loading,
insertionData,
totalCount,
isInsert,
isUpdate,
} = args;
setError(error);
setLoading(loading);
// if update or insert function returns true it means that component handles updates
// component can use flush() which will call callback without delta and cause data state update
if (!loading) {
if (
isUpdate &&
!skipUpdates &&
update &&
update({ delta, data, totalCount })
) {
return;
}
if (isInsert && insert && insert({ insertionData, data, totalCount })) {
return;
}
const callback = useCallback<UpdateCallback<Data, Delta>>((args) => {
const {
data,
delta,
error,
loading,
insertionData,
totalCount,
isInsert,
isUpdate,
} = args;
setError(error);
setLoading(loading);
// if update or insert function returns true it means that component handles updates
// component can use flush() which will call callback without delta and cause data state update
if (!loading) {
if (
isUpdate &&
(skipUpdatesRef.current ||
(!skipUpdatesRef.current &&
updateRef.current &&
updateRef.current({ delta, data, totalCount })))
) {
return;
}
setTotalCount(totalCount);
setData(data);
if (!loading && !isUpdate && update) {
update({ data });
if (
isInsert &&
insertRef.current &&
insertRef.current({ insertionData, data, totalCount })
) {
return;
}
},
[update, insert, skipUpdates]
);
}
setTotalCount(totalCount);
setData(data);
if (!loading && !isUpdate && updateRef.current) {
updateRef.current({ data });
}
}, []);
useEffect(() => {
updateRef.current = update;
}, [update]);
useEffect(() => {
insertRef.current = insert;
}, [insert]);
useEffect(() => {
skipUpdatesRef.current = skipUpdates;
}, [skipUpdates]);
useEffect(() => {
setData(null);
setError(undefined);
setTotalCount(undefined);
if (update) {
update({ data: null });
if (updateRef.current) {
updateRef.current({ data: null });
}
if (skip) {
setLoading(false);
if (update) {
update({ data: null });
if (updateRef.current) {
updateRef.current({ data: null });
}
return;
}
@@ -157,7 +175,7 @@ export const useDataProvider = <
loadRef.current = undefined;
return unsubscribe();
};
}, [client, dataProvider, callback, variables, skip, update]);
}, [client, dataProvider, callback, variables, skip]);
return {
data,
loading,
@@ -175,7 +193,7 @@ export const useThrottledDataProvider = <
Variables extends OperationVariables = OperationVariables
>(
params: Omit<useDataProviderParams<Data, Delta, Variables>, 'update'>,
wait?: number
wait = 500
) => {
const [data, setData] = useState<Data | null>(null);
const dataRef = useRef<Data | null>(null);
@@ -80,6 +80,7 @@ export const useFetch = <T>(
}
data = (await response.json()) as T;
// @ts-ignore - 'error' in data
if (data && 'error' in data) {
// @ts-ignore - data.error
throw new Error(data.error);
@@ -12,6 +12,7 @@ interface DialogProps {
open: boolean;
onChange?: (isOpen: boolean) => void;
onCloseAutoFocus?: (e: Event) => void;
onInteractOutside?: (e: Event) => void;
title?: string;
icon?: ReactNode;
intent?: Intent;
@@ -24,6 +25,7 @@ export function Dialog({
open,
onChange,
onCloseAutoFocus,
onInteractOutside,
title,
icon,
intent,
@@ -66,6 +68,7 @@ export function Dialog({
<DialogPrimitives.Content
className={contentClasses}
onCloseAutoFocus={onCloseAutoFocus}
onInteractOutside={onInteractOutside}
data-testid={dataTestId}
>
<div className={wrapperClasses}>
@@ -55,9 +55,9 @@ export const Notification = ({
'bg-vega-light-100 dark:bg-vega-dark-100 ': intent === Intent.None,
'bg-vega-blue-300 dark:bg-vega-blue-700': intent === Intent.Primary,
'bg-vega-green-300 dark:bg-vega-green-700': intent === Intent.Success,
'bg-vega-orange-300 dark:bg-vega-orange-650':
'bg-vega-orange-300 dark:bg-vega-orange-700':
intent === Intent.Warning,
'bg-vega-pink-300 dark:bg-vega-pink-650': intent === Intent.Danger,
'bg-vega-pink-300 dark:bg-vega-pink-700': intent === Intent.Danger,
},
'border rounded p-2 flex items-start gap-2.5'
)}
@@ -26,7 +26,10 @@ export const Pagination = ({
onLast,
}: PaginationProps) => {
return (
<div className={'flex gap-2 my-2 items-center justify-center'}>
<div
className={'flex gap-2 my-2 items-center justify-center'}
data-testid="page-info"
>
{onFirst && (
<Button
size="sm"
+3
View File
@@ -31,6 +31,9 @@ export interface VegaWalletContextShape {
/** Transaction payload */
transaction: Transaction
) => Promise<TransactionResponse | null>;
/** Fetch public keys */
fetchPubKeys?: () => Promise<PubKey[] | null>;
}
export const VegaWalletContext = createContext<
+35 -1
View File
@@ -50,6 +50,7 @@ describe('VegaWalletProvider', () => {
connect: expect.any(Function),
disconnect: expect.any(Function),
sendTx: expect.any(Function),
fetchPubKeys: expect.any(Function || undefined),
});
// Connect
@@ -77,14 +78,47 @@ describe('VegaWalletProvider', () => {
expect(spyOnSend).toHaveBeenCalledWith(mockPubKeys[1].publicKey, {});
});
it('should fetch new keypairs', async () => {
const { result } = setup();
// Default state
expect(result.current).toEqual({
pubKey: null,
pubKeys: null,
isReadOnly: false,
selectPubKey: expect.any(Function),
connect: expect.any(Function),
disconnect: expect.any(Function),
sendTx: expect.any(Function),
fetchPubKeys: expect.any(Function),
});
// Connect
await act(async () => {
result.current.connect(restConnector);
result.current.selectPubKey(mockPubKeys[0].publicKey);
});
expect(spyOnConnect).toHaveBeenCalled();
expect(result.current.pubKeys).toHaveLength(mockPubKeys.length);
expect(result.current.pubKey).toBe(mockPubKeys[0].publicKey);
// Fetch pub keys
mockPubKeys.push({ publicKey: '333', name: 'public key 3' });
await act(async () => {
result.current.fetchPubKeys && result.current.fetchPubKeys();
});
expect(result.current.pubKeys).toHaveLength(mockPubKeys.length);
});
it('persists selected pubkey and disconnects', async () => {
const { result } = setup();
expect(result.current.pubKey).toBe(null);
await act(async () => {
result.current.connect(restConnector);
result.current.selectPubKey(mockPubKeys[0].publicKey);
});
expect(result.current.pubKey).toBe(mockPubKeys[1].publicKey);
expect(result.current.pubKey).toBe(mockPubKeys[0].publicKey);
// Disconnect
await act(async () => {
+34 -2
View File
@@ -21,7 +21,7 @@ export const VegaWalletProvider = ({ children }: VegaWalletProviderProps) => {
const [pubKey, setPubKey] = useState<string | null>(null);
const [isReadOnly, setIsReadOnly] = useState<boolean>(false);
// Arary of pubkeys retrieved from the connector
// Array of public keys retrieved from the connector
const [pubKeys, setPubKeys] = useState<PubKey[] | null>(null);
// Reference to the current connector instance
@@ -32,6 +32,28 @@ export const VegaWalletProvider = ({ children }: VegaWalletProviderProps) => {
LocalStorage.setItem(WALLET_KEY, pk);
}, []);
const fetchPubKeys = useCallback(async () => {
if (!connector.current) {
throw new Error('No connector');
}
try {
const keys = await connector.current.connect();
if (keys?.length) {
setPubKeys(keys);
setIsReadOnly(connector.current instanceof ViewConnector);
return keys;
} else {
return null;
}
} catch (err) {
if (err instanceof WalletClientError) {
throw err;
}
return null;
}
}, []);
const connect = useCallback(async (c: VegaConnector) => {
connector.current = c;
try {
@@ -95,8 +117,18 @@ export const VegaWalletProvider = ({ children }: VegaWalletProviderProps) => {
connect,
disconnect,
sendTx,
fetchPubKeys,
};
}, [isReadOnly, pubKey, pubKeys, selectPubKey, connect, disconnect, sendTx]);
}, [
isReadOnly,
pubKey,
pubKeys,
selectPubKey,
connect,
disconnect,
sendTx,
fetchPubKeys,
]);
return (
<VegaWalletContext.Provider value={contextValue}>
+2 -2
View File
@@ -30,13 +30,13 @@ export const useJsonRpcConnect = (onConnect: () => void) => {
// Check if wallet is configured for the same chain as the app
setStatus(Status.GettingChainId);
// Dont throw in when cypress is running as trading app relies on
// Do not throw in when cypress is running as trading app relies on
// mocks which result in a mismatch between chainId for app and
// chainId for wallet
if (!('Cypress' in window)) {
const chainIdResult = await connector.getChainId();
if (chainIdResult.chainID !== appChainId) {
// Throw wallet error for consitent error handling
// Throw wallet error for consistent error handling
throw ClientErrors.WRONG_NETWORK;
}
}
+5 -1
View File
@@ -1,6 +1,7 @@
import type { StateCreator } from 'zustand';
import { act } from 'react-dom/test-utils';
const { create: actualCreate } = jest.requireActual('zustand'); // if using jest
const { create: actualCreate, useStore: actualUseStore } =
jest.requireActual('zustand'); // if using jest
// a variable to hold reset functions for all stores declared in the app
const storeResetFns = new Set<() => void>();
@@ -15,6 +16,9 @@ export const create =
return store;
};
export const createStore = create;
export const useStore = actualUseStore;
// Reset all stores after each test run
beforeEach(() => {
act(() => storeResetFns.forEach((resetFn) => resetFn()));
+11 -10
View File
@@ -1,23 +1,24 @@
export * from './lib/constants';
export * from './lib/eip-1193-custom-bridge';
export * from './lib/ethereum-error';
export * from './lib/ethereum-transaction-dialog';
export * from './lib/url-connector';
export * from './lib/use-bridge-contract';
export * from './lib/use-eager-connect';
export * from './lib/use-token-contract';
export * from './lib/use-token-decimals';
export * from './lib/use-ethereum-config';
export * from './lib/use-ethereum-read-contract';
export * from './lib/use-ethereum-transaction';
export * from './lib/use-ethereum-transaction-updater';
export * from './lib/use-ethereum-transaction-store';
export * from './lib/use-ethereum-transaction-manager';
export * from './lib/use-ethereum-transaction-store';
export * from './lib/use-ethereum-transaction-updater';
export * from './lib/use-ethereum-transaction';
export * from './lib/use-ethereum-withdraw-approvals-manager';
export * from './lib/use-ethereum-withdraw-approvals-store';
export * from './lib/use-get-withdraw-delay';
export * from './lib/use-get-withdraw-threshold';
export * from './lib/ethereum-transaction-dialog';
export * from './lib/web3-provider';
export * from './lib/web3-connectors';
export * from './lib/use-token-contract';
export * from './lib/use-token-decimals';
export * from './lib/use-web3-disconnect';
export * from './lib/web3-connect-dialog';
export * from './lib/web3-connect-store';
export * from './lib/url-connector';
export * from './lib/eip-1193-custom-bridge';
export * from './lib/web3-connectors';
export * from './lib/web3-provider';
+7
View File
@@ -9,3 +9,10 @@ export const getChainName = (chainId: number | null | undefined) => {
const name = chainId ? ChainIdMap[chainId] : undefined;
return name || 'Unknown';
};
/**
* WalletConnect project id
* https://cloud.walletconnect.com/sign-in
*/
export const WALLETCONNECT_PROJECT_ID =
process.env['NX_WALLETCONNECT_PROJECT_ID'] || '';
+1 -1
View File
@@ -69,7 +69,7 @@ export class UrlConnector extends Connector {
const chainId = await this.provider!.request({ method: 'eth_chainId' });
this.actions.update({ chainId: Number(chainId) });
} catch (error) {
this.actions.reportError(error as Error);
this.onError?.(error as Error);
}
}
}

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