Compare commits

..
Author SHA1 Message Date
Edd cf6d6e70bc fix(explorer): cache more appropriately 2022-11-25 19:19:36 +00:00
Edd 9e2dc19426 fix(explorer): fix wss urls 2022-11-25 18:54:46 +00:00
Edd 344971d5a9 fix(explorer): remove old urls from default env 2022-11-25 16:57:08 +00:00
803 changed files with 12907 additions and 21556 deletions
@@ -0,0 +1,28 @@
inputs:
all:
description: 'Install all binaries'
default: false
version:
description: 'Vega version'
gobin:
description: 'GOBIN path'
default: '/home/runner/go/bin'
runs:
using: 'composite'
steps:
- name: Install Vega binaries
shell: bash
run: |
wget 'https://github.com/vegaprotocol/vega/releases/download/${{ inputs.version }}/vega-linux-amd64.zip' -q
unzip vega-linux-amd64.zip -d ${{ inputs.gobin }}
- name: Checkout vegawallet-dummy
uses: actions/checkout@v3
with:
repository: 'vegaprotocol/vegawallet-dummy'
path: './dummy'
- name: Install vegawallet-dummy binaries
shell: bash
run: go install
working-directory: ./dummy
@@ -1,6 +1,26 @@
inputs:
github-token:
description: 'github token'
runs:
using: 'composite'
steps:
- name: Checkout capsule
uses: actions/checkout@v2
with:
repository: vegaprotocol/vegacapsule
ref: main
token: ${{ inputs.github-token }}
path: './capsule'
- name: Build capsule
run: go install
shell: bash
working-directory: capsule
- name: Login to docker
shell: bash
run: echo -n ${{ inputs.github-token }} | docker login https://ghcr.io -u vega-ci-bot --password-stdin
- name: Start nomad
shell: bash
run: vegacapsule nomad &
@@ -1,10 +1,6 @@
inputs:
passphrase:
description: 'Wallet password'
outputs:
token:
description: 'api-token of wallet'
value: ${{ steps.generate-api-token.outputs.api-token }}
runs:
using: 'composite'
steps:
@@ -20,23 +16,10 @@ runs:
shell: bash
run: vega wallet import -w capsule_wallet --recovery-phrase-file ./frontend-monorepo/vegacapsule/recovery -p ./passphrase --home ~/.vegacapsule/testnet/wallet
- name: Generate second public key
shell: bash
run: vega wallet key generate -w capsule_wallet -p ./passphrase --home ~/.vegacapsule/testnet/wallet
- name: Import network
shell: bash
run: vega wallet network import --force --from-file ./frontend-monorepo/vegacapsule/wallet-config.toml --home ~/.vegacapsule/testnet/wallet
- name: Init api-token
shell: bash
run: vega wallet api-token init --home ~/.vegacapsule/testnet/wallet --passphrase-file passphrase
- name: Generate api-token
id: generate-api-token
shell: bash
run: echo api-token=$(vega wallet api-token generate --wallet-name capsule_wallet --tokens-passphrase-file passphrase --wallet-passphrase-file passphrase --home ~/.vegacapsule/testnet/wallet | grep -Eo '[a-zA-Z0-9]{64}') >> $GITHUB_OUTPUT
- name: Start service using capsule network
shell: bash
run: vega wallet service run -n DV --load-tokens --tokens-passphrase-file passphrase --no-version-check --automatic-consent --home ~/.vegacapsule/testnet/wallet &
run: vegawallet-dummy service run --network DV --wallet capsule_wallet --passphrase-file ./passphrase --home ~/.vegacapsule/testnet/wallet &
+1 -14
View File
@@ -3,10 +3,6 @@ inputs:
description: 'Recovery phrase'
passphrase:
description: 'Wallet password'
outputs:
token:
description: 'api-token of wallet'
value: ${{ steps.generate-api-token.outputs.api-token }}
runs:
using: 'composite'
steps:
@@ -34,15 +30,6 @@ runs:
shell: bash
run: vega wallet network import --from-url="https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml" --force --home ~/.vegacapsule/testnet/wallet
- name: Init api-token
shell: bash
run: vega wallet api-token init --home ~/.vegacapsule/testnet/wallet --passphrase-file passphrase
- name: Generate api-token
id: generate-api-token
shell: bash
run: echo api-token=$(vega wallet api-token generate --wallet-name UI_Trading_Test --tokens-passphrase-file passphrase --wallet-passphrase-file passphrase --home ~/.vegacapsule/testnet/wallet | grep -Eo '[a-zA-Z0-9]{64}') >> $GITHUB_OUTPUT
- name: Start service using stagnet3 network
shell: bash
run: vega wallet service run -n stagnet3 --load-tokens --tokens-passphrase-file passphrase --no-version-check --automatic-consent --home ~/.vegacapsule/testnet/wallet &
run: vegawallet-dummy service run --network stagnet3 --wallet UI_Trading_Test --passphrase-file ./passphrase --home ~/.vegacapsule/testnet/wallet &
@@ -26,6 +26,10 @@ on:
required: false
type: boolean
default: false
env:
GOBIN: /home/runner/go/bin
VEGA_VERSION: 'v0.62.1'
jobs:
manual:
name: Run Cypress tests -- manual trigger
@@ -39,6 +43,8 @@ jobs:
run: echo SKIP_NX_CACHE="--skip-nx-cache" >> $GITHUB_ENV
outputs:
vega-version: ${{env.VEGA_VERSION}}
gobin: ${{env.GOBIN}}
skip-cache: ${{env.SKIP_NX_CACHE}}
tags: ${{env.TAGS}}
@@ -48,5 +54,7 @@ jobs:
secrets: inherit
with:
project: ${{ inputs.project }}
vega-version: ${{needs.manual.outputs.vega-version}}
gobin: ${{needs.manual.outputs.gobin}}
skip-cache: ${{needs.manual.outputs.skip-cache}}
tags: ${{needs.manual.outputs.tags}}
@@ -13,5 +13,7 @@ jobs:
secrets: inherit
with:
project: '[console-lite-e2e, explorer-e2e, liquidity-provision-dashboard-e2e, stats-e2e, token-e2e, trading-e2e]'
vega-version: 'v0.62.1'
gobin: /home/runner/go/bin
tags: --env.grepTags '[ @smoke, @regression, @slow ]'
night-run: true
+10 -1
View File
@@ -11,6 +11,11 @@ on:
- reopened
- synchronize
- ready_for_review
env:
GOBIN: /home/runner/go/bin
VEGA_VERSION: 'v0.62.1'
jobs:
pr:
runs-on: ubuntu-latest
@@ -51,6 +56,8 @@ jobs:
outputs:
projects: ${{ env.AFFECTED }}
vega-version: ${{ env.VEGA_VERSION }}
gobin: ${{ env.GOBIN }}
dispatch:
needs: pr
@@ -58,4 +65,6 @@ jobs:
secrets: inherit
with:
project: ${{ needs.pr.outputs.projects }}
tags: "--env.grepTags='[ @smoke, @regression ]'"
vega-version: ${{needs.pr.outputs.vega-version}}
gobin: ${{needs.pr.outputs.gobin}}
tags: "--env.grepTags='@smoke'"
+20 -4
View File
@@ -7,6 +7,13 @@ on:
required: true
type: string
default: 'false'
vega-version:
required: true
type: string
gobin:
required: false
type: string
default: /home/runner/go/bin
skip-cache:
required: false
type: string
@@ -19,8 +26,9 @@ jobs:
if: ${{ inputs.trigger == 'true' }}
runs-on: self-hosted
steps:
- name: Vega version
run: vega version
# Add GOBIN to PATH
- name: Add GOBIN to PATH
run: echo ${{ inputs.gobin }} >> $GITHUB_PATH
# Checkout front ends
- name: Checkout frontend mono repo
@@ -43,12 +51,21 @@ jobs:
run: yarn install --frozen-lockfile
working-directory: frontend-monorepo
#######
## Build and run Vegacapsule network
#######
- name: Install Vega binaries
uses: ./frontend-monorepo/.github/actions/install-vega-binaries
with:
version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
######
## Setup a Vega wallet for our user
######
- name: Set up Vegawallet
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet
with:
recovery: ${{ secrets.TRADING_TEST_VEGA_WALLET_RECOVERY }}
@@ -66,4 +83,3 @@ jobs:
CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}
+18 -9
View File
@@ -7,6 +7,13 @@ on:
required: true
type: string
default: 'false'
vega-version:
required: true
type: string
gobin:
required: false
type: string
default: /home/runner/go/bin
skip-cache:
required: false
type: string
@@ -24,11 +31,9 @@ jobs:
runs-on: self-hosted
timeout-minutes: 30
steps:
- name: Vega version
run: vega version
- name: Vegacapsule version
run: vegacapsule version
# Add GOBIN to PATH
- name: Add GOBIN to PATH
run: echo ${{ inputs.gobin }} >> $GITHUB_PATH
# Checkout front ends
- name: Checkout frontend mono repo
@@ -55,15 +60,22 @@ jobs:
## Build and run Vegacapsule network
#######
- name: Install Vega binaries
uses: ./frontend-monorepo/.github/actions/install-vega-binaries
with:
version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
- name: Build and run Vegacapsule network
uses: ./frontend-monorepo/.github/actions/run-vegacapsule
with:
github-token: ${{ secrets.VEGA_CI_BOT_GITHUB_TOKEN }}
######
## Setup a Vega wallet for our user
######
- name: Set up Vegawallet for docker
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet-docker
with:
passphrase: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
@@ -85,7 +97,6 @@ jobs:
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_NIGHTLY_RUN: ${{ inputs.night-run }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}
######
## Upload logs
@@ -93,10 +104,8 @@ jobs:
- name: Logs
run: vegacapsule network logs > vega-capsule-logs.txt
if: ${{ always() }}
- uses: actions/upload-artifact@v2
if: ${{ always() }}
with:
name: logs
path: ./vega-capsule-logs.txt
+18 -9
View File
@@ -7,6 +7,13 @@ on:
required: true
type: string
default: 'false'
vega-version:
required: true
type: string
gobin:
required: false
type: string
default: /home/runner/go/bin
skip-cache:
required: false
type: string
@@ -20,11 +27,9 @@ jobs:
runs-on: self-hosted
timeout-minutes: 60
steps:
- name: Vega version
run: vega version
- name: Vegacapsule version
run: vegacapsule version
# Add GOBIN to PATH
- name: Add GOBIN to PATH
run: echo ${{ inputs.gobin }} >> $GITHUB_PATH
# Checkout front ends
- name: Checkout frontend mono repo
@@ -51,15 +56,22 @@ jobs:
## Build and run Vegacapsule network
#######
- name: Install Vega binaries
uses: ./frontend-monorepo/.github/actions/install-vega-binaries
with:
version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
- name: Build and run Vegacapsule network
uses: ./frontend-monorepo/.github/actions/run-vegacapsule
with:
github-token: ${{ secrets.VEGA_CI_BOT_GITHUB_TOKEN }}
######
## Setup a Vega wallet for our user
######
- name: Set up Vegawallet for docker
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet-docker
with:
passphrase: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
@@ -80,7 +92,6 @@ jobs:
CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}
######
## Upload logs
@@ -88,10 +99,8 @@ jobs:
- name: Logs
run: vegacapsule network logs > vega-capsule-logs.txt
if: ${{ always() }}
- uses: actions/upload-artifact@v2
if: ${{ always() }}
with:
name: logs
path: ./vega-capsule-logs.txt
+20 -4
View File
@@ -7,6 +7,13 @@ on:
required: true
type: string
default: 'false'
vega-version:
required: true
type: string
gobin:
required: false
type: string
default: /home/runner/go/bin
skip-cache:
required: false
type: string
@@ -20,8 +27,9 @@ jobs:
timeout-minutes: 30
runs-on: self-hosted
steps:
- name: Vega version
run: vega version
# Add GOBIN to PATH
- name: Add GOBIN to PATH
run: echo ${{ inputs.gobin }} >> $GITHUB_PATH
# Checkout front ends
- name: Checkout frontend mono repo
@@ -44,12 +52,21 @@ jobs:
run: yarn install --frozen-lockfile
working-directory: frontend-monorepo
#######
## Build and run Vegacapsule network
#######
- name: Install Vega binaries
uses: ./frontend-monorepo/.github/actions/install-vega-binaries
with:
version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
######
## Setup a Vega wallet for our user
######
- name: Set up Vegawallet
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet
with:
recovery: ${{ secrets.TRADING_TEST_VEGA_WALLET_RECOVERY }}
@@ -67,4 +84,3 @@ jobs:
CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}
@@ -4,7 +4,7 @@ name: Publish docker containers
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
- 'v[0-9]+.[0-9]+.[0-9]+-*'
- 'v[0-9]+.[0-9]+.[0-9]+-pre[0-9]+'
workflow_dispatch:
inputs:
+15
View File
@@ -4,6 +4,13 @@ on:
project:
required: true
type: string
vega-version:
required: true
type: string
gobin:
required: false
type: string
default: /home/runner/go/bin
skip-cache:
required: false
type: string
@@ -20,6 +27,8 @@ jobs:
secrets: inherit
with:
trigger: ${{ contains(inputs.project, 'console-lite-e2e') || contains(inputs.project, 'console-lite') }}
vega-version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
skip-cache: ${{ inputs.skip-cache }}
tags: ${{ inputs.tags }}
@@ -28,6 +37,8 @@ jobs:
secrets: inherit
with:
trigger: ${{ contains(inputs.project, 'explorer-e2e') || contains(inputs.project, 'explorer') }}
vega-version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
skip-cache: ${{ inputs.skip-cache }}
tags: ${{ inputs.tags }}
night-run: ${{ inputs.night-run }}
@@ -49,6 +60,8 @@ jobs:
secrets: inherit
with:
trigger: ${{ contains(inputs.project, 'token-e2e') || contains(inputs.project, 'token') }}
vega-version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
skip-cache: ${{ inputs.skip-cache }}
tags: ${{ inputs.tags }}
@@ -57,5 +70,7 @@ jobs:
secrets: inherit
with:
trigger: ${{ contains(inputs.project, 'trading-e2e') || contains(inputs.project, 'trading') }}
vega-version: ${{ inputs.vega-version }}
gobin: ${{ inputs.gobin }}
skip-cache: ${{ inputs.skip-cache }}
tags: ${{ inputs.tags }}
+5 -5
View File
@@ -88,12 +88,12 @@ Run `nx test my-app` to execute the unit tests with [Jest](https://jestjs.io), o
### Using wallet
To run tests locally using your own wallets make sure you have generated at least two public keys and update the following environment variables in `cypress.config.js` to match your wallet.
To run tests locally using your own wallets you can add the following environment variables to `cypress.json`
1. Set `VEGA_PUBLIC_KEY` and `TRUNCATED_VEGA_PUBLIC_KEY` to your first public key.
2. Set `VEGA_PUBLIC_KEY2` and `TRUNCATED_VEGA_PUBLIC_KEY2` to your second public key.
3. Set `TRADING_TEST_VEGA_WALLET_PASSPHRASE` as your wallet passphrase
4. Add `ETH_WALLET_MNEMONIC` as your Ethereum wallet mnemonic
1. Change `TRADING_TEST_VEGA_WALLET_NAME` to your Vega wallet name
2. Add `TRADING_TEST_VEGA_WALLET_PASSPHRASE` as your wallet passphrase
3. Add `ETH_WALLET_MNEMONIC` as your Ethereum wallet mnemonic
4. Use [vegawallet-dummy](https://github.com/vegaprotocol/vegawallet-dummy) to avoid being prompted in CLI during test execution.
### Formatting
-1
View File
@@ -7,4 +7,3 @@ NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_EXPLORER_URL=https://stagnet3.explorer.vega.xyz
NX_VEGA_WALLET_URL=http://localhost:1789
CYPRESS_VEGA_ENV=STAGNET3
CYPRESS_VEGA_WALLET_API_TOKEN=
+2 -1
View File
@@ -4,7 +4,7 @@ module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
require('@cypress/grep/src/plugin')(config);
require('cypress-grep/src/plugin')(config);
return config;
},
baseUrl: 'http://localhost:4200',
@@ -23,6 +23,7 @@ module.exports = defineConfig({
viewportHeight: 900,
},
env: {
TRADING_TEST_VEGA_WALLET_NAME: 'UI_Trading_Test',
ETHEREUM_PROVIDER_URL:
'https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8',
VEGA_PUBLIC_KEY:
-20
View File
@@ -1,20 +0,0 @@
/// <reference types="cypress" />
declare namespace Cypress {
// specify additional properties in the TestConfig object
// in our case we will add "tags" property
interface SuiteConfigOverrides {
/**
* List of tags for this test
* @example a single tag
* it('logs in', { tags: '@smoke' }, () => { ... })
* @example multiple tags
* it('works', { tags: ['@smoke', '@slow'] }, () => { ... })
*/
tags?: string | string[];
}
interface Cypress {
grep?: (grep?: string, tags?: string, burn?: string) => void;
}
}
@@ -1,3 +1,4 @@
import { connectVegaWallet } from '../support/vega-wallet';
import { aliasQuery } from '@vegaprotocol/cypress';
import {
generateMarket,
@@ -7,7 +8,11 @@ import {
generateSimpleMarkets,
} from '../support/mocks/generate-markets';
import { generateMarketTags } from '../support/mocks/generate-market-tags';
import { generateMarketPositions } from '../support/mocks/generate-market-positions';
import { generateEstimateOrder } from '../support/mocks/generate-estimate-order';
import { generatePartyBalance } from '../support/mocks/generate-party-balance';
import { generatePartyMarketData } from '../support/mocks/generate-party-market-data';
import { generateMarketMarkPrice } from '../support/mocks/generate-market-mark-price';
import { generateMarketNames } from '../support/mocks/generate-market-names';
import { generateMarketDepth } from '../support/mocks/generate-market-depth';
import type { Market, MarketsQuery } from '@vegaprotocol/market-list';
@@ -26,7 +31,11 @@ describe('market selector', { tags: '@smoke' }, () => {
aliasQuery(req, 'MarketData', generateMarketData());
aliasQuery(req, 'Market', generateMarket());
aliasQuery(req, 'MarketTags', generateMarketTags());
aliasQuery(req, 'MarketPositions', generateMarketPositions());
aliasQuery(req, 'EstimateOrder', generateEstimateOrder());
aliasQuery(req, 'PartyBalance', generatePartyBalance());
aliasQuery(req, 'PartyMarketData', generatePartyMarketData());
aliasQuery(req, 'MarketMarkPrice', generateMarketMarkPrice());
aliasQuery(req, 'MarketNames', generateMarketNames());
aliasQuery(req, 'MarketDepth', generateMarketDepth());
});
@@ -43,7 +52,7 @@ describe('market selector', { tags: '@smoke' }, () => {
it('should be properly rendered', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('input[placeholder="Search"]').should(
'have.value',
markets[0].tradableInstrument.instrument.name
@@ -67,7 +76,7 @@ describe('market selector', { tags: '@smoke' }, () => {
it('typing should change list', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('input[placeholder="Search"]').type('{backspace}');
cy.getByTestId('market-pane')
.children()
@@ -103,7 +112,7 @@ describe('market selector', { tags: '@smoke' }, () => {
it.skip('keyboard navigation should work well', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('input[placeholder="Search"]').type('{backspace}');
cy.get('input[placeholder="Search"]').clear();
cy.focused().realPress('ArrowDown');
@@ -125,7 +134,7 @@ describe('market selector', { tags: '@smoke' }, () => {
if (markets?.length) {
cy.viewport('iphone-xr');
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('[role="dialog"]').should('not.exist');
cy.getByTestId('arrow-button').click();
cy.get('[role="dialog"]').should('be.visible');
@@ -1,3 +1,4 @@
import { connectVegaWallet } from '../support/vega-wallet';
import { aliasQuery } from '@vegaprotocol/cypress';
import {
generateSimpleMarkets,
@@ -7,14 +8,15 @@ import {
generateMarketData,
} from '../support/mocks/generate-markets';
import { generateMarketTags } from '../support/mocks/generate-market-tags';
import { generateMarketPositions } from '../support/mocks/generate-market-positions';
import { generateEstimateOrder } from '../support/mocks/generate-estimate-order';
import { generatePartyBalance } from '../support/mocks/generate-party-balance';
import { generatePartyMarketData } from '../support/mocks/generate-party-market-data';
import { generateMarketMarkPrice } from '../support/mocks/generate-market-mark-price';
import { generateMarketDepth } from '../support/mocks/generate-market-depth';
import type { MarketsQuery, Market } from '@vegaprotocol/market-list';
import { generateChainId } from '../support/mocks/generate-chain-id';
import { generateStatistics } from '../support/mocks/generate-statistics';
import { generateAccounts } from '../support/mocks/generate-accounts';
import { generateAssets } from '../support/mocks/generate-assets';
import { generatePositions } from '../support/mocks/generate-positions';
describe('Market trade', { tags: '@smoke' }, () => {
let markets: Market[];
@@ -27,13 +29,14 @@ describe('Market trade', { tags: '@smoke' }, () => {
aliasQuery(req, 'MarketsData', generateMarketsData());
aliasQuery(req, 'SimpleMarkets', generateSimpleMarkets());
aliasQuery(req, 'MarketTags', generateMarketTags());
aliasQuery(req, 'MarketPositions', generateMarketPositions());
aliasQuery(req, 'EstimateOrder', generateEstimateOrder());
aliasQuery(req, 'Accounts', generateAccounts());
aliasQuery(req, 'Assets', generateAssets());
aliasQuery(req, 'PartyBalance', generatePartyBalance());
aliasQuery(req, 'PartyMarketData', generatePartyMarketData());
aliasQuery(req, 'MarketMarkPrice', generateMarketMarkPrice());
aliasQuery(req, 'MarketDepth', generateMarketDepth());
aliasQuery(req, 'Market', generateMarket());
aliasQuery(req, 'MarketData', generateMarketData());
aliasQuery(req, 'Positions', generatePositions());
});
cy.visit('/markets');
cy.wait('@Markets').then((response) => {
@@ -60,7 +63,7 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('side selector should work well', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').should(
'have.text',
'Long'
@@ -79,7 +82,7 @@ describe('Market trade', { tags: '@smoke' }, () => {
if (markets?.length) {
cy.viewport('iphone-xr');
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.getByTestId('next-button').scrollIntoView().click();
cy.get('button[aria-label="Open long position"]').should(
@@ -110,26 +113,8 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('size slider should work well', () => {
if (markets?.length) {
const marketId = markets[1].id;
cy.mockGQL((req) => {
aliasQuery(
req,
'Market',
generateMarket({
market: {
id: marketId,
tradableInstrument: {
instrument: {
product: { settlementAsset: { id: 'asset-id-2' } },
},
},
},
})
);
});
cy.visit(`/trading/${marketId}`);
cy.visit(`/trading/${markets[1].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').click();
cy.get('button[aria-label="Open short position"]').click();
cy.get('#step-2-control').click();
@@ -150,25 +135,8 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('percentage selection should work well', () => {
if (markets?.length) {
const marketId = markets[1].id;
cy.mockGQL((req) => {
aliasQuery(
req,
'Market',
generateMarket({
market: {
id: marketId,
tradableInstrument: {
instrument: {
product: { settlementAsset: { id: 'asset-id-2' } },
},
},
},
})
);
});
cy.visit(`/trading/${marketId}`);
cy.connectVegaWallet();
cy.visit(`/trading/${markets[1].id}`);
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').click();
cy.get('button[aria-label="Open short position"]').click();
cy.get('#step-2-control').click();
@@ -178,7 +146,7 @@ describe('Market trade', { tags: '@smoke' }, () => {
.find('button')
.should('have.text', '1');
cy.getByTestId('max-label').should('have.text', '11');
cy.getByTestId('max-label').should('have.text', '21');
cy.getByTestId('percentage-selector')
.find('button')
@@ -188,14 +156,14 @@ describe('Market trade', { tags: '@smoke' }, () => {
.find('dd')
.eq(0)
.find('button')
.should('have.text', '11');
.should('have.text', '21');
}
});
it('size input should work well', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[1].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').click();
cy.get('button[aria-label="Open short position"]').click();
cy.get('#step-2-control').click();
@@ -222,25 +190,8 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('slippage value should be displayed', () => {
if (markets?.length) {
const marketId = markets[1].id;
cy.mockGQL((req) => {
aliasQuery(
req,
'Market',
generateMarket({
market: {
id: marketId,
tradableInstrument: {
instrument: {
product: { settlementAsset: { id: 'asset-id-2' } },
},
},
},
})
);
});
cy.visit(`/trading/${marketId}`);
cy.connectVegaWallet();
cy.visit(`/trading/${markets[1].id}`);
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').click();
cy.get('button[aria-label="Open short position"]').click();
cy.get('#step-2-control').click();
@@ -255,25 +206,8 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('allow slippage value to be adjusted', () => {
if (markets?.length) {
const marketId = markets[1].id;
cy.mockGQL((req) => {
aliasQuery(
req,
'Market',
generateMarket({
market: {
id: marketId,
tradableInstrument: {
instrument: {
product: { settlementAsset: { id: 'asset-id-2' } },
},
},
},
})
);
});
cy.visit(`/trading/${marketId}`);
cy.connectVegaWallet();
cy.visit(`/trading/${markets[1].id}`);
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').click();
cy.get('button[aria-label="Open short position"]').click();
cy.get('#step-2-control').click();
@@ -301,7 +235,7 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('notional position size should be present', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[1].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').click();
cy.get('button[aria-label="Open short position"]').click();
cy.get('#step-2-control').click();
@@ -328,7 +262,7 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('total fees should be displayed', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[1].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('#step-1-control [aria-label^="Selected value"]').click();
cy.get('button[aria-label="Open short position"]').click();
cy.get('#step-2-control').click();
@@ -346,7 +280,7 @@ describe('Market trade', { tags: '@smoke' }, () => {
it('order review should display proper calculations', () => {
if (markets?.length) {
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('#step-3-control').click();
cy.getByTestId('review-trade')
@@ -376,7 +310,7 @@ describe('Market trade', { tags: '@smoke' }, () => {
if (markets?.length) {
cy.viewport('iphone-xr');
cy.visit(`/trading/${markets[0].id}`);
cy.connectVegaWallet();
connectVegaWallet();
cy.get('#step-3-control').click();
// Start from the bottom tooltip to ensure the tooltip above
@@ -1,3 +1,4 @@
import { connectVegaWallet } from '../support/vega-wallet';
import { aliasQuery } from '@vegaprotocol/cypress';
import {
generatePositions,
@@ -21,7 +22,7 @@ describe('Portfolio page - wallet', { tags: '@smoke' }, () => {
cy.visit('/');
cy.get('[href="/portfolio"]').eq(0).click();
cy.getByTestId('trading-connect-wallet').should('be.visible');
cy.connectVegaWallet();
connectVegaWallet();
cy.getByTestId('trading-connect-wallet').should('not.exist');
});
});
@@ -42,7 +43,7 @@ describe('Portfolio page tabs', { tags: '@smoke' }, () => {
it('certain tabs should exist', () => {
cy.visit('/portfolio');
cy.connectVegaWallet();
connectVegaWallet();
cy.getByTestId('assets').click();
cy.location('pathname').should('eq', '/portfolio/assets');
@@ -73,7 +74,7 @@ describe('Portfolio page tabs', { tags: '@smoke' }, () => {
aliasQuery(req, 'Assets', generateAssets());
});
cy.visit('/portfolio/assets');
cy.connectVegaWallet();
connectVegaWallet();
});
it('data should be properly rendered', () => {
@@ -104,11 +105,11 @@ describe('Portfolio page tabs', { tags: '@smoke' }, () => {
aliasQuery(req, 'Assets', generateAssets());
});
cy.visit('/portfolio/positions');
cy.connectVegaWallet();
connectVegaWallet();
});
it('data should be properly rendered', () => {
cy.get('.ag-center-cols-container .ag-row').should('have.length', 1);
cy.get('.ag-center-cols-container .ag-row').should('have.length', 2);
});
});
@@ -121,7 +122,7 @@ describe('Portfolio page tabs', { tags: '@smoke' }, () => {
aliasQuery(req, 'Markets', generateFillsMarkets());
});
cy.visit('/portfolio/orders');
cy.connectVegaWallet();
connectVegaWallet();
});
it('data should be properly rendered', () => {
@@ -138,7 +139,7 @@ describe('Portfolio page tabs', { tags: '@smoke' }, () => {
aliasQuery(req, 'Markets', generateFillsMarkets());
});
cy.visit('/portfolio/fills');
cy.connectVegaWallet();
connectVegaWallet();
});
it('data should be properly rendered', () => {
@@ -165,7 +166,7 @@ describe('Portfolio page tabs', { tags: '@smoke' }, () => {
aliasQuery(req, 'MarketsData', generateMarketsData());
});
cy.visit('/portfolio');
cy.connectVegaWallet();
connectVegaWallet();
});
it('"No data to display" should be always displayed', () => {
+1 -1
View File
@@ -17,7 +17,7 @@ import '@vegaprotocol/cypress';
import 'cypress-real-events/support';
// Import commands.js using ES2015 syntax:
import './commands';
import registerCypressGrep from '@cypress/grep';
import registerCypressGrep from 'cypress-grep';
import { aliasQuery } from '@vegaprotocol/cypress';
registerCypressGrep();
@@ -1,5 +1,5 @@
import type { Market } from '@vegaprotocol/market-list';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import type { SingleMarketFieldsFragment } from '@vegaprotocol/market-list';
export const protoCandles = [
@@ -1,6 +1,6 @@
import merge from 'lodash/merge';
import type { AccountsQuery } from '@vegaprotocol/accounts';
import * as Types from '@vegaprotocol/types';
import { Schema as Types } from '@vegaprotocol/types';
import type { PartialDeep } from 'type-fest';
export const generateAccounts = (
@@ -74,21 +74,6 @@ export const generateAccounts = (
},
},
},
{
__typename: 'AccountEdge',
node: {
type: Types.AccountType.ACCOUNT_TYPE_MARGIN,
asset: {
__typename: 'Asset',
id: 'asset-id-2',
},
balance: '265329',
market: {
id: '57fbaa322e97cfc8bb5f1de048c37e033c41b1ac1906d3aed9960912a067ef5a',
__typename: 'Market',
},
},
},
{
__typename: 'AccountEdge',
node: {
@@ -1,6 +1,6 @@
import merge from 'lodash/merge';
import type { AssetsQuery } from '@vegaprotocol/assets';
import * as Types from '@vegaprotocol/types';
import { Schema as Types } from '@vegaprotocol/types';
import type { PartialDeep } from 'type-fest';
export const generateAssets = (override?: PartialDeep<AssetsQuery>) => {
@@ -1,5 +1,5 @@
import type { FillsQuery, FillFieldsFragment } from '@vegaprotocol/fills';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
@@ -1,7 +1,7 @@
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
// eslint-disable-next-line @nrwl/nx/enforce-module-boundaries
import type { MarketDepthQuery } from '../../../../../libs/market-depth/src/lib/__generated__/MarketDepth';
import type { MarketDepthQuery } from '../../../../../libs/market-depth/src/lib/__generated___/MarketDepth';
export const generateMarketDepth = (
override?: PartialDeep<MarketDepthQuery>
@@ -110,91 +110,91 @@ export const generateMarketDepth = (
],
buy: [
{
price: '9891005',
price: '9893005',
volume: '4',
numberOfOrders: '3',
__typename: 'PriceLevel',
},
{
price: '9890003',
price: '9893003',
volume: '2',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9889001',
price: '9893001',
volume: '1',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9888006',
price: '9892006',
volume: '3',
numberOfOrders: '2',
__typename: 'PriceLevel',
},
{
price: '9887006',
price: '9891006',
volume: '2',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9886001',
price: '9891001',
volume: '1',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9885101',
price: '9890101',
volume: '2',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9884091',
price: '9890091',
volume: '5',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9883081',
price: '9890081',
volume: '4',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9882050',
price: '9890050',
volume: '2',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9881040',
price: '9890040',
volume: '6',
numberOfOrders: '3',
__typename: 'PriceLevel',
},
{
price: '9880030',
price: '9890030',
volume: '6',
numberOfOrders: '2',
__typename: 'PriceLevel',
},
{
price: '9879021',
price: '9890021',
volume: '3',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9878011',
price: '9890011',
volume: '1',
numberOfOrders: '1',
__typename: 'PriceLevel',
},
{
price: '9877001',
price: '9890001',
volume: '11',
numberOfOrders: '1',
__typename: 'PriceLevel',
@@ -0,0 +1,9 @@
export const generateMarketMarkPrice = () => {
return {
market: {
decimalPlaces: 5,
data: { markPrice: '692748', __typename: 'MarketData' },
__typename: 'Market',
},
};
};
@@ -0,0 +1,72 @@
import type { MarketPositionsQuery } from '@vegaprotocol/deal-ticket';
import { Schema } from '@vegaprotocol/types';
export const generateMarketPositions = (): MarketPositionsQuery => {
return {
party: {
id: '2e1ef32e5804e14232406aebaad719087d326afa5c648b7824d0823d8a46c8d1',
accountsConnection: {
__typename: 'AccountsConnection',
edges: [
{
__typename: 'AccountEdge',
node: {
__typename: 'AccountBalance',
type: Schema.AccountType.ACCOUNT_TYPE_GENERAL,
asset: {
decimals: 5,
},
balance: '400000000000000000000',
market: {
id: '2751c508f9759761f912890f37fb3f97a00300bf7685c02a56a86e05facfe221',
__typename: 'Market',
},
},
},
{
__typename: 'AccountEdge',
node: {
type: Schema.AccountType.ACCOUNT_TYPE_MARGIN,
asset: {
decimals: 5,
},
balance: '265329',
market: {
id: 'ca7768f6de84bf86a21bbb6b0109d9659c81917b0e0339b2c262566c9b581a15',
__typename: 'Market',
},
},
},
],
},
positionsConnection: {
edges: [
{
node: {
openVolume: '3',
market: {
id: '2751c508f9759761f912890f37fb3f97a00300bf7685c02a56a86e05facfe221',
__typename: 'Market',
},
__typename: 'Position',
},
__typename: 'PositionEdge',
},
{
node: {
openVolume: '12',
market: {
id: 'ca7768f6de84bf86a21bbb6b0109d9659c81917b0e0339b2c262566c9b581a15',
__typename: 'Market',
},
__typename: 'Position',
},
__typename: 'PositionEdge',
},
],
__typename: 'PositionConnection',
},
__typename: 'Party',
},
};
};
@@ -1,5 +1,5 @@
import merge from 'lodash/merge';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import type {
MarketsQuery,
Market,
@@ -1392,15 +1392,12 @@ export const generatePositionsMarkets = () => {
};
};
export const generateMarket = (
override?: PartialDeep<MarketQuery>
): MarketQuery => {
const defaultResult = {
export const generateMarket = (): MarketQuery => {
return {
market: {
...singleMarket,
},
};
return merge(defaultResult, override);
};
export const generateMarketData = (): MarketDataQuery => {
@@ -1416,7 +1413,6 @@ export const generateMarketData = (): MarketDataQuery => {
},
marketTradingMode:
Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
marketState: Schema.MarketState.STATE_ACTIVE,
staticMidPrice: '0',
indicativePrice: '0',
bestStaticBidPrice: '0',
@@ -1,7 +1,7 @@
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
import type { OrdersQuery, OrderFieldsFragment } from '@vegaprotocol/orders';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
export const generateOrders = (
override?: PartialDeep<OrdersQuery>
@@ -0,0 +1,81 @@
import merge from 'lodash/merge';
import type { PartyBalanceQuery } from '@vegaprotocol/deal-ticket';
import type { PartialDeep } from 'type-fest';
import { Schema as Types } from '@vegaprotocol/types';
export const generatePartyBalance = (
override?: PartialDeep<PartyBalanceQuery>
): PartyBalanceQuery => {
const defaultResult: PartyBalanceQuery = {
party: {
accountsConnection: {
__typename: 'AccountsConnection',
edges: [
{
__typename: 'AccountEdge',
node: {
balance: '88474051',
type: Types.AccountType.ACCOUNT_TYPE_GENERAL,
asset: {
id: 'dai-id',
symbol: 'tDAI',
name: 'tDAI TEST',
decimals: 5,
__typename: 'Asset',
},
__typename: 'AccountBalance',
},
},
{
__typename: 'AccountEdge',
node: {
balance: '100000000',
type: Types.AccountType.ACCOUNT_TYPE_GENERAL,
asset: {
id: '8b52d4a3a4b0ffe733cddbc2b67be273816cfeb6ca4c8b339bac03ffba08e4e4',
symbol: 'tEURO',
name: 'tEURO TEST',
decimals: 5,
__typename: 'Asset',
},
__typename: 'AccountBalance',
},
},
{
__typename: 'AccountEdge',
node: {
balance: '3412867',
type: Types.AccountType.ACCOUNT_TYPE_GENERAL,
asset: {
id: 'dai-id',
symbol: 'tDAI',
name: 'tDAI TEST',
decimals: 5,
__typename: 'Asset',
},
__typename: 'AccountBalance',
},
},
{
__typename: 'AccountEdge',
node: {
balance: '70007',
type: Types.AccountType.ACCOUNT_TYPE_GENERAL,
asset: {
id: 'dai-id',
symbol: 'tDAI',
name: 'tDAI TEST',
decimals: 5,
__typename: 'Asset',
},
__typename: 'AccountBalance',
},
},
],
},
__typename: 'Party',
},
};
return merge(defaultResult, override);
};
@@ -0,0 +1,40 @@
import type { PartyMarketDataQuery } from '@vegaprotocol/deal-ticket';
import { Schema as Types } from '@vegaprotocol/types';
export const generatePartyMarketData = (): PartyMarketDataQuery => {
return {
party: {
id: '2e1ef32e5804e14232406aebaad719087d326afa5c648b7824d0823d8a46c8d1',
accountsConnection: {
__typename: 'AccountsConnection',
edges: [
{
__typename: 'AccountEdge',
node: {
type: Types.AccountType.ACCOUNT_TYPE_GENERAL,
balance: '1200000',
asset: { id: 'fBTC', decimals: 5, __typename: 'Asset' },
market: null,
__typename: 'AccountBalance',
},
},
{
__typename: 'AccountEdge',
node: {
__typename: 'AccountBalance',
type: Types.AccountType.ACCOUNT_TYPE_GENERAL,
balance: '0.000000001',
asset: {
__typename: 'Asset',
id: '5cfa87844724df6069b94e4c8a6f03af21907d7bc251593d08e4251043ee9f7c',
decimals: 0,
},
},
},
],
},
marginsConnection: { edges: null, __typename: 'MarginConnection' },
__typename: 'Party',
},
};
};
@@ -41,7 +41,7 @@ export const generatePositions = (
averageEntryPrice: '84400088',
updatedAt: '2022-07-28T14:53:54.725477Z',
market: {
id: '57fbaa322e97cfc8bb5f1de048c37e033c41b1ac1906d3aed9960912a067ef5a',
id: '5a4b0b9e9c0629f0315ec56fcb7bd444b0c6e4da5ec7677719d502626658a376',
__typename: 'Market',
},
__typename: 'Position',
@@ -0,0 +1,12 @@
export const connectVegaWallet = () => {
const form = 'rest-connector-form';
const walletName = Cypress.env('TRADING_TEST_VEGA_WALLET_NAME');
const walletPassphrase = Cypress.env('TRADING_TEST_VEGA_WALLET_PASSPHRASE');
cy.getByTestId('connect-vega-wallet').click();
cy.getByTestId('connectors-list')
.find('[data-testid="connector-gui"]')
.click();
cy.getByTestId(form).find('#wallet').click().type(walletName);
cy.getByTestId(form).find('#passphrase').click().type(walletPassphrase);
cy.getByTestId('rest-connector-form').find('button[type=submit]').click();
};
+2 -2
View File
@@ -7,7 +7,7 @@
"allowSyntheticDefaultImports": true,
"outDir": "../../dist/out-tsc",
"allowJs": true,
"types": ["cypress", "node", "cypress-real-events", "@cypress/grep"]
"types": ["cypress", "node", "cypress-real-events", "cypress-grep"]
},
"include": ["src/**/*.ts", "src/**/*.js", "./declaration.d.ts", "index.d.ts"]
"include": ["src/**/*.ts", "src/**/*.js", "./declaration.d.ts"]
}
@@ -0,0 +1,18 @@
query PartyBalanceQuery($partyId: ID!) {
party(id: $partyId) {
accountsConnection {
edges {
node {
type
balance
asset {
id
symbol
name
decimals
}
}
}
}
}
}
@@ -1,54 +1,51 @@
import * as Types from '@vegaprotocol/types';
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type MarketTagsQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
// ====================================================
// GraphQL query operation: MarketTags
// ====================================================
export type MarketTagsQuery = { __typename?: 'Query', market?: { __typename?: 'Market', tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null } } } } | null };
export const MarketTagsDocument = gql`
query MarketTags($marketId: ID!) {
market(id: $marketId) {
tradableInstrument {
instrument {
metadata {
tags
}
}
}
}
export interface MarketTags_market_tradableInstrument_instrument_metadata {
__typename: "InstrumentMetadata";
/**
* An arbitrary list of tags to associated to associate to the Instrument (string list)
*/
tags: string[] | null;
}
`;
/**
* __useMarketTagsQuery__
*
* To run a query within a React component, call `useMarketTagsQuery` and pass it any options that fit your needs.
* When your component renders, `useMarketTagsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useMarketTagsQuery({
* variables: {
* marketId: // value for 'marketId'
* },
* });
*/
export function useMarketTagsQuery(baseOptions: Apollo.QueryHookOptions<MarketTagsQuery, MarketTagsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<MarketTagsQuery, MarketTagsQueryVariables>(MarketTagsDocument, options);
}
export function useMarketTagsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<MarketTagsQuery, MarketTagsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<MarketTagsQuery, MarketTagsQueryVariables>(MarketTagsDocument, options);
}
export type MarketTagsQueryHookResult = ReturnType<typeof useMarketTagsQuery>;
export type MarketTagsLazyQueryHookResult = ReturnType<typeof useMarketTagsLazyQuery>;
export type MarketTagsQueryResult = Apollo.QueryResult<MarketTagsQuery, MarketTagsQueryVariables>;
export interface MarketTags_market_tradableInstrument_instrument {
__typename: "Instrument";
/**
* Metadata for this instrument
*/
metadata: MarketTags_market_tradableInstrument_instrument_metadata;
}
export interface MarketTags_market_tradableInstrument {
__typename: "TradableInstrument";
/**
* An instance of, or reference to, a fully specified instrument.
*/
instrument: MarketTags_market_tradableInstrument_instrument;
}
export interface MarketTags_market {
__typename: "Market";
/**
* An instance of, or reference to, a tradable instrument.
*/
tradableInstrument: MarketTags_market_tradableInstrument;
}
export interface MarketTags {
/**
* An instrument that is trading on the Vega network
*/
market: MarketTags_market | null;
}
export interface MarketTagsVariables {
marketId: string;
}
@@ -0,0 +1,54 @@
import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type MarketTagsQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type MarketTagsQuery = { __typename?: 'Query', market?: { __typename?: 'Market', tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null } } } } | null };
export const MarketTagsDocument = gql`
query MarketTags($marketId: ID!) {
market(id: $marketId) {
tradableInstrument {
instrument {
metadata {
tags
}
}
}
}
}
`;
/**
* __useMarketTagsQuery__
*
* To run a query within a React component, call `useMarketTagsQuery` and pass it any options that fit your needs.
* When your component renders, `useMarketTagsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useMarketTagsQuery({
* variables: {
* marketId: // value for 'marketId'
* },
* });
*/
export function useMarketTagsQuery(baseOptions: Apollo.QueryHookOptions<MarketTagsQuery, MarketTagsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<MarketTagsQuery, MarketTagsQueryVariables>(MarketTagsDocument, options);
}
export function useMarketTagsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<MarketTagsQuery, MarketTagsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<MarketTagsQuery, MarketTagsQueryVariables>(MarketTagsDocument, options);
}
export type MarketTagsQueryHookResult = ReturnType<typeof useMarketTagsQuery>;
export type MarketTagsLazyQueryHookResult = ReturnType<typeof useMarketTagsLazyQuery>;
export type MarketTagsQueryResult = Apollo.QueryResult<MarketTagsQuery, MarketTagsQueryVariables>;
@@ -0,0 +1,61 @@
import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type PartyBalanceQueryQueryVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
}>;
export type PartyBalanceQueryQuery = { __typename?: 'Query', party?: { __typename?: 'Party', accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string, asset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number } } } | null> | null } | null } | null };
export const PartyBalanceQueryDocument = gql`
query PartyBalanceQuery($partyId: ID!) {
party(id: $partyId) {
accountsConnection {
edges {
node {
type
balance
asset {
id
symbol
name
decimals
}
}
}
}
}
}
`;
/**
* __usePartyBalanceQueryQuery__
*
* To run a query within a React component, call `usePartyBalanceQueryQuery` and pass it any options that fit your needs.
* When your component renders, `usePartyBalanceQueryQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = usePartyBalanceQueryQuery({
* variables: {
* partyId: // value for 'partyId'
* },
* });
*/
export function usePartyBalanceQueryQuery(baseOptions: Apollo.QueryHookOptions<PartyBalanceQueryQuery, PartyBalanceQueryQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<PartyBalanceQueryQuery, PartyBalanceQueryQueryVariables>(PartyBalanceQueryDocument, options);
}
export function usePartyBalanceQueryLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<PartyBalanceQueryQuery, PartyBalanceQueryQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<PartyBalanceQueryQuery, PartyBalanceQueryQueryVariables>(PartyBalanceQueryDocument, options);
}
export type PartyBalanceQueryQueryHookResult = ReturnType<typeof usePartyBalanceQueryQuery>;
export type PartyBalanceQueryLazyQueryHookResult = ReturnType<typeof usePartyBalanceQueryLazyQuery>;
export type PartyBalanceQueryQueryResult = Apollo.QueryResult<PartyBalanceQueryQuery, PartyBalanceQueryQueryVariables>;
@@ -1,13 +1,9 @@
import React from 'react';
import { render } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing';
import type { MarketDealTicketAsset } from '@vegaprotocol/market-list';
import type { AccountFragment } from '@vegaprotocol/deal-ticket';
import { DealTicketBalance } from './deal-ticket-balance';
jest.mock('@vegaprotocol/wallet', () => ({
...jest.requireActual('@vegaprotocol/wallet'),
useVegaWallet: jest.fn().mockReturnValue('wallet-pub-key'),
}));
import { Schema } from '@vegaprotocol/types';
import type { MarketDealTicketAsset } from '@vegaprotocol/market-list';
const tDAI: MarketDealTicketAsset = {
__typename: 'Asset',
@@ -17,20 +13,23 @@ const tDAI: MarketDealTicketAsset = {
decimals: 2,
};
let mockAccountBalance: {
accountBalance: string;
accountDecimals: number | null;
} = { accountBalance: '1000000', accountDecimals: 2 };
jest.mock('@vegaprotocol/accounts', () => ({
...jest.requireActual('@vegaprotocol/accounts'),
useAccountBalance: jest.fn(() => mockAccountBalance),
}));
const accounts: AccountFragment[] = [
{
__typename: 'AccountBalance',
type: Schema.AccountType.ACCOUNT_TYPE_GENERAL,
balance: '1000000',
asset: tDAI,
},
];
describe('DealTicketBalance', function () {
it('should render the balance', () => {
const { getByText, getByRole } = render(
<DealTicketBalance settlementAsset={tDAI} isWalletConnected />,
{ wrapper: MockedProvider }
<DealTicketBalance
settlementAsset={tDAI}
accounts={accounts}
isWalletConnected
/>
);
expect(getByRole('complementary')).toHaveAccessibleName('tDAI Balance');
@@ -40,8 +39,11 @@ describe('DealTicketBalance', function () {
it('should prompt to connect wallet', () => {
const { getByText } = render(
<DealTicketBalance settlementAsset={tDAI} isWalletConnected={false} />,
{ wrapper: MockedProvider }
<DealTicketBalance
settlementAsset={tDAI}
accounts={accounts}
isWalletConnected={false}
/>
);
expect(
@@ -50,10 +52,12 @@ describe('DealTicketBalance', function () {
});
it('should display zero balance', () => {
mockAccountBalance = { accountBalance: '', accountDecimals: null };
const { getByText } = render(
<DealTicketBalance settlementAsset={tDAI} isWalletConnected={true} />,
{ wrapper: MockedProvider }
<DealTicketBalance
settlementAsset={tDAI}
accounts={[]}
isWalletConnected={true}
/>
);
expect(getByText('No tDAI left to trade')).toBeInTheDocument();
@@ -1,38 +1,41 @@
import classNames from 'classnames';
import {
addDecimalsFormatNumber,
t,
toBigNum,
} from '@vegaprotocol/react-helpers';
import { addDecimalsFormatNumber, t } from '@vegaprotocol/react-helpers';
import { Schema } from '@vegaprotocol/types';
import type { AccountFragment } from '@vegaprotocol/deal-ticket';
import type { MarketDealTicket } from '@vegaprotocol/market-list';
import { useAccountBalance } from '@vegaprotocol/accounts';
import { useSettlementAccount } from '@vegaprotocol/deal-ticket';
interface DealTicketBalanceProps {
settlementAsset: MarketDealTicket['tradableInstrument']['instrument']['product']['settlementAsset'];
accounts: AccountFragment[];
isWalletConnected: boolean;
className?: string;
}
export const DealTicketBalance = ({
settlementAsset,
accounts,
isWalletConnected,
className = '',
}: DealTicketBalanceProps) => {
const settlementAssetId = settlementAsset?.id;
const settlementAssetSymbol = settlementAsset?.symbol;
const { accountBalance, accountDecimals } =
useAccountBalance(settlementAssetId) || {};
const settlementBalance = toBigNum(accountBalance || 0, accountDecimals || 0);
const settlementAccount = useSettlementAccount(
settlementAssetId,
accounts,
Schema.AccountType.ACCOUNT_TYPE_GENERAL
);
const formattedNumber =
accountBalance &&
accountDecimals &&
addDecimalsFormatNumber(accountBalance, accountDecimals);
settlementAccount?.balance &&
settlementAccount.asset.decimals &&
addDecimalsFormatNumber(
settlementAccount.balance,
settlementAccount.asset.decimals
);
const balance = (
<p className="text-blue text-lg font-semibold">
{!settlementBalance.isZero()
{settlementAccount
? t(`${formattedNumber}`)
: `No ${settlementAssetSymbol} left to trade`}
</p>
@@ -1,5 +1,9 @@
import { useParams } from 'react-router-dom';
import { DealTicketManager } from '@vegaprotocol/deal-ticket';
import compact from 'lodash/compact';
import {
DealTicketManager,
usePartyBalanceQuery,
} from '@vegaprotocol/deal-ticket';
import { Loader, Splash } from '@vegaprotocol/ui-toolkit';
import { t, useDataProvider } from '@vegaprotocol/react-helpers';
import { useVegaWallet } from '@vegaprotocol/wallet';
@@ -22,6 +26,11 @@ export const DealTicketContainer = () => {
const { marketId } = useParams<{ marketId: string }>();
const { pubKey } = useVegaWallet();
const { data: partyData } = usePartyBalanceQuery({
variables: { partyId: pubKey || '' },
skip: !pubKey,
});
const variables = useMemo(
() => ({
marketId: marketId || '',
@@ -37,6 +46,10 @@ export const DealTicketContainer = () => {
skip: !marketId,
});
const accounts = compact(partyData?.party?.accountsConnection?.edges).map(
(e) => e.node
);
const loader = <Loader />;
if (marketId && data) {
const balance = (
@@ -45,6 +58,7 @@ export const DealTicketContainer = () => {
settlementAsset={
data.tradableInstrument.instrument.product?.settlementAsset
}
accounts={accounts || []}
isWalletConnected={!!pubKey}
/>
);
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm, Controller } from 'react-hook-form';
import compact from 'lodash/compact';
import { Stepper } from '../stepper';
import {
getDefaultOrder,
useOrderCloseOut,
useOrderMargin,
usePartyBalanceQuery,
useMaximumPositionSize,
useCalculateSlippage,
validateAmount,
@@ -35,7 +37,7 @@ import { DealTicketSize } from './deal-ticket-size';
import MarketNameRenderer from '../simple-market-list/simple-market-renderer';
import SideSelector, { SIDE_NAMES } from './side-selector';
import ReviewTrade from './review-trade';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import { DealTicketSlippage } from './deal-ticket-slippage';
import { useOrderValidation } from './use-order-validation';
import type { MarketDealTicket } from '@vegaprotocol/market-list';
@@ -75,7 +77,17 @@ export const DealTicketSteps = ({ market }: DealTicketMarketProps) => {
});
const { submit, transaction, finalizedOrder, Dialog } = useOrderSubmit();
const { data: partyBalance } = usePartyBalanceQuery({
variables: { partyId: pubKey || '' },
skip: !pubKey,
});
const accounts = compact(partyBalance?.party?.accountsConnection?.edges).map(
(e) => e.node
);
const maxTrade = useMaximumPositionSize({
partyId: pubKey || '',
accounts: accounts,
marketId: market.id,
settlementAssetId:
market.tradableInstrument.instrument.product.settlementAsset.id,
@@ -86,6 +98,7 @@ export const DealTicketSteps = ({ market }: DealTicketMarketProps) => {
const estCloseOut = useOrderCloseOut({
order,
market,
partyData: partyBalance,
});
const slippage = useCalculateSlippage({ marketId: market.id, order });
const [slippageValue, setSlippageValue] = useState(
@@ -8,10 +8,28 @@ import classNames from 'classnames';
import { DealTicketEstimates } from '@vegaprotocol/deal-ticket';
import type { OrderSubmissionBody } from '@vegaprotocol/wallet';
import { SIDE_NAMES } from './side-selector';
import * as Schema from '@vegaprotocol/types';
import { gql, useQuery } from '@apollo/client';
import { Schema } from '@vegaprotocol/types';
import { MarketExpires } from '@vegaprotocol/market-info';
import type { MarketDealTicket } from '@vegaprotocol/market-list';
import { useMarketTagsQuery } from './__generated__/MarketTags';
import type {
MarketTags,
MarketTagsVariables,
} from './__generated__/MarketTags';
export const MARKET_TAGS_QUERY = gql`
query MarketTags($marketId: ID!) {
market(id: $marketId) {
tradableInstrument {
instrument {
metadata {
tags
}
}
}
}
}
`;
interface Props {
market: MarketDealTicket;
@@ -39,9 +57,12 @@ export default ({
notionalSize,
slippage,
}: Props) => {
const { data: tagsData } = useMarketTagsQuery({
variables: { marketId: market.id },
});
const { data: tagsData } = useQuery<MarketTags, MarketTagsVariables>(
MARKET_TAGS_QUERY,
{
variables: { marketId: market.id },
}
);
return (
<div className="mb-8 text-black dark:text-white" data-testid="review-trade">
@@ -2,7 +2,7 @@ import React from 'react';
import classNames from 'classnames';
import { FormGroup } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/react-helpers';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
interface SideSelectorProps {
value: Schema.Side;
@@ -3,7 +3,11 @@ import { renderHook } from '@testing-library/react';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { MockedProvider } from '@apollo/client/testing';
import type { VegaWalletContextShape } from '@vegaprotocol/wallet';
import * as Schema from '@vegaprotocol/types';
import {
MarketStateMapping,
Schema as Types,
Schema,
} from '@vegaprotocol/types';
import type { ValidationProps } from './use-order-validation';
import { marketTranslations, useOrderValidation } from './use-order-validation';
import type { MarketDealTicket } from '@vegaprotocol/market-list';
@@ -74,10 +78,9 @@ const market: MarketDealTicket = {
bestBidPrice: '1605489971',
bestOfferPrice: '1606823730',
markPrice: '1606823730',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
trigger: Types.AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
staticMidPrice: '1606156850',
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
marketState: Schema.MarketState.STATE_ACTIVE,
indicativeVolume: '0',
indicativePrice: '0',
bestStaticBidPrice: '1605489971',
@@ -88,11 +91,7 @@ const market: MarketDealTicket = {
auctionEnd: null,
market: { __typename: 'Market', id: 'market-id' },
},
marketTimestamps: {
__typename: 'MarketTimestamps',
close: null,
open: null,
},
marketTimestamps: {},
};
const defaultWalletContext = {
@@ -194,11 +193,7 @@ describe('useOrderValidation', () => {
`(
'Returns an error message for market state when not accepting orders',
({ state }) => {
const market = {
...defaultOrder.market,
data: { ...defaultOrder.market.data, marketState: state },
};
const { result } = setup({ market });
const { result } = setup({ market: { ...defaultOrder.market, state } });
expect(result.current).toStrictEqual({
isDisabled: true,
message: `This market is ${marketTranslations(
@@ -220,19 +215,14 @@ describe('useOrderValidation', () => {
balance: '0',
margin: '100',
balanceError: false,
// asset,
});
const market = {
...defaultOrder.market,
data: {
...defaultOrder.market.data,
marketState: state,
marketTradingMode:
Schema.MarketTradingMode.TRADING_MODE_BATCH_AUCTION,
},
};
const { result } = setup({
market,
market: {
...defaultOrder.market,
state,
tradingMode: Schema.MarketTradingMode.TRADING_MODE_BATCH_AUCTION,
},
order: {
...order,
type: Schema.OrderType.TYPE_LIMIT,
@@ -241,7 +231,7 @@ describe('useOrderValidation', () => {
});
expect(result.current).toStrictEqual({
isDisabled: false,
message: `This market is ${Schema.MarketStateMapping[
message: `This market is ${MarketStateMapping[
state as Schema.MarketState
].toLowerCase()} and only accepting liquidity commitment orders`,
section: 'sec-summary',
@@ -257,12 +247,8 @@ describe('useOrderValidation', () => {
`(
`Returns an error message when trying to submit a non-limit order for a "$tradingMode" market`,
({ tradingMode, errorMessage }) => {
const market = {
...defaultOrder.market,
data: { ...defaultOrder.market.data, marketTradingMode: tradingMode },
};
const { result } = setup({
market,
market: { ...defaultOrder.market, tradingMode },
order: {
...order,
type: Schema.OrderType.TYPE_MARKET,
@@ -287,12 +273,8 @@ describe('useOrderValidation', () => {
`(
`Returns an error message when submitting a limit order with a "$orderTimeInForce" value to a "$tradingMode" market`,
({ tradingMode, orderTimeInForce, errorMessage }) => {
const market = {
...defaultOrder.market,
data: { ...defaultOrder.market.data, marketTradingMode: tradingMode },
};
const { result } = setup({
market,
market: { ...defaultOrder.market, tradingMode },
order: {
...order,
type: Schema.OrderType.TYPE_LIMIT,
@@ -395,15 +377,14 @@ describe('useOrderValidation', () => {
`(
'Returns error when market state is pending and size is wrong',
({ state }) => {
const market = {
...defaultOrder.market,
data: { ...defaultOrder.market.data, marketState: state },
};
const { result } = setup({
fieldErrors: {
size: { type: `validate`, message: DealTicket.ERROR_SIZE_DECIMAL },
},
market,
market: {
...market,
state,
},
});
expect(result.current).toStrictEqual({
isDisabled: true,
@@ -3,7 +3,7 @@ import type { FieldErrors } from 'react-hook-form';
import { useMemo } from 'react';
import { t, toDecimal } from '@vegaprotocol/react-helpers';
import { useVegaWallet } from '@vegaprotocol/wallet';
import * as Schema from '@vegaprotocol/types';
import { MarketStateMapping, Schema } from '@vegaprotocol/types';
import type { OrderSubmissionBody } from '@vegaprotocol/wallet';
import { Tooltip } from '@vegaprotocol/ui-toolkit';
import {
@@ -39,7 +39,7 @@ export const marketTranslations = (marketState: Schema.MarketState) => {
case Schema.MarketState.STATE_TRADING_TERMINATED:
return t('terminated');
default:
return t(Schema.MarketStateMapping[marketState]).toLowerCase();
return t(MarketStateMapping[marketState]).toLowerCase();
}
};
@@ -169,13 +169,13 @@ export const useOrderValidation = ({
Schema.MarketState.STATE_TRADING_TERMINATED,
Schema.MarketState.STATE_CANCELLED,
Schema.MarketState.STATE_CLOSED,
].includes(market.data.marketState)
].includes(market.state)
) {
return {
isDisabled: true,
message: t(
`This market is ${marketTranslations(
market.data.marketState
market.state
)} and not accepting orders`
),
section: DEAL_TICKET_SECTION.SUMMARY,
@@ -186,7 +186,7 @@ export const useOrderValidation = ({
[
Schema.MarketState.STATE_PROPOSED,
Schema.MarketState.STATE_PENDING,
].includes(market.data.marketState)
].includes(market.state)
) {
if (fieldErrorChecking) {
return fieldErrorChecking;
@@ -195,7 +195,7 @@ export const useOrderValidation = ({
isDisabled: false,
message: t(
`This market is ${marketTranslations(
market.data.marketState
market.state
)} and only accepting liquidity commitment orders`
),
section: DEAL_TICKET_SECTION.SUMMARY,
@@ -205,9 +205,9 @@ export const useOrderValidation = ({
if (isMarketInAuction(market)) {
if (order.type === Schema.OrderType.TYPE_MARKET) {
if (
market.data.marketTradingMode ===
market.tradingMode ===
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION &&
market.data.trigger ===
market.data?.trigger ===
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY
) {
return {
@@ -230,9 +230,9 @@ export const useOrderValidation = ({
};
}
if (
market.data.marketTradingMode ===
market.tradingMode ===
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION &&
market.data.trigger === Schema.AuctionTrigger.AUCTION_TRIGGER_PRICE
market.data?.trigger === Schema.AuctionTrigger.AUCTION_TRIGGER_PRICE
) {
return {
isDisabled: true,
@@ -270,9 +270,9 @@ export const useOrderValidation = ({
].includes(order.timeInForce)
) {
if (
market.data.marketTradingMode ===
market.tradingMode ===
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION &&
market.data.trigger ===
market.data?.trigger ===
Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY
) {
return {
@@ -297,9 +297,9 @@ export const useOrderValidation = ({
};
}
if (
market.data.marketTradingMode ===
market.tradingMode ===
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION &&
market.data.trigger === Schema.AuctionTrigger.AUCTION_TRIGGER_PRICE
market.data?.trigger === Schema.AuctionTrigger.AUCTION_TRIGGER_PRICE
) {
return {
isDisabled: true,
@@ -355,7 +355,7 @@ export const useOrderValidation = ({
Schema.MarketTradingMode.TRADING_MODE_BATCH_AUCTION,
Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
Schema.MarketTradingMode.TRADING_MODE_OPENING_AUCTION,
].includes(market.data.marketTradingMode)
].includes(market.tradingMode)
) {
return {
isDisabled: false,
@@ -12,7 +12,7 @@ import {
t,
} from '@vegaprotocol/react-helpers';
import BigNumber from 'bignumber.js';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
interface Props {
partyId: string;
@@ -14,14 +14,20 @@ import {
import type { OrderFieldsFragment, Order } from '@vegaprotocol/orders';
import type { OrderCancellationBody } from '@vegaprotocol/wallet';
import { isOrderActive } from '@vegaprotocol/orders';
import * as Schema from '@vegaprotocol/types';
import {
OrderRejectionReasonMapping,
OrderStatusMapping,
OrderTypeMapping,
Schema,
OrderTimeInForceMapping,
} from '@vegaprotocol/types';
import BigNumber from 'bignumber.js';
import { Button } from '@vegaprotocol/ui-toolkit';
type StatusKey = keyof typeof Schema.OrderStatusMapping;
type RejectReasonKey = keyof typeof Schema.OrderRejectionReasonMapping;
type OrderTimeKey = keyof typeof Schema.OrderTimeInForceMapping;
type StatusKey = keyof typeof OrderStatusMapping;
type RejectReasonKey = keyof typeof OrderRejectionReasonMapping;
type OrderTimeKey = keyof typeof OrderTimeInForceMapping;
interface Props {
setEditOrder: (order: Order) => void;
orderCancel: {
@@ -75,7 +81,7 @@ const useColumnDefinitions = ({ setEditOrder, orderCancel }: Props) => {
value,
}: ValueFormatterParams & {
value?: OrderFieldsFragment['type'];
}) => Schema.OrderTypeMapping[value as Schema.OrderType],
}) => OrderTypeMapping[value as Schema.OrderType],
},
{
colId: 'status',
@@ -89,14 +95,14 @@ const useColumnDefinitions = ({ setEditOrder, orderCancel }: Props) => {
}) => {
if (value && data && data.market) {
if (value === Schema.OrderStatus.STATUS_REJECTED) {
return `${Schema.OrderStatusMapping[value as StatusKey]}: ${
return `${OrderStatusMapping[value as StatusKey]}: ${
data.rejectionReason &&
Schema.OrderRejectionReasonMapping[
OrderRejectionReasonMapping[
data.rejectionReason as RejectReasonKey
]
}`;
}
return Schema.OrderStatusMapping[value as StatusKey] as string;
return OrderStatusMapping[value as StatusKey] as string;
}
return '-';
},
@@ -170,11 +176,11 @@ const useColumnDefinitions = ({ setEditOrder, orderCancel }: Props) => {
new Date(data.expiresAt)
);
return `${
Schema.OrderTimeInForceMapping[value as OrderTimeKey]
OrderTimeInForceMapping[value as OrderTimeKey]
}: ${expiry}`;
}
return Schema.OrderTimeInForceMapping[value as OrderTimeKey];
return OrderTimeInForceMapping[value as OrderTimeKey];
}
return '-';
},
@@ -16,7 +16,7 @@ import type {
GroupCellRendererParams,
ColDef,
} from 'ag-grid-community';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import type { VegaValueFormatterParams } from '@vegaprotocol/ui-toolkit';
import { Intent, ProgressBarCell } from '@vegaprotocol/ui-toolkit';
@@ -1,4 +1,4 @@
import * as Types from '@vegaprotocol/types';
import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
@@ -1,6 +1,6 @@
import { t } from '@vegaprotocol/react-helpers';
import { themelite as theme } from '@vegaprotocol/tailwindcss-config';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import colors from 'tailwindcss/colors';
import type { Market } from '@vegaprotocol/market-list';
import { IS_MARKET_TRADABLE } from '../../constants';
@@ -9,7 +9,7 @@ import {
} from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing';
import { BrowserRouter } from 'react-router-dom';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import type { Market } from '@vegaprotocol/market-list';
import SimpleMarketList from './simple-market-list';
@@ -13,7 +13,7 @@ import SimpleMarketToolbar from './simple-market-toolbar';
import { IS_MARKET_TRADABLE } from '../../constants';
import { ConsoleLiteGrid } from '../console-lite-grid';
import type { Market } from '@vegaprotocol/market-list';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import { marketsWithCandlesProvider } from '@vegaprotocol/market-list';
export type MarketWithPercentChange = Market & {
@@ -4,7 +4,7 @@ import { InView } from 'react-intersection-observer';
import { useDataProvider, useYesterday } from '@vegaprotocol/react-helpers';
import type { Candle } from '@vegaprotocol/market-list';
import { marketCandlesProvider } from '@vegaprotocol/market-list';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
interface Props {
candles: (Candle | null)[] | null;
@@ -1,6 +1,6 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import MarketNameRenderer from './simple-market-renderer';
import type { Market } from '@vegaprotocol/market-list';
@@ -14,7 +14,7 @@ import {
getAllByText,
} from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import type { Market } from '@vegaprotocol/market-list';
import SimpleMarketToolbar from './simple-market-toolbar';
import { markets as filterData } from './mocks/market-filters.json';
@@ -13,7 +13,7 @@ import {
DropdownMenuItemIndicator,
Icon,
} from '@vegaprotocol/ui-toolkit';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import type { Market } from '@vegaprotocol/market-list';
import { HorizontalMenu } from '../horizontal-menu';
import type { HorizontalMenuItem } from '../horizontal-menu';
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import type { MarketWithCandles } from '@vegaprotocol/market-list';
import type { RouterParams } from './simple-market-list';
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Schema from '@vegaprotocol/types';
import { Schema } from '@vegaprotocol/types';
import { t } from '@vegaprotocol/react-helpers';
import type { Market } from '@vegaprotocol/market-list';
-2
View File
@@ -16,5 +16,3 @@ NX_EXPLORER_TXS_LIST=0
NX_EXPLORER_NETWORK_PARAMETERS=1
NX_EXPLORER_PARTIES=1
NX_EXPLORER_VALIDATORS=1
CYPRESS_VEGA_WALLET_API_TOKEN=
+1 -1
View File
@@ -5,7 +5,7 @@ module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
require('@cypress/grep/src/plugin')(config);
require('cypress-grep/src/plugin')(config);
return config;
},
baseUrl: 'http://localhost:3000',
+11 -14
View File
@@ -47,37 +47,34 @@ context('Asset page', { tags: '@regression' }, function () {
.then((assetsListedInJson) => {
const assetInfo = this.assetsInfo[assetName];
assert.equal(assetsListedInJson.name, assetInfo.node.name);
assert.equal(assetsListedInJson.id, assetInfo.node.id);
assert.equal(
assetsListedInJson.decimals,
assetInfo.node.decimals
);
assert.equal(assetsListedInJson.symbol, assetInfo.node.symbol);
assert.equal(assetsListedInJson.name, assetInfo.name);
assert.equal(assetsListedInJson.id, assetInfo.id);
assert.equal(assetsListedInJson.decimals, assetInfo.decimals);
assert.equal(assetsListedInJson.symbol, assetInfo.symbol);
assert.equal(
assetsListedInJson.source.__typename,
assetInfo.node.source.__typename
assetInfo.source.__typename
);
if (assetInfo.node.source.__typename == 'ERC20') {
if (assetInfo.source.__typename == 'ERC20') {
assert.equal(
assetsListedInJson.source.contractAddress,
assetInfo.node.source.contractAddress
assetInfo.source.contractAddress
);
}
if (assetInfo.node.source.__typename == 'BuiltinAsset') {
if (assetInfo.source.__typename == 'BuiltinAsset') {
assert.equal(
assetsListedInJson.source.maxFaucetAmountMint,
assetInfo.node.source.maxFaucetAmountMint
assetInfo.source.maxFaucetAmountMint
);
}
let knownAssetTypes = ['BuiltinAsset', 'ERC20'];
assert.include(
knownAssetTypes,
assetInfo.node.source.__typename,
`Checking that current asset type of ${assetInfo.node.source.__typename} /
assetInfo.source.__typename,
`Checking that current asset type of ${assetInfo.source.__typename} /
is one of: ${knownAssetTypes}: /
If fail then we need to add extra tests for un-encountered asset types`
);
+1 -1
View File
@@ -50,7 +50,7 @@ context('Home Page', function () {
.invoke('text')
.should('match', /\d+d \d+h \d+m \d+s/i);
cy.get(statsValue).eq(3).should('have.text', '2');
cy.get(statsValue).eq(4).should('have.text', '2');
cy.get(statsValue).eq(4).should('have.text', '0');
cy.get(statsValue)
.eq(5)
.invoke('text')
@@ -14,9 +14,7 @@ let assetData = {
const assetsInTest = Object.keys(assetData);
// skipped due to existing issue
// https://github.com/vegaprotocol/frontend-monorepo/issues/2243
context.skip('Parties page', { tags: '@regression' }, function () {
context('Parties page', { tags: '@regression' }, function () {
before('send-faucet assets to connected vega wallet', function () {
assetsInTest.forEach((asset) => {
cy.vega_wallet_receive_fauceted_asset(
@@ -279,9 +279,9 @@ context('Validator page', { tags: '@smoke' }, function () {
Cypress.Commands.add('get_nodes', () => {
const mutation =
'{nodesConnection { edges { node { id name infoUrl avatarUrl pubkey tmPubkey ethereumAddress \
'{nodes { id name infoUrl avatarUrl pubkey tmPubkey ethereumAddress \
location stakedByOperator stakedByDelegates stakedTotal pendingStake \
epochData { total offline online __typename } status name __typename}}}}';
epochData { total offline online __typename } status name __typename}}';
cy.request({
method: 'POST',
url: `http://localhost:3028/query`,
@@ -290,7 +290,7 @@ context('Validator page', { tags: '@smoke' }, function () {
},
headers: { 'content-type': 'application/json' },
})
.its(`body.data.nodesConnection.edges`)
.its(`body.data.nodes`)
.then(function (response) {
let nodes = [];
response.forEach((node) => {
+1 -1
View File
@@ -15,5 +15,5 @@
import '@vegaprotocol/cypress';
import './common.functions.js';
import registerCypressGrep from '@cypress/grep';
import registerCypressGrep from 'cypress-grep';
registerCypressGrep();
+1 -1
View File
@@ -4,7 +4,7 @@
"jsx": "react-jsx",
"sourceMap": false,
"outDir": "../../dist/out-tsc",
"types": ["cypress", "node", "@cypress/grep"],
"types": ["cypress", "node", "cypress-grep"],
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
+3 -2
View File
@@ -1,5 +1,6 @@
NX_TENDERMINT_URL=https://tm.n00.stagnet3.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n00.stagnet3.vega.xyz/websocket
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=https://tm.be.stagnet3.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.stagnet3.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=STAGNET3
+1
View File
@@ -1,4 +1,5 @@
# App configuration variables
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=http://localhost:26617
NX_TENDERMINT_WEBSOCKET_URL=wss://localhost:26617/websocket
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
+1
View File
@@ -1,4 +1,5 @@
# App configuration variables
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=https://n04.d.vega.xyz/tm
NX_TENDERMINT_WEBSOCKET_URL=wss://n04.d.vega.xyz/tm/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/devnet-network.json
+2 -1
View File
@@ -1,5 +1,6 @@
# App configuration variables
NX_TENDERMINT_URL=https://be.explorer.vega.xyz
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=https://be.explorer.vega.xyz/websocket
NX_TENDERMINT_WEBSOCKET_URL=wss://be.explorer.vega.xyz
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/mainnet-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
+2 -2
View File
@@ -7,7 +7,7 @@ NX_VEGA_EXPLORER_URL=https://stagnet1.explorer.vega.xyz
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_TOKEN_URL=https://stagnet1.token.vega.xyz
NX_VEGA_WALLET_URL=http://localhost:1789
NX_TENDERMINT_URL=https://tm.n01.stagnet1.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n01.stagnet1.vega.xyz/websocket
NX_TENDERMINT_URL=https://tm.be.stagnet1.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.stagnet1.vega.xyz/websocket
NX_BLOCK_EXPLORER=https://be.stagnet1.vega.xyz/rest
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
+2 -1
View File
@@ -1,5 +1,6 @@
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=https://tm.n00.stagnet3.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n00.stagnet3.vega.xyz/websocket
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.stagnet3.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=STAGNET3
+2 -1
View File
@@ -1,7 +1,8 @@
# App configuration variables
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=https://tm.be.testnet.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.testnet.vega.xyz/websocket
NX_BLOCK_EXPLORER=https://be.testnet.vega.xyz/rest
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.testnet.vega.xyz/
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/testnet-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=TESTNET
+1
View File
@@ -1,4 +1,5 @@
# App configuration variables
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=http://localhost:26607/
NX_TENDERMINT_WEBSOCKET_URL=wss://localhost:26607/websocket
NX_VEGA_ENV=CUSTOM
+15 -14
View File
@@ -45,20 +45,21 @@ yarn nx run explorer:serve --env={env} # e.g. stagnet3
There are a few different configuration options offered for this app:
| **Flag** | **Purpose** |
| -------------------------------- | ---------------------------------------------------------- | --- |
| `NX_TENDERMINT_URL` | The Tendermint REST URL for the Vega consesus engine |
| `NX_TENDERMINT_WEBSOCKET_URL` | The Tendermint Websocket URL for the Vega consensus engine |
| `NX_VEGA_ENV` | The name of the currently connected vega environment | |
| `NX_EXPLORER_ASSETS` | Enable the assets page for the explorer |
| `NX_EXPLORER_GENESIS` | Enable the genesis page for the explorer |
| `NX_EXPLORER_GOVERNANCE` | Enable the governance page for the explorer |
| `NX_EXPLORER_MARKETS` | Enable the markets page for the explorer |
| `NX_EXPLORER_ORACLES` | Enable the oracles page for the explorer |
| `NX_EXPLORER_TXS_LIST` | Enable the transactions list page for the explorer |
| `NX_EXPLORER_NETWORK_PARAMETERS` | Enable the network parameters page for the explorer |
| `NX_EXPLORER_PARTIES` | Enable the parties page for the explorer |
| `NX_EXPLORER_VALIDATORS` | Enable the validators page for the explorer |
| **Flag** | **Purpose** |
| -------------------------------- | --------------------------------------------------------------- | --- |
| `NX_CHAIN_EXPLORER_URL` | The URL of the chain explorer service for decoding transactions |
| `NX_TENDERMINT_URL` | The Tendermint REST URL for the Vega consesus engine |
| `NX_TENDERMINT_WEBSOCKET_URL` | The Tendermint Websocket URL for the Vega consensus engine |
| `NX_VEGA_ENV` | The name of the currently connected vega environment | |
| `NX_EXPLORER_ASSETS` | Enable the assets page for the explorer |
| `NX_EXPLORER_GENESIS` | Enable the genesis page for the explorer |
| `NX_EXPLORER_GOVERNANCE` | Enable the governance page for the explorer |
| `NX_EXPLORER_MARKETS` | Enable the markets page for the explorer |
| `NX_EXPLORER_ORACLES` | Enable the oracles page for the explorer |
| `NX_EXPLORER_TXS_LIST` | Enable the transactions list page for the explorer |
| `NX_EXPLORER_NETWORK_PARAMETERS` | Enable the network parameters page for the explorer |
| `NX_EXPLORER_PARTIES` | Enable the parties page for the explorer |
| `NX_EXPLORER_VALIDATORS` | Enable the validators page for the explorer |
## Testing
-1
View File
@@ -1,5 +1,4 @@
/* eslint-disable */
process.env.TZ = 'UTC';
export default {
displayName: 'explorer',
preset: '../../jest.preset.js',
@@ -1,5 +0,0 @@
query ExplorerGovernanceAsset {
networkParameter(key: "reward.asset") {
value
}
}
@@ -1,45 +0,0 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerGovernanceAssetQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ExplorerGovernanceAssetQuery = { __typename?: 'Query', networkParameter?: { __typename?: 'NetworkParameter', value: string } | null };
export const ExplorerGovernanceAssetDocument = gql`
query ExplorerGovernanceAsset {
networkParameter(key: "reward.asset") {
value
}
}
`;
/**
* __useExplorerGovernanceAssetQuery__
*
* To run a query within a React component, call `useExplorerGovernanceAssetQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerGovernanceAssetQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useExplorerGovernanceAssetQuery({
* variables: {
* },
* });
*/
export function useExplorerGovernanceAssetQuery(baseOptions?: Apollo.QueryHookOptions<ExplorerGovernanceAssetQuery, ExplorerGovernanceAssetQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerGovernanceAssetQuery, ExplorerGovernanceAssetQueryVariables>(ExplorerGovernanceAssetDocument, options);
}
export function useExplorerGovernanceAssetLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerGovernanceAssetQuery, ExplorerGovernanceAssetQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerGovernanceAssetQuery, ExplorerGovernanceAssetQueryVariables>(ExplorerGovernanceAssetDocument, options);
}
export type ExplorerGovernanceAssetQueryHookResult = ReturnType<typeof useExplorerGovernanceAssetQuery>;
export type ExplorerGovernanceAssetLazyQueryHookResult = ReturnType<typeof useExplorerGovernanceAssetLazyQuery>;
export type ExplorerGovernanceAssetQueryResult = Apollo.QueryResult<ExplorerGovernanceAssetQuery, ExplorerGovernanceAssetQueryVariables>;
@@ -1,40 +0,0 @@
import { addDecimalsFormatNumber } from '@vegaprotocol/react-helpers';
import { AssetLink } from '../links';
import { useExplorerAssetQuery } from '../links/asset-link/__generated__/Asset';
export type AssetBalanceProps = {
assetId: string;
price: string;
showAssetLink?: boolean;
};
/**
* Given a market ID and a price it will fetch the market
* and format the price in that market's decimal places.
*/
const AssetBalance = ({
assetId,
price,
showAssetLink = true,
}: AssetBalanceProps) => {
const { data } = useExplorerAssetQuery({
fetchPolicy: 'cache-first',
variables: { id: assetId },
});
const label =
data && data.asset?.decimals
? addDecimalsFormatNumber(price, data.asset.decimals)
: price;
return (
<div className="inline-block">
<span>{label}</span>{' '}
{showAssetLink && data?.asset?.id ? (
<AssetLink id={data.asset.id} />
) : null}
</div>
);
};
export default AssetBalance;
@@ -1,30 +0,0 @@
import { addDecimalsFormatNumber } from '@vegaprotocol/react-helpers';
import { useExplorerGovernanceAssetQuery } from './__generated__/Governance-asset';
import AssetBalance from './asset-balance';
export type GovernanceAssetBalanceProps = {
price: string;
};
const DEFAULT_DECIMALS = 18;
/**
* Effectively a wrapper around AssetBalance that does an extra query to fetch
* the governance asset first, which is set by a network parameter
*/
const GovernanceAssetBalance = ({ price }: GovernanceAssetBalanceProps) => {
const { data } = useExplorerGovernanceAssetQuery();
if (data && data.networkParameter?.value) {
const governanceAssetId = data.networkParameter.value;
return <AssetBalance price={price} assetId={governanceAssetId} />;
} else {
return (
<div className="inline-block">
<span>{addDecimalsFormatNumber(price, DEFAULT_DECIMALS)}</span>
</div>
);
}
};
export default GovernanceAssetBalance;
@@ -1,4 +1,4 @@
import { useMemo } from 'react';
import React, { useMemo } from 'react';
import type { ReactNode } from 'react';
import { Panel } from '../panel';
import {
@@ -1,4 +1,4 @@
import * as Types from '@vegaprotocol/types';
import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
@@ -16,7 +16,6 @@ export type AssetLinkProps = Partial<ComponentProps<typeof Link>> & {
*/
const AssetLink = ({ id, ...props }: AssetLinkProps) => {
const { data } = useExplorerAssetQuery({
fetchPolicy: 'cache-first',
variables: { id },
});
@@ -21,7 +21,7 @@ export const EthExplorerLink = ({
const link = `${DATA_SOURCES.ethExplorerUrl}/${type}/${id}`;
return (
<a
className="underline external font-mono"
className="underline external"
target="_blank"
rel="noopener noreferrer"
{...props}
@@ -1,15 +1,9 @@
query ExplorerMarket($id: ID!) {
market(id: $id) {
id
decimalPlaces
tradableInstrument {
instrument {
name
product {
... on Future {
quoteName
}
}
}
}
state
@@ -1,4 +1,4 @@
import * as Types from '@vegaprotocol/types';
import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
@@ -8,22 +8,16 @@ export type ExplorerMarketQueryVariables = Types.Exact<{
}>;
export type ExplorerMarketQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, decimalPlaces: number, state: Types.MarketState, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', name: string, product: { __typename?: 'Future', quoteName: string } } } } | null };
export type ExplorerMarketQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, state: Types.MarketState, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', name: string } } } | null };
export const ExplorerMarketDocument = gql`
query ExplorerMarket($id: ID!) {
market(id: $id) {
id
decimalPlaces
tradableInstrument {
instrument {
name
product {
... on Future {
quoteName
}
}
}
}
state
@@ -4,11 +4,10 @@ import type { MockedResponse } from '@apollo/client/testing';
import { render } from '@testing-library/react';
import MarketLink from './market-link';
import { ExplorerMarketDocument } from './__generated__/Market';
import { GraphQLError } from 'graphql';
function renderComponent(id: string, mocks: MockedResponse[]) {
function renderComponent(id: string, mock: MockedResponse[]) {
return (
<MockedProvider mocks={mocks} addTypename={false}>
<MockedProvider mocks={mock}>
<MemoryRouter>
<MarketLink id={id} />
</MemoryRouter>
@@ -22,26 +21,6 @@ describe('Market link component', () => {
expect(res.getByText('123')).toBeInTheDocument();
});
it('Renders the ID with an emoji on error', async () => {
const mock = {
request: {
query: ExplorerMarketDocument,
variables: {
id: '456',
},
},
result: {
errors: [new GraphQLError('No such market')],
},
};
const res = render(renderComponent('456', [mock]));
// The ID
expect(res.getByText('456')).toBeInTheDocument();
// The emoji
expect(await res.findByRole('img')).toBeInTheDocument();
});
it('Renders the market name when the query returns a result', async () => {
const mock = {
request: {
@@ -54,14 +33,10 @@ describe('Market link component', () => {
data: {
market: {
id: '123',
decimalPlaces: 5,
state: 'irrelevant-test-data',
tradableInstrument: {
instrument: {
name: 'test-label',
product: {
quoteName: 'dai',
},
},
},
},
@@ -4,7 +4,6 @@ import { useExplorerMarketQuery } from './__generated__/Market';
import { Link } from 'react-router-dom';
import type { ComponentProps } from 'react';
import { t } from '@vegaprotocol/react-helpers';
export type MarketLinkProps = Partial<ComponentProps<typeof Link>> & {
id: string;
@@ -16,25 +15,14 @@ export type MarketLinkProps = Partial<ComponentProps<typeof Link>> & {
* it will use the ID instead
*/
const MarketLink = ({ id, ...props }: MarketLinkProps) => {
const { data, error, loading } = useExplorerMarketQuery({
const { data } = useExplorerMarketQuery({
variables: { id },
});
let label = <span>{id}</span>;
let label = id;
if (!loading) {
if (data?.market?.tradableInstrument.instrument.name) {
label = <span>{data.market.tradableInstrument.instrument.name}</span>;
} else if (error) {
label = (
<div title={t('Unknown market')}>
<span role="img" aria-label="Unknown market" className="img">
</span>
&nbsp;{id}
</div>
);
}
if (data?.market?.tradableInstrument.instrument.name) {
label = data.market.tradableInstrument.instrument.name;
}
return (
@@ -1,4 +1,4 @@
import * as Types from '@vegaprotocol/types';
import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
@@ -22,7 +22,7 @@ const NodeLink = ({ id, ...props }: NodeLinkProps) => {
return (
<Link className="underline" {...props} to={`/${Routes.VALIDATORS}#${id}`}>
<code>{label}</code>
{label}
</Link>
);
};
@@ -10,11 +10,7 @@ export type PartyLinkProps = Partial<ComponentProps<typeof Link>> & {
const PartyLink = ({ id, ...props }: PartyLinkProps) => {
return (
<Link
className="underline font-mono"
{...props}
to={`/${Routes.PARTIES}/${id}`}
>
<Link className="underline" {...props} to={`/${Routes.PARTIES}/${id}`}>
{id}
</Link>
);
@@ -1,34 +0,0 @@
fragment ExplorerDeterministicOrderFields on Order {
id
type
reference
status
version
createdAt
updatedAt
expiresAt
timeInForce
price
side
remaining
size
rejectionReason
party {
id
}
market {
id
decimalPlaces
tradableInstrument {
instrument {
name
}
}
}
}
query ExplorerDeterministicOrder($orderId: ID!, $version: Int) {
orderByID(id: $orderId, version: $version) {
...ExplorerDeterministicOrderFields
}
}
@@ -1,81 +0,0 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerDeterministicOrderFieldsFragment = { __typename?: 'Order', id: string, type?: Types.OrderType | null, reference: string, status: Types.OrderStatus, version: string, createdAt: any, updatedAt?: any | null, expiresAt?: any | null, timeInForce: Types.OrderTimeInForce, price: string, side: Types.Side, remaining: string, size: string, rejectionReason?: Types.OrderRejectionReason | null, party: { __typename?: 'Party', id: string }, market: { __typename?: 'Market', id: string, decimalPlaces: number, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', name: string } } } };
export type ExplorerDeterministicOrderQueryVariables = Types.Exact<{
orderId: Types.Scalars['ID'];
version?: Types.InputMaybe<Types.Scalars['Int']>;
}>;
export type ExplorerDeterministicOrderQuery = { __typename?: 'Query', orderByID: { __typename?: 'Order', id: string, type?: Types.OrderType | null, reference: string, status: Types.OrderStatus, version: string, createdAt: any, updatedAt?: any | null, expiresAt?: any | null, timeInForce: Types.OrderTimeInForce, price: string, side: Types.Side, remaining: string, size: string, rejectionReason?: Types.OrderRejectionReason | null, party: { __typename?: 'Party', id: string }, market: { __typename?: 'Market', id: string, decimalPlaces: number, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', name: string } } } } };
export const ExplorerDeterministicOrderFieldsFragmentDoc = gql`
fragment ExplorerDeterministicOrderFields on Order {
id
type
reference
status
version
createdAt
updatedAt
expiresAt
timeInForce
price
side
remaining
size
rejectionReason
party {
id
}
market {
id
decimalPlaces
tradableInstrument {
instrument {
name
}
}
}
}
`;
export const ExplorerDeterministicOrderDocument = gql`
query ExplorerDeterministicOrder($orderId: ID!, $version: Int) {
orderByID(id: $orderId, version: $version) {
...ExplorerDeterministicOrderFields
}
}
${ExplorerDeterministicOrderFieldsFragmentDoc}`;
/**
* __useExplorerDeterministicOrderQuery__
*
* To run a query within a React component, call `useExplorerDeterministicOrderQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerDeterministicOrderQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useExplorerDeterministicOrderQuery({
* variables: {
* orderId: // value for 'orderId'
* version: // value for 'version'
* },
* });
*/
export function useExplorerDeterministicOrderQuery(baseOptions: Apollo.QueryHookOptions<ExplorerDeterministicOrderQuery, ExplorerDeterministicOrderQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerDeterministicOrderQuery, ExplorerDeterministicOrderQueryVariables>(ExplorerDeterministicOrderDocument, options);
}
export function useExplorerDeterministicOrderLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerDeterministicOrderQuery, ExplorerDeterministicOrderQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerDeterministicOrderQuery, ExplorerDeterministicOrderQueryVariables>(ExplorerDeterministicOrderDocument, options);
}
export type ExplorerDeterministicOrderQueryHookResult = ReturnType<typeof useExplorerDeterministicOrderQuery>;
export type ExplorerDeterministicOrderLazyQueryHookResult = ReturnType<typeof useExplorerDeterministicOrderLazyQuery>;
export type ExplorerDeterministicOrderQueryResult = Apollo.QueryResult<ExplorerDeterministicOrderQuery, ExplorerDeterministicOrderQueryVariables>;
@@ -1,153 +0,0 @@
import type { components } from '../../../types/explorer';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import { MemoryRouter } from 'react-router-dom';
import AmendOrderDetails from './amend-order-details';
import { ExplorerDeterministicOrderDocument } from './__generated__/Order';
import { render } from '@testing-library/react';
import * as Schema from '@vegaprotocol/types';
import { ExplorerMarketDocument } from '../links/market-link/__generated__/Market';
type Amend = components['schemas']['v1OrderAmendment'];
function renderAmendOrderDetails(
id: string,
version: number,
amend: Amend,
mocks: MockedResponse[]
) {
return render(
<MockedProvider mocks={mocks} addTypename={false}>
<MemoryRouter>
<AmendOrderDetails version={version} id={id} amend={amend} />
</MemoryRouter>
</MockedProvider>
);
}
function renderExistingAmend(id: string, version: number, amend: Amend) {
const mocks = [
{
request: {
query: ExplorerDeterministicOrderDocument,
variables: {
orderId: '123',
version: 1,
},
},
result: {
data: {
orderByID: {
__typename: 'Order',
id: '123',
type: 'GTT',
status: Schema.OrderStatus.STATUS_ACTIVE,
version: version,
createdAt: '123',
updatedAt: '456',
expiresAt: '789',
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
price: '200',
side: 'BUY',
remaining: '99',
rejectionReason: 'rejection',
reference: '123',
size: '100',
party: {
__typename: 'Party',
id: '234',
},
market: {
__typename: 'Market',
id: '789',
decimalPlaces: '5',
tradableInstrument: {
instrument: {
name: 'test',
},
},
},
},
},
},
},
{
request: {
query: ExplorerMarketDocument,
variables: {
id: '789',
},
},
result: {
data: {
market: {
id: '789',
decimalPlaces: 5,
state: 'irrelevant-test-data',
tradableInstrument: {
instrument: {
name: 'test-label',
product: {
quoteName: 'dai',
},
},
},
},
},
},
},
];
return renderAmendOrderDetails(id, version, amend, mocks);
}
describe('Amend order details', () => {
it('Renders price if price changed', async () => {
const amend: Amend = {
sizeDelta: '123',
};
const res = renderExistingAmend('123', 1, amend);
expect(await res.findByText('New size')).toBeInTheDocument();
});
it('Renders Reference if provided', async () => {
const amend: Amend = {
peggedReference: 'PEGGED_REFERENCE_MID',
};
const res = renderExistingAmend('123', 1, amend);
expect(await res.findByText('New reference')).toBeInTheDocument();
expect(await res.findByText('Mid')).toBeInTheDocument();
});
it('Renders offset if provided: positive', async () => {
const amend: Amend = {
peggedOffset: '1',
};
const res = renderExistingAmend('123', 1, amend);
expect(await res.findByText('New offset')).toBeInTheDocument();
expect(await res.findByText('1')).toBeInTheDocument();
});
it('Renders positive price if provided', async () => {
const amend: Amend = {
price: '7879',
};
const res = renderExistingAmend('123', 1, amend);
expect(await res.findByText('New price')).toBeInTheDocument();
expect(await res.findByText('7879')).toBeInTheDocument();
});
it('Renders negative price if provided', async () => {
const amend: Amend = {
price: '-7879',
};
const res = renderExistingAmend('123', 1, amend);
expect(await res.findByText('New price')).toBeInTheDocument();
expect(await res.findByText('-7879')).toBeInTheDocument();
});
});
@@ -1,139 +0,0 @@
import { t } from '@vegaprotocol/react-helpers';
import { useExplorerDeterministicOrderQuery } from './__generated__/Order';
import { MarketLink } from '../links';
import PriceInMarket from '../price-in-market/price-in-market';
import { Time } from '../time';
import { sideText, peggedReference } from './lib/order-labels';
import type { components } from '../../../types/explorer';
import { VegaColours } from '@vegaprotocol/tailwindcss-config';
import { wrapperClasses } from './deterministic-order-details';
export interface AmendOrderDetailsProps {
id: string;
amend: components['schemas']['v1OrderAmendment'];
// Version to fetch, with 0 being 'latest' and 1 being 'first'. Defaults to 0
version?: number;
}
export function getSideDeltaColour(delta: string): string {
if (delta.charAt(0) === '-') {
return VegaColours.pink.DEFAULT;
} else {
return VegaColours.green.DEFAULT;
}
}
/**
* This component renders the changes to an order made in an amend. It's very
* similar to the deterministic-order-details component, and should probably
* eventually be merged in to that view. However the APIs to make that experience
* work nicely are not available, so instead of making 1 complex component, it's
* currently 2 similar components.
*
* @param param0
* @returns
*/
const AmendOrderDetails = ({
id,
version = 0,
amend,
}: AmendOrderDetailsProps) => {
const { data, error } = useExplorerDeterministicOrderQuery({
variables: { orderId: id, version },
});
if (error || (data && !data.orderByID)) {
return (
<div className={wrapperClasses}>
<div className="mb-12 lg:mb-0">
<div className="relative block rounded-lg px-3 py-6 md:px-6 lg:-mr-7">
<h2 className="text-3xl font-bold mb-4 display-5">
{t('Order not found')}
</h2>
<p className="text-gray-500 mb-12">
{t('No order created from this transaction')}
</p>
</div>
</div>
</div>
);
}
if (!data || !data.orderByID) {
return null;
}
const o = data.orderByID;
return (
<div className={wrapperClasses}>
<div className="mb-12 lg:mb-0">
<div className="relative block px-3 py-6 md:px-6 lg:-mr-7">
<h2 className="text-3xl font-bold mb-4 display-5">
{t('Edits to ')}
{sideText[o.side]}
{t(' order')}
</h2>
<p className="text-gray-500 mb-4">
In <MarketLink id={o.market.id} />, updated at{' '}
<Time date={o.updatedAt} />.
</p>
<div className="grid md:grid-cols-4 gap-x-6">
{amend.sizeDelta && amend.sizeDelta !== '0' ? (
<div className="mb-12 md:mb-0">
<h2 className="text-2xl font-bold text-dark mb-4">
{t('New size')}
</h2>
<h5
className={`text-lg font-medium text-gray-500 mb-0 capitalize ${getSideDeltaColour(
amend.sizeDelta
)}`}
>
{amend.sizeDelta}
</h5>
</div>
) : null}
{amend.price && amend.price !== '0' ? (
<div className="">
<h2 className="text-2xl font-bold text-dark mb-4">
{t('New price')}
</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0">
<PriceInMarket price={amend.price} marketId={o.market.id} />
</h5>
</div>
) : null}
{amend.peggedReference &&
amend.peggedReference !== 'PEGGED_REFERENCE_UNSPECIFIED' ? (
<div className="">
<h2 className="text-2xl font-bold text-dark mb-4">
{t('New reference')}
</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0">
{peggedReference[amend.peggedReference]}
</h5>
</div>
) : null}
{amend.peggedOffset ? (
<div className="">
<h2 className="text-2xl font-bold text-dark mb-4">
{t('New offset')}
</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0">
{amend.peggedOffset}
</h5>
</div>
) : null}
</div>
</div>
</div>
</div>
);
};
export default AmendOrderDetails;
@@ -1,123 +0,0 @@
import { t } from '@vegaprotocol/react-helpers';
import { useExplorerDeterministicOrderQuery } from './__generated__/Order';
import { MarketLink } from '../links';
import PriceInMarket from '../price-in-market/price-in-market';
import { Time } from '../time';
import { sideText, statusText, tifFull, tifShort } from './lib/order-labels';
export interface DeterministicOrderDetailsProps {
id: string;
// Version to fetch, with 0 being 'latest' and 1 being 'first'. Defaults to 0
version?: number;
}
export const wrapperClasses =
'grid lg:grid-cols-1 flex items-center max-w-xl border border-zinc-200 dark:border-zinc-800 rounded-md pv-2 ph-5 mb-5';
/**
* This component renders the *current* details for an order
*
* An important part of this component is that unlike most of the rest of the Explorer,
* it is displaying 'live' data. With the current APIs it's impossible to get the state
* of the order at a specific point in time. While one day that might be possible, this
* order component is not built with that in mind.
*
* @param param0
* @returns
*/
const DeterministicOrderDetails = ({
id,
version = 0,
}: DeterministicOrderDetailsProps) => {
const { data, error } = useExplorerDeterministicOrderQuery({
variables: { orderId: id, version },
});
if (error || (data && !data.orderByID)) {
return (
<div className={wrapperClasses}>
<div className="mb-12 lg:mb-0">
<div className="relative block rounded-lg px-3 py-6 md:px-6 lg:-mr-7">
<h2 className="text-3xl font-bold mb-4 display-5">
{t('Order not found')}
</h2>
<p className="text-gray-500 mb-12">
{t('No order created from this transaction')}
</p>
</div>
</div>
</div>
);
}
if (!data || !data.orderByID) {
return null;
}
const o = data.orderByID;
return (
<div className={wrapperClasses}>
<div className="mb-12 lg:mb-0">
<div className="relative block px-3 py-6 md:px-6 lg:-mr-7">
<h2 className="text-3xl font-bold mb-4 display-5">
<abbr title={tifFull[o.timeInForce]} className="bb-dotted mr-2">
{tifShort[o.timeInForce]}
</abbr>
{sideText[o.side]}
<span className="mx-5 text-base">@</span>
<PriceInMarket price={o.price} marketId={o.market.id} />
</h2>
<p className="text-gray-500 mb-4">
In <MarketLink id={o.market.id} /> at <Time date={o.createdAt} />.
</p>
{o.reference ? (
<p className="text-gray-500 mb-4">
<span>{t('Reference')}</span>: {o.reference}
</p>
) : null}
<div className="grid md:grid-cols-4 gap-x-6">
{version !== 0 ? null : (
<div className="mb-12 md:mb-0">
<h2 className="text-2xl font-bold text-dark mb-4">
{t('Status')}
</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0 capitalize">
{statusText[o.status]}
</h5>
</div>
)}
<div className="mb-12 md:mb-0">
<h2 className="text-2xl font-bold text-dark mb-4">{t('Size')}</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0">
{o.size}
</h5>
</div>
{version !== 0 ? null : (
<div className="">
<h2 className="text-2xl font-bold text-dark mb-4">
{t('Remaining')}
</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0">
{o.remaining}
</h5>
</div>
)}
<div className="">
<h2 className="text-2xl font-bold text-dark mb-4">
{t('Version')}
</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0">
{o.version}
</h5>
</div>
</div>
</div>
</div>
</div>
);
};
export default DeterministicOrderDetails;
@@ -1,49 +0,0 @@
import { t } from '@vegaprotocol/react-helpers';
import type * as Schema from '@vegaprotocol/types';
export interface DeterministicOrderDetailsProps {
id: string;
// Version to fetch, with 0 being 'latest' and 1 being 'first'. Defaults to 0
version?: number;
}
export const statusText: Record<Schema.OrderStatus, string> = {
STATUS_ACTIVE: t('Active'),
STATUS_CANCELLED: t('Cancelled'),
STATUS_EXPIRED: t('Expired'),
STATUS_FILLED: t('Filled'),
STATUS_PARKED: t('Parked'),
// Intentionally vague - table shows partial fills
STATUS_PARTIALLY_FILLED: t('Active'),
STATUS_REJECTED: t('Rejected'),
STATUS_STOPPED: t('Stopped'),
};
export const sideText: Record<Schema.Side, string> = {
SIDE_BUY: t('Buy'),
SIDE_SELL: t('Sell'),
};
export const tifShort: Record<Schema.OrderTimeInForce, string> = {
TIME_IN_FORCE_FOK: t('FOK'),
TIME_IN_FORCE_GFA: t('GFA'),
TIME_IN_FORCE_GFN: t('GFN'),
TIME_IN_FORCE_GTC: t('GTC'),
TIME_IN_FORCE_GTT: t('GTT'),
TIME_IN_FORCE_IOC: t('IOC'),
};
export const tifFull: Record<Schema.OrderTimeInForce, string> = {
TIME_IN_FORCE_FOK: t('Fill or Kill'),
TIME_IN_FORCE_GFA: t('Good for Auction'),
TIME_IN_FORCE_GFN: t('Good for Normal'),
TIME_IN_FORCE_GTC: t("Good 'til Cancel"),
TIME_IN_FORCE_GTT: t("Good 'til Time"),
TIME_IN_FORCE_IOC: t('Immediate or Cancel'),
};
export const peggedReference: Record<Schema.PeggedReference, string> = {
PEGGED_REFERENCE_BEST_ASK: 'Best Ask',
PEGGED_REFERENCE_BEST_BID: 'Best Bid',
PEGGED_REFERENCE_MID: 'Mid',
};
@@ -1,92 +0,0 @@
import { MemoryRouter } from 'react-router-dom';
import { MockedProvider } from '@apollo/client/testing';
import type { MockedResponse } from '@apollo/client/testing';
import { render } from '@testing-library/react';
import PriceInMarket from './price-in-market';
import { ExplorerMarketDocument } from '../links/market-link/__generated__/Market';
function renderComponent(
price: string,
marketId: string,
mocks: MockedResponse[]
) {
return (
<MockedProvider mocks={mocks} addTypename={false}>
<MemoryRouter>
<PriceInMarket marketId={marketId} price={price} />
</MemoryRouter>
</MockedProvider>
);
}
describe('Price in Market component', () => {
it('Renders the raw price when there is no market data', () => {
const res = render(renderComponent('100', '123', []));
expect(res.getByText('100')).toBeInTheDocument();
});
it('Renders the formatted price when market data is fetched', async () => {
const mock = {
request: {
query: ExplorerMarketDocument,
variables: {
id: '123',
},
},
result: {
data: {
market: {
id: '123',
decimalPlaces: 2,
state: 'irrelevant-test-data',
tradableInstrument: {
instrument: {
name: 'test dai',
product: {
__typename: 'Future',
quoteName: 'dai',
},
},
},
},
},
},
};
const res = render(renderComponent('100', '123', [mock]));
expect(await res.findByText('1.00')).toBeInTheDocument();
expect(await res.findByText('dai')).toBeInTheDocument();
});
it('Leaves the market id when the market is not found', async () => {
const mock = {
request: {
query: ExplorerMarketDocument,
variables: {
id: '123',
},
},
error: new Error('No such market'),
};
const res = render(renderComponent('100', '123', [mock]));
expect(await res.findByText('100')).toBeInTheDocument();
});
it('Renders `Market` instead of a price for market orders: 0 price', () => {
const res = render(renderComponent('0', '123', []));
expect(res.getByText('Market')).toBeInTheDocument();
});
it('Renders `Market` instead of a price for market orders: undefined price', () => {
const res = render(
renderComponent(undefined as unknown as string, '123', [])
);
expect(res.getByText('Market')).toBeInTheDocument();
});
it('Renders `Market` instead of a price for market orders: empty price', () => {
const res = render(renderComponent('', '123', []));
expect(res.getByText('Market')).toBeInTheDocument();
});
});

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