Compare commits

..
Author SHA1 Message Date
Matthew Russell ae7a639fc2 chore: cherry pick position pnl formatting fix 2023-07-19 11:34:50 +01:00
5b8df4c414 chore(trading): orderbook adjustments (#4293)
Co-authored-by: Ben <ben@vega.xyz>
Co-authored-by: Mikołaj Młodzikowski <mikolaj.mlodzikowski@gmail.com>
Co-authored-by: Joe Tsang <30622993+jtsang586@users.noreply.github.com>
Co-authored-by: Dexter Edwards <dexter.edwards93@gmail.com>
Co-authored-by: m.ray <16125548+MadalinaRaicu@users.noreply.github.com>
Co-authored-by: Art <artur@vegaprotocol.io>
Co-authored-by: Bartłomiej Głownia <bglownia@gmail.com>
Co-authored-by: Gordsport <83510148+gordsport@users.noreply.github.com>
2023-07-18 14:48:51 +00:00
Daniel ce6873fe54 feat(environment): add mainnet mirror config (#4287) 2023-07-18 12:23:58 +01:00
Gordsport d0e64364e3 chore: update the PM action secret token (#4325) 2023-07-18 12:16:57 +01:00
Bartłomiej Głownia 737ffb4c35 feat(trading): copy order book volume value to deal ticket (#4333) 2023-07-18 12:16:07 +01:00
Maciek 53048ac8ef chore(trading): 4134 see if a closed market was succeeded (#4336) 2023-07-18 09:37:25 +00:00
Art 05ca1a09b9 chore(explorer): align staking terminology (#4290) 2023-07-18 09:03:48 +00:00
m.ray 94e398dd1c feat(trading): submit iceberg orders (#4230) 2023-07-17 14:24:51 +00:00
m.ray 7c0a4f61e9 fix(trading): add internal termination oracle (#4208) 2023-07-17 13:33:52 +00:00
m.ray 056d3215e8 feat(trading): view iceberg orders (#4207) 2023-07-17 13:04:03 +00:00
Dexter Edwards a68b2093e4 fix(ui-toolkit): toolkit bugs (#4329) 2023-07-17 10:59:22 +00:00
Mikołaj Młodzikowski f440f57be2 fix(ci): do not trigger releasing to s3 on pull requests 2023-07-14 13:45:06 +02:00
59 changed files with 1079 additions and 170 deletions
+9 -3
View File
@@ -28,6 +28,7 @@ jobs:
echo IS_MAINNET_RELEASE=false >> $GITHUB_ENV
echo IS_TESTNET_RELEASE=false >> $GITHUB_ENV
echo IS_IPFS_RELEASE=false >> $GITHUB_ENV
echo IS_S3_RELASE=false >> $GITHUB_ENV
- name: Is PR
if: ${{ github.event_name == 'pull_request' }}
@@ -49,6 +50,11 @@ jobs:
run: |
echo IS_IPFS_RELEASE=true >> $GITHUB_ENV
- name: Is S3 Release
if: ${{ env.IS_IPFS_RELASE == 'false' && github.event_name == 'push' }}
run: |
echo IS_S3_RELASE=true >> $GITHUB_ENV
- name: Set up QEMU
id: quemu
uses: docker/setup-qemu-action@v2
@@ -245,7 +251,7 @@ jobs:
- name: Publish dist to s3
uses: jakejarvis/s3-sync-action@master
# s3 releases are not happening for trading on mainnet - it's IPFS
if: ${{ env.IS_IPFS_RELEASE == 'false' }}
if: ${{ env.IS_S3_RELASE == 'true' }}
with:
args: --acl private --follow-symlinks --delete
env:
@@ -256,11 +262,11 @@ jobs:
SOURCE_DIR: 'dist-result'
- name: Install aws CLI
if: ${{ env.IS_IPFS_RELEASE == 'false' }}
if: ${{ env.IS_S3_RELASE == 'true' }}
uses: unfor19/install-aws-cli-action@master
- name: Perform cache invalidation
if: ${{ env.IS_IPFS_RELEASE == 'false' }}
if: ${{ env.IS_S3_RELASE == 'true' }}
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+1 -1
View File
@@ -4,7 +4,7 @@ NX_TENDERMINT_WEBSOCKET_URL=wss://be.mainnet-mirror.vega.rocks/websocket
NX_SENTRY_DSN=https://4b8c8a8ba07742648aa4dfe1b8d17e40@o286262.ingest.sentry.io/5882996
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/mainnet-mirror/vegawallet-mainnet-mirror.toml
NX_VEGA_URL=https://api.mainnet-mirror.vega.rocks/graphql
NX_VEGA_ENV=MAINNET-MIRROR
NX_VEGA_ENV=MAINNET_MIRROR
NX_BLOCK_EXPLORER=https://be.mainnet-mirror.vega.rocks/rest
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://governance.mainnet-mirror.vega.rocks
@@ -54,7 +54,7 @@ export const PartyBlockStake = ({
{p?.stakingSummary.currentStakeAvailable ? (
<KeyValueTable>
<KeyValueTableRow noBorder={true}>
<div>{t('Available stake')}</div>
<div>{t('Associated to key')}</div>
<div>
<GovernanceAssetBalance
price={p.stakingSummary.currentStakeAvailable}
@@ -62,7 +62,7 @@ export const PartyBlockStake = ({
</div>
</KeyValueTableRow>
<KeyValueTableRow noBorder={true}>
<div>{t('Active stake')}</div>
<div>{t('Staked to validator')}</div>
<div>
<GovernanceAssetBalance price={linkedStake || '0'} />
</div>
+2 -2
View File
@@ -1,8 +1,8 @@
# App configuration variables
NX_VEGA_ENV=MAINNET-MIRROR
NX_VEGA_ENV=MAINNET_MIRROR
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/mainnet-mirror/vegawallet-mainnet-mirror.toml
NX_VEGA_URL=https://api.mainnet-mirror.vega.rocks/graphql
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.governance.vega.xyz","TESTNET":"https://governance.fairground.wtf","MAINNET":"https://governance.vega.xyz","MAINNET-MIRROR":"https://governance.mainnet-mirror.vega.rocks","STAGNET1":"https://trading.stagnet1.vega.rocks"}'
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.governance.vega.xyz","TESTNET":"https://governance.fairground.wtf","MAINNET":"https://governance.vega.xyz","MAINNET_MIRROR":"https://governance.mainnet-mirror.vega.rocks","STAGNET1":"https://trading.stagnet1.vega.rocks"}'
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
+4
View File
@@ -25,6 +25,10 @@ export const ContractAddresses: {
claimAddress: customClaimAddress ?? '0x0',
lockedAddress: customLockedAddress ?? '0x0',
},
MAINNET_MIRROR: {
claimAddress: '0x8Cef746ab7C83B61F6461cC92882bD61AB65a994', // TODO not deployed to this env, but random address so app doesn't error
lockedAddress: '0x0', // TODO not deployed to this env
},
DEVNET: {
claimAddress: '0x8Cef746ab7C83B61F6461cC92882bD61AB65a994', // TODO not deployed to this env, but random address so app doesn't error
lockedAddress: '0x0', // TODO not deployed to this env
File diff suppressed because one or more lines are too long
@@ -3,12 +3,12 @@ import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ProposalFieldsFragment = { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string } } };
export type ProposalFieldsFragment = { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string } } };
export type ProposalsQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ProposalsQuery = { __typename?: 'Query', proposalsConnection?: { __typename?: 'ProposalsConnection', edges?: Array<{ __typename?: 'ProposalEdge', node: { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string } } } } | null> | null } | null };
export type ProposalsQuery = { __typename?: 'Query', proposalsConnection?: { __typename?: 'ProposalsConnection', edges?: Array<{ __typename?: 'ProposalEdge', node: { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string } } } } | null> | null } | null };
export const ProposalFieldsFragmentDoc = gql`
fragment ProposalFields on Proposal {
@@ -369,6 +369,10 @@ describe('Closed markets', { tags: '@smoke' }, () => {
.first()
.find('button svg')
.should('exist');
cy.get(rowSelector)
.find('[col-id="successorMarketID"]')
.first()
.should('have.text', ' - ');
});
// test market list for market in terminated state
@@ -9,6 +9,7 @@ const bidCumulative = 'cumulative-vol-9889001';
const midPrice = 'middle-mark-price-4612690000';
const priceResolution = 'resolution';
const dealTicketPrice = 'order-price';
const dealTicketSize = 'order-size';
const resPrice = 'price-990';
describe('order book', { tags: '@smoke' }, () => {
@@ -74,6 +75,18 @@ describe('order book', { tags: '@smoke' }, () => {
cy.getByTestId(dealTicketPrice).should('have.value', '98.94585');
});
it('copy size to deal ticket form', () => {
// 6003-ORDB-009
cy.getByTestId(bidCumulative).click();
cy.getByTestId(dealTicketSize).should('have.value', '7');
});
it('copy size to deal ticket form', () => {
// 6003-ORDB-009
cy.getByTestId(bidVolume).click();
cy.getByTestId(dealTicketSize).should('have.value', '1');
});
it('change price resolution', () => {
// 6003-ORDB-008
const resolutions = [
@@ -88,13 +101,14 @@ describe('order book', { tags: '@smoke' }, () => {
'1,000',
'10,000',
];
cy.getByTestId(priceResolution)
.find('option')
cy.getByTestId(priceResolution).click();
cy.get('[role="menu"]')
.find('[role="menuitem"]')
.each(($el, index) => {
expect($el.text()).to.equal(resolutions[index]);
});
cy.getByTestId(priceResolution).select('0.0');
cy.get('[role="menuitem"]').eq(4).click();
cy.getByTestId(resPrice).should('have.text', '99.0');
cy.getByTestId(askPrice).should('not.exist');
cy.getByTestId(bidPrice).should('not.exist');
@@ -50,7 +50,7 @@ describe('Portfolio page', { tags: '@smoke' }, () => {
cy.get('fieldset.ag-simple-filter-body-wrapper')
.should('be.visible')
.within((fields) => {
cy.wrap(fields).find('label').should('have.length', 16);
cy.wrap(fields).find('label').should('have.length', 18);
});
cy.getByTestId('"Ledger entries"').click();
cy.get('fieldset.ag-simple-filter-body-wrapper').should('not.exist');
@@ -71,7 +71,7 @@ describe('trades', { tags: '@smoke' }, () => {
});
});
it('copy price to deal ticket form', () => {
it.skip('copy price to deal ticket form', () => {
// 6005-THIS-007
cy.get(colIdPrice).last().should('be.visible').click();
cy.getByTestId('order-price').should('have.value', '171.16898');
+2 -2
View File
@@ -3,9 +3,9 @@ NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_SENTRY_DSN=https://2ffce43721964aafa78277c50654ece4@o286262.ingest.sentry.io/6300613
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/mainnet-mirror/vegawallet-mainnet-mirror.toml
NX_VEGA_ENV=MAINNET-MIRROR
NX_VEGA_ENV=MAINNET_MIRROR
NX_VEGA_EXPLORER_URL=https://explorer.mainnet-mirror.vega.rocks
NX_VEGA_NETWORKS={\"MAINNET\":\"https://console.vega.xyz\",\"TESTNET\":\"https://console.fairground.wtf\",\"STAGNET1\":\"https://trading.stagnet1.vega.rocks\",\"MAINNET-MIRROR\":\"https://trading.mainnet-mirror.vega.rocks\"}
NX_VEGA_NETWORKS={\"MAINNET\":\"https://console.vega.xyz\",\"TESTNET\":\"https://console.fairground.wtf\",\"STAGNET1\":\"https://trading.stagnet1.vega.rocks\",\"MAINNET_MIRROR\":\"https://trading.mainnet-mirror.vega.rocks\"}
NX_VEGA_TOKEN_URL=https://governance.mainnet-mirror.vega.rocks
NX_VEGA_WALLET_URL=http://localhost:1789
NX_VEGA_DOCS_URL=https://docs.vega.xyz/mainnet
+104 -22
View File
@@ -1,4 +1,5 @@
import { act, render, screen, within } from '@testing-library/react';
import { act, render, screen, within, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { Closed } from './closed';
import { MarketStateMapping, PropertyKeyType } from '@vegaprotocol/types';
import { PositionStatus } from '@vegaprotocol/types';
@@ -211,15 +212,22 @@ describe('Closed', () => {
it('renders correctly formatted and filtered rows', async () => {
await act(async () => {
render(
<MockedProvider
mocks={[marketsMock, marketsDataMock, positionsMock, oracleDataMock]}
>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
<MemoryRouter>
<MockedProvider
mocks={[
marketsMock,
marketsDataMock,
positionsMock,
oracleDataMock,
]}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
</MemoryRouter>
);
});
// screen.debug(document, Infinity);
@@ -230,6 +238,7 @@ describe('Closed', () => {
'Description',
'Status',
'Settlement date',
'Successor market',
'Best bid',
'Best offer',
'Mark price',
@@ -247,6 +256,7 @@ describe('Closed', () => {
market.tradableInstrument.instrument.name,
MarketStateMapping[market.state],
'3 days ago',
'-',
/* eslint-disable @typescript-eslint/no-non-null-assertion */
addDecimalsFormatNumber(marketsData.bestBidPrice, market.decimalPlaces),
addDecimalsFormatNumber(
@@ -315,20 +325,22 @@ describe('Closed', () => {
};
await act(async () => {
render(
<MockedProvider
mocks={[
mixedMarketsMock,
marketsDataMock,
positionsMock,
oracleDataMock,
]}
>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
<MemoryRouter>
<MockedProvider
mocks={[
mixedMarketsMock,
marketsDataMock,
positionsMock,
oracleDataMock,
]}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
</MemoryRouter>
);
});
@@ -359,4 +371,74 @@ describe('Closed', () => {
});
expect(cells).toEqual(expectedRows.map((m) => m.node.id));
});
it('successor marked should be visible', async () => {
const mixedMarkets = [
{
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'include-0',
state: MarketState.STATE_SETTLED,
successorMarketID: 'successorMarketID',
}),
},
{
__typename: 'MarketEdge' as const,
node: {
...createMarketFragment({
id: 'successorMarketID',
state: MarketState.STATE_ACTIVE,
}),
tradableInstrument: {
...createMarketFragment().tradableInstrument,
instrument: {
...createMarketFragment().tradableInstrument.instrument,
id: 'successorAssset',
name: 'Successor Market Name',
code: 'SuccessorCode',
},
},
},
},
];
const mixedMarketsMock: MockedResponse<MarketsQuery> = {
request: {
query: MarketsDocument,
},
result: {
data: {
marketsConnection: {
__typename: 'MarketConnection',
edges: mixedMarkets,
},
},
},
};
render(
<MemoryRouter>
<MockedProvider
mocks={[
mixedMarketsMock,
marketsDataMock,
positionsMock,
oracleDataMock,
]}
>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
</MemoryRouter>
);
await waitFor(() => {
expect(
screen.getByRole('button', { name: 'SuccessorCode' })
).toBeInTheDocument();
});
});
});
+38 -1
View File
@@ -4,7 +4,11 @@ import type {
VegaICellRendererParams,
VegaValueFormatterParams,
} from '@vegaprotocol/datagrid';
import { AgGridLazy as AgGrid, COL_DEFS } from '@vegaprotocol/datagrid';
import {
AgGridLazy as AgGrid,
COL_DEFS,
MarketNameCell,
} from '@vegaprotocol/datagrid';
import { useMemo } from 'react';
import { t } from '@vegaprotocol/i18n';
import { MarketState, MarketStateMapping } from '@vegaprotocol/types';
@@ -20,6 +24,7 @@ import type {
import {
MarketActionsDropdown,
closedMarketsWithDataProvider,
marketProvider,
} from '@vegaprotocol/markets';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
@@ -27,6 +32,7 @@ import type { ColDef } from 'ag-grid-community';
import { SettlementDateCell } from './settlement-date-cell';
import { SettlementPriceCell } from './settlement-price-cell';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { useMarketClickHandler } from '../../lib/hooks/use-market-click-handler';
type SettlementAsset =
MarketMaybeWithData['tradableInstrument']['instrument']['product']['settlementAsset'];
@@ -48,6 +54,7 @@ interface Row {
tradingTerminationOracleId: string;
settlementAsset: SettlementAsset;
realisedPNL: string | undefined;
successorMarketID: string | undefined | null;
}
export const Closed = () => {
@@ -109,6 +116,7 @@ export const Closed = () => {
instrument.product.dataSourceSpecForTradingTermination.id,
settlementAsset: instrument.product.settlementAsset,
realisedPNL: position?.node.realisedPNL,
successorMarketID: market.successorMarketID,
};
return row;
@@ -120,6 +128,28 @@ export const Closed = () => {
);
};
export const SuccessorMarketRenderer = ({
value,
}: VegaICellRendererParams<Row, 'successorMarketID'>) => {
const { data } = useDataProvider({
dataProvider: marketProvider,
variables: {
marketId: value || '',
},
skip: !value,
});
const onMarketClick = useMarketClickHandler();
return data ? (
<MarketNameCell
value={data.tradableInstrument.instrument.code}
data={data}
onMarketClick={onMarketClick}
/>
) : (
' - '
);
};
const ClosedMarketsDataGrid = ({
rowData,
error,
@@ -199,6 +229,11 @@ const ClosedMarketsDataGrid = ({
},
},
},
{
headerName: t('Successor market'),
field: 'successorMarketID',
cellRenderer: 'SuccessorMarketRenderer',
},
{
headerName: t('Best bid'),
field: 'bestBidPrice',
@@ -311,7 +346,9 @@ const ClosedMarketsDataGrid = ({
defaultColDef={{
resizable: true,
minWidth: 100,
flex: 1,
}}
components={{ SuccessorMarketRenderer }}
overlayNoRowsTemplate={error ? error.message : t('No markets')}
/>
);
@@ -23,6 +23,11 @@ export const OrderTypeCell = ({
return undefined;
}
if (!value) return '-';
if (order?.icebergOrder) {
return t('%s (Iceberg)', [Schema.OrderTypeMapping[value]]);
}
if (order?.peggedOrder) {
const reference =
Schema.PeggedReferenceMapping[order.peggedOrder?.reference];
@@ -34,6 +39,7 @@ export const OrderTypeCell = ({
);
return t('%s %s %s Peg limit', [reference, side, offset]);
}
if (order?.liquidityProvision) {
return t('Liquidity provision');
}
@@ -0,0 +1,195 @@
import { Controller, type Control } from 'react-hook-form';
import type { Market } from '@vegaprotocol/markets';
import type { OrderObj } from '@vegaprotocol/orders';
import type { OrderFormFields } from '../../hooks/use-order-form';
import { toDecimal, validateAmount } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import {
FormGroup,
Input,
InputError,
Tooltip,
} from '@vegaprotocol/ui-toolkit';
export interface DealTicketSizeIcebergProps {
control: Control<OrderFormFields>;
market: Market;
peakSizeError?: string;
minimumVisibleSizeError?: string;
update: (obj: Partial<OrderObj>) => void;
peakSize: string;
minimumVisibleSize: string;
size: string;
}
export const DealTicketSizeIceberg = ({
control,
market,
update,
peakSizeError,
minimumVisibleSizeError,
peakSize,
minimumVisibleSize,
size,
}: DealTicketSizeIcebergProps) => {
const sizeStep = toDecimal(market?.positionDecimalPlaces);
const renderPeakSizeError = () => {
if (peakSizeError) {
return (
<InputError testId="deal-ticket-peak-error-message-size-limit">
{peakSizeError}
</InputError>
);
}
return null;
};
const renderMinimumSizeError = () => {
if (minimumVisibleSizeError) {
return (
<InputError testId="deal-ticket-minimum-error-message-size-limit">
{minimumVisibleSizeError}
</InputError>
);
}
return null;
};
return (
<div className="mb-2">
<div className="flex items-center gap-4">
<div className="flex-1">
<FormGroup
label={
<Tooltip
description={
<div>
{t(
'The maximum volume that can be traded at once. Must be less than the total size of the order.'
)}
</div>
}
>
<span className="text-xs">{t('Peak size')}</span>
</Tooltip>
}
labelFor="input-order-peak-size"
className="!mb-1"
>
<Controller
name="icebergOpts.peakSize"
control={control}
rules={{
required: t('You need to provide a peak size'),
min: {
value: sizeStep,
message: t('Peak size cannot be lower than ' + sizeStep),
},
max: {
value: size,
message: t(
'Peak size cannot be greater than the size (%s) ',
[size]
),
},
validate: validateAmount(sizeStep, 'peakSize'),
}}
render={() => (
<Input
id="input-order-peak-size"
className="w-full"
type="number"
value={peakSize}
onChange={(e) =>
update({
icebergOpts: {
peakSize: e.target.value,
minimumVisibleSize,
},
})
}
step={sizeStep}
min={sizeStep}
max={size}
data-testid="order-peak-size"
onWheel={(e) => e.currentTarget.blur()}
/>
)}
/>
</FormGroup>
</div>
<div className="flex-0 items-center">
<div className="flex"></div>
<div className="flex"></div>
</div>
<div className="flex-1">
<FormGroup
label={
<Tooltip
description={
<div>
{t(
'When the order trades and its size falls below this threshold, it will be reset to the peak size and moved to the back of the priority order. Must be less than or equal to peak size, and greater than 0.'
)}
</div>
}
>
<span className="text-xs">{t('Minimum size')}</span>
</Tooltip>
}
labelFor="input-order-minimum-size"
className="!mb-1"
>
<Controller
name="icebergOpts.minimumVisibleSize"
control={control}
rules={{
required: t('You need to provide a minimum visible size'),
min: {
value: sizeStep,
message: t(
'Minimum visible size cannot be lower than ' + sizeStep
),
},
max: {
value: peakSize,
message: t(
'Minimum visible size cannot be greater than the peak size (%s)',
[peakSize]
),
},
validate: validateAmount(sizeStep, 'minimumVisibleSize'),
}}
render={() => (
<Input
id="input-order-minimum-size"
className="w-full"
type="number"
value={minimumVisibleSize}
onChange={(e) =>
update({
icebergOpts: {
peakSize,
minimumVisibleSize: e.target.value,
},
})
}
step={sizeStep}
min={sizeStep}
max={peakSize}
data-testid="order-minimum-size"
onWheel={(e) => e.currentTarget.blur()}
/>
)}
/>
</FormGroup>
</div>
</div>
{renderPeakSizeError()}
{renderMinimumSizeError()}
</div>
);
};
@@ -224,6 +224,109 @@ describe('DealTicket', () => {
expect(screen.getByTestId('reduce-only')).not.toBeChecked();
});
it('should set values for a persistent post only iceberg order and disable reduce only checkbox', () => {
const expectedOrder = {
marketId: market.id,
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
size: '10',
price: '300.22',
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
persist: true,
reduceOnly: false,
postOnly: true,
iceberg: true,
icebergOpts: {
peakSize: '5',
minimumVisibleSize: '7',
},
};
useOrderStore.setState({
orders: {
[expectedOrder.marketId]: expectedOrder,
},
});
render(generateJsx());
// Assert correct defaults are used from store
expect(
screen
.getByTestId(`order-type-${Schema.OrderType.TYPE_LIMIT}`)
.querySelector('input')
).toBeChecked();
expect(
screen.queryByTestId('order-side-SIDE_SELL')?.querySelector('input')
).toBeChecked();
expect(
screen.queryByTestId('order-side-SIDE_BUY')?.querySelector('input')
).not.toBeChecked();
expect(screen.getByTestId('order-size')).toHaveDisplayValue(
expectedOrder.size
);
expect(screen.getByTestId('order-tif')).toHaveValue(
expectedOrder.timeInForce
);
expect(screen.getByTestId('order-price')).toHaveDisplayValue(
expectedOrder.price
);
expect(screen.getByTestId('post-only')).toBeEnabled();
expect(screen.getByTestId('reduce-only')).toBeDisabled();
expect(screen.getByTestId('post-only')).toBeChecked();
expect(screen.getByTestId('reduce-only')).not.toBeChecked();
expect(screen.getByTestId('iceberg')).toBeEnabled();
expect(screen.getByTestId('iceberg')).toBeChecked();
});
it('should set values for a non-persistent iceberg order and disable post only checkbox', () => {
const expectedOrder = {
marketId: market.id,
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
size: '0.1',
price: '300.22',
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC,
persist: false,
reduceOnly: false,
postOnly: false,
};
useOrderStore.setState({
orders: {
[expectedOrder.marketId]: expectedOrder,
},
});
render(generateJsx());
// Assert correct defaults are used from store
expect(
screen
.getByTestId(`order-type-${Schema.OrderType.TYPE_LIMIT}`)
.querySelector('input')
).toBeChecked();
expect(
screen.queryByTestId('order-side-SIDE_SELL')?.querySelector('input')
).toBeChecked();
expect(
screen.queryByTestId('order-side-SIDE_BUY')?.querySelector('input')
).not.toBeChecked();
expect(screen.getByTestId('order-size')).toHaveDisplayValue(
expectedOrder.size
);
expect(screen.getByTestId('order-tif')).toHaveValue(
expectedOrder.timeInForce
);
expect(screen.getByTestId('order-price')).toHaveDisplayValue(
expectedOrder.price
);
expect(screen.getByTestId('post-only')).toBeDisabled();
expect(screen.getByTestId('reduce-only')).toBeEnabled();
expect(screen.getByTestId('reduce-only')).not.toBeChecked();
expect(screen.getByTestId('post-only')).not.toBeChecked();
expect(screen.getByTestId('iceberg')).not.toBeChecked();
});
it('handles TIF select box dependent on order type', async () => {
render(generateJsx());
@@ -54,6 +54,7 @@ import {
import { OrderTimeInForce, OrderType } from '@vegaprotocol/types';
import { useOrderForm } from '../../hooks/use-order-form';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { DealTicketSizeIceberg } from './deal-ticket-size-iceberg';
export interface DealTicketProps {
market: Market;
@@ -292,6 +293,22 @@ export const DealTicket = ({
timeInForce: lastTIF[type] || order.timeInForce,
postOnly:
type === OrderType.TYPE_MARKET ? false : order.postOnly,
iceberg:
type === OrderType.TYPE_MARKET ||
[
OrderTimeInForce.TIME_IN_FORCE_FOK,
OrderTimeInForce.TIME_IN_FORCE_IOC,
].includes(lastTIF[type] || order.timeInForce)
? false
: order.iceberg,
icebergOpts:
type === OrderType.TYPE_MARKET ||
[
OrderTimeInForce.TIME_IN_FORCE_FOK,
OrderTimeInForce.TIME_IN_FORCE_IOC,
].includes(lastTIF[type] || order.timeInForce)
? undefined
: order.icebergOpts,
reduceOnly:
type === OrderType.TYPE_LIMIT &&
![
@@ -463,6 +480,51 @@ export const DealTicket = ({
)}
/>
</div>
<div className="flex gap-2 pb-2 justify-between">
{order.type === Schema.OrderType.TYPE_LIMIT && (
<Controller
name="iceberg"
control={control}
render={() => (
<Checkbox
name="iceberg"
checked={order.iceberg}
onCheckedChange={() => {
update({ iceberg: !order.iceberg, icebergOpts: undefined });
}}
label={
<Tooltip
description={
<p>
{t(`Trade only a fraction of the order size at once.
After the peak size of the order has traded, the size is reset. This is repeated until the order is cancelled, expires, or its full volume trades away.
For example, an iceberg order with a size of 1000 and a peak size of 100 will effectively be split into 10 orders with a size of 100 each.
Note that the full volume of the order is not hidden and is still reflected in the order book.`)}
</p>
}
>
<span className="text-xs">{t('Iceberg')}</span>
</Tooltip>
}
/>
)}
/>
)}
</div>
{order.iceberg && (
<DealTicketSizeIceberg
update={update}
market={market}
peakSizeError={errors.icebergOpts?.peakSize?.message}
minimumVisibleSizeError={
errors.icebergOpts?.minimumVisibleSize?.message
}
control={control}
size={order.size}
peakSize={order.icebergOpts?.peakSize || ''}
minimumVisibleSize={order.icebergOpts?.minimumVisibleSize || ''}
/>
)}
<SummaryMessage
errorMessage={errors.summary?.message}
asset={asset}
+3 -6
View File
@@ -4,7 +4,6 @@ import { getDefaultOrder, useOrder } from '@vegaprotocol/orders';
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import type { Exact } from 'type-fest';
export type OrderFormFields = OrderObj & {
summary: string;
@@ -51,13 +50,11 @@ export const useOrderForm = (marketId: string) => {
}
}, [order, isSubmitted, getValues, setValue]);
const handleSubmitWrapper = (
cb: <T>(o: Exact<OrderSubmission, T>) => void
) => {
const handleSubmitWrapper = (cb: (o: OrderSubmission) => void) => {
return handleSubmit(() => {
// remove the persist key from the order in the store, the wallet will reject
// remove the persist and iceberg key from the order in the store, the wallet will reject
// an order that contains unrecognized additional keys
cb(omit(order, 'persist'));
cb(omit(order, 'persist', 'iceberg'));
});
};
@@ -163,6 +163,7 @@ describe('Network switcher', () => {
[Networks.MAINNET]: 'https://main.net',
[Networks.TESTNET]: 'https://test.net',
[Networks.VALIDATOR_TESTNET]: 'https://validator-test.net',
[Networks.MAINNET_MIRROR]: 'https://mainnet-mirror.net',
[Networks.DEVNET]: 'https://dev.net',
[Networks.STAGNET1]: 'https://stag1.net',
};
@@ -209,6 +210,7 @@ describe('Network switcher', () => {
[Networks.CUSTOM]: undefined,
[Networks.MAINNET]: 'https://main.net',
[Networks.VALIDATOR_TESTNET]: 'https://validator-test.net',
[Networks.MAINNET_MIRROR]: 'https://mainnet-mirror.net',
[Networks.TESTNET]: 'https://test.net',
[Networks.DEVNET]: 'https://dev.net',
[Networks.STAGNET1]: 'https://stag1.net',
@@ -240,6 +242,7 @@ describe('Network switcher', () => {
[Networks.CUSTOM]: undefined,
[Networks.MAINNET]: undefined,
[Networks.VALIDATOR_TESTNET]: 'https://validator-test.net',
[Networks.MAINNET_MIRROR]: 'https://mainnet-mirror.net',
[Networks.TESTNET]: 'https://test.net',
[Networks.DEVNET]: 'https://dev.net',
[Networks.STAGNET1]: 'https://stag1.net',
@@ -16,6 +16,7 @@ import classNames from 'classnames';
export const envNameMapping: Record<Networks, string> = {
[Networks.VALIDATOR_TESTNET]: t('VALIDATOR_TESTNET'),
[Networks.MAINNET_MIRROR]: t('Mainnet-mirror'),
[Networks.CUSTOM]: t('Custom'),
[Networks.DEVNET]: t('Devnet'),
[Networks.STAGNET1]: t('Stagnet'),
@@ -31,6 +32,7 @@ export const envTriggerMapping: Record<Networks, string> = {
export const envDescriptionMapping: Record<Networks, string> = {
[Networks.CUSTOM]: '',
[Networks.VALIDATOR_TESTNET]: t('The validator deployed testnet'),
[Networks.MAINNET_MIRROR]: t('The mainnet-mirror network'),
[Networks.DEVNET]: t('The latest Vega code auto-deployed'),
[Networks.STAGNET1]: t('A release candidate for the staging environment'),
[Networks.TESTNET]: t(
+4
View File
@@ -20,6 +20,7 @@ type DAppLinks = {
const EmptyLinks: DAppLinks = {
[Networks.VALIDATOR_TESTNET]: '',
[Networks.MAINNET_MIRROR]: '',
[Networks.DEVNET]: '',
[Networks.STAGNET1]: '',
[Networks.TESTNET]: '',
@@ -31,6 +32,7 @@ const ExplorerLinks = {
[Networks.TESTNET]: 'https://explorer.fairground.wtf',
[Networks.VALIDATOR_TESTNET]:
'https://explorer.validators-testnet.vega.rocks',
[Networks.MAINNET_MIRROR]: 'https://explorer.mainnet-mirror.vega.rocks/',
[Networks.MAINNET]: 'https://explorer.vega.xyz',
};
@@ -39,6 +41,7 @@ const ConsoleLinks = {
[Networks.STAGNET1]: 'https://trading.stagnet1.vega.rocks',
[Networks.TESTNET]: 'https://console.fairground.wtf',
[Networks.MAINNET]: 'https://console.vega.xyz',
[Networks.MAINNET_MIRROR]: 'https://console.mainnet-mirror.vega.rocks/',
};
const TokenLinks = {
@@ -47,6 +50,7 @@ const TokenLinks = {
[Networks.TESTNET]: 'https://governance.fairground.wtf',
[Networks.VALIDATOR_TESTNET]:
'https://governance.validators-testnet.vega.rocks',
[Networks.MAINNET_MIRROR]: 'https://governance.mainnet-mirror.vega.rocks/',
[Networks.MAINNET]: 'https://governance.vega.xyz',
};
+1
View File
@@ -4,6 +4,7 @@ import type { envSchema } from './utils/validate-environment';
export enum Networks {
VALIDATOR_TESTNET = 'VALIDATOR_TESTNET',
MAINNET_MIRROR = 'MAINNET_MIRROR',
CUSTOM = 'CUSTOM',
TESTNET = 'TESTNET',
STAGNET1 = 'STAGNET1',
@@ -2,6 +2,7 @@ import z from 'zod';
export enum Networks {
VALIDATOR_TESTNET = 'VALIDATOR_TESTNET',
MAINNET_MIRROR = 'MAINNET_MIRROR',
CUSTOM = 'CUSTOM',
TESTNET = 'TESTNET',
STAGNET1 = 'STAGNET1',
+4 -4
View File
@@ -3,14 +3,14 @@ import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type LiquidityProvisionFieldsFragment = { __typename?: 'LiquidityProvision', id?: string | null, createdAt: any, updatedAt?: any | null, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus, party: { __typename?: 'Party', id: string, accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string } } | null> | null } | null } };
export type LiquidityProvisionFieldsFragment = { __typename?: 'LiquidityProvision', id: string, createdAt: any, updatedAt?: any | null, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus, party: { __typename?: 'Party', id: string, accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string } } | null> | null } | null } };
export type LiquidityProvisionsQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type LiquidityProvisionsQuery = { __typename?: 'Query', market?: { __typename?: 'Market', liquidityProvisionsConnection?: { __typename?: 'LiquidityProvisionsConnection', edges?: Array<{ __typename?: 'LiquidityProvisionsEdge', node: { __typename?: 'LiquidityProvision', id?: string | null, createdAt: any, updatedAt?: any | null, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus, party: { __typename?: 'Party', id: string, accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string } } | null> | null } | null } } } | null> | null } | null } | null };
export type LiquidityProvisionsQuery = { __typename?: 'Query', market?: { __typename?: 'Market', liquidityProvisionsConnection?: { __typename?: 'LiquidityProvisionsConnection', edges?: Array<{ __typename?: 'LiquidityProvisionsEdge', node: { __typename?: 'LiquidityProvision', id: string, createdAt: any, updatedAt?: any | null, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus, party: { __typename?: 'Party', id: string, accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string } } | null> | null } | null } } } | null> | null } | null } | null };
export type LiquidityProvisionsUpdateSubscriptionVariables = Types.Exact<{
partyId?: Types.InputMaybe<Types.Scalars['ID']>;
@@ -18,7 +18,7 @@ export type LiquidityProvisionsUpdateSubscriptionVariables = Types.Exact<{
}>;
export type LiquidityProvisionsUpdateSubscription = { __typename?: 'Subscription', liquidityProvisions?: Array<{ __typename?: 'LiquidityProvisionUpdate', id?: string | null, partyID: string, createdAt: any, updatedAt?: any | null, marketID: string, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus }> | null };
export type LiquidityProvisionsUpdateSubscription = { __typename?: 'Subscription', liquidityProvisions?: Array<{ __typename?: 'LiquidityProvisionUpdate', id: string, partyID: string, createdAt: any, updatedAt?: any | null, marketID: string, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus }> | null };
export type LiquidityProviderFeeShareFieldsFragment = { __typename?: 'LiquidityProviderFeeShare', equityLikeShare: string, averageEntryValuation: string, party: { __typename?: 'Party', id: string } };
@@ -180,4 +180,4 @@ export function useLiquidityProviderFeeShareLazyQuery(baseOptions?: Apollo.LazyQ
}
export type LiquidityProviderFeeShareQueryHookResult = ReturnType<typeof useLiquidityProviderFeeShareQuery>;
export type LiquidityProviderFeeShareLazyQueryHookResult = ReturnType<typeof useLiquidityProviderFeeShareLazyQuery>;
export type LiquidityProviderFeeShareQueryResult = Apollo.QueryResult<LiquidityProviderFeeShareQuery, LiquidityProviderFeeShareQueryVariables>;
export type LiquidityProviderFeeShareQueryResult = Apollo.QueryResult<LiquidityProviderFeeShareQuery, LiquidityProviderFeeShareQueryVariables>;
@@ -66,10 +66,13 @@ export const OrderbookManager = ({ marketId }: OrderbookManagerProps) => {
decimalPlaces={market?.decimalPlaces ?? 0}
positionDecimalPlaces={market?.positionDecimalPlaces ?? 0}
assetSymbol={market?.tradableInstrument.instrument.product.quoteName}
onClick={(price: string) => {
onClick={({ price, size }) => {
if (price) {
updateOrder(marketId, { price });
}
if (size) {
updateOrder(marketId, { size });
}
}}
midPrice={marketData?.midPrice}
/>
+59 -19
View File
@@ -11,10 +11,14 @@ interface OrderbookRowProps {
decimalPlaces: number;
positionDecimalPlaces: number;
price: string;
onClick?: (price: string) => void;
onClick?: (args: { price?: string; size?: string }) => void;
type: VolumeType;
width: number;
}
const HIDE_VOL_WIDTH = 150;
const HIDE_CUMULATIVE_VOL_WIDTH = 220;
const CumulationBar = ({
cumulativeValue = 0,
type,
@@ -26,7 +30,7 @@ const CumulationBar = ({
<div
data-testid={`${VolumeType.bid === type ? 'bid' : 'ask'}-bar`}
className={classNames(
'absolute top-0 left-0 h-full transition-all',
'absolute top-0 left-0 h-full',
type === VolumeType.bid
? 'bg-market-green-300 dark:bg-market-green/50'
: 'bg-market-red-300 dark:bg-market-red/30'
@@ -43,6 +47,7 @@ const CumulativeVol = memo(
testId,
positionDecimalPlaces,
cumulativeValue,
onClick,
}: {
ask?: number;
bid?: number;
@@ -50,6 +55,7 @@ const CumulativeVol = memo(
testId?: string;
className?: string;
positionDecimalPlaces: number;
onClick?: (size?: string | number) => void;
}) => {
const volume = cumulativeValue ? (
<NumericCell
@@ -61,7 +67,15 @@ const CumulativeVol = memo(
/>
) : null;
return (
return onClick && volume ? (
<button
data-testid={testId}
onClick={() => onClick(cumulativeValue)}
className="hover:dark:bg-neutral-800 hover:bg-neutral-200 text-right pr-1"
>
{volume}
</button>
) : (
<div className="pr-1" data-testid={testId}>
{volume}
</div>
@@ -80,16 +94,24 @@ export const OrderbookRow = React.memo(
price,
onClick,
type,
width,
}: OrderbookRowProps) => {
const txtId = type === VolumeType.bid ? 'bid' : 'ask';
const cols =
width >= HIDE_CUMULATIVE_VOL_WIDTH ? 3 : width >= HIDE_VOL_WIDTH ? 2 : 1;
return (
<div className="relative">
<div className="relative pr-1">
<CumulationBar cumulativeValue={cumulativeRelativeValue} type={type} />
<div className="grid gap-1 text-right grid-cols-3">
<div
data-testid={`${txtId}-rows-container`}
className={classNames('grid gap-1 text-right', `grid-cols-${cols}`)}
>
<PriceCell
testId={`price-${price}`}
value={BigInt(price)}
onClick={() => onClick && onClick(addDecimal(price, decimalPlaces))}
onClick={() =>
onClick && onClick({ price: addDecimal(price, decimalPlaces) })
}
valueFormatted={addDecimalsFixedFormatNumber(price, decimalPlaces)}
className={
type === VolumeType.ask
@@ -97,19 +119,37 @@ export const OrderbookRow = React.memo(
: 'text-market-green-600 dark:text-market-green'
}
/>
<NumericCell
testId={`${txtId}-vol-${price}`}
value={value}
valueFormatted={addDecimalsFixedFormatNumber(
value,
positionDecimalPlaces
)}
/>
<CumulativeVol
testId={`cumulative-vol-${price}`}
positionDecimalPlaces={positionDecimalPlaces}
cumulativeValue={cumulativeValue}
/>
{width >= HIDE_VOL_WIDTH && (
<PriceCell
testId={`${txtId}-vol-${price}`}
onClick={(value) =>
onClick &&
value &&
onClick({
size: addDecimal(value, positionDecimalPlaces),
})
}
value={value}
valueFormatted={addDecimalsFixedFormatNumber(
value,
positionDecimalPlaces
)}
/>
)}
{width >= HIDE_CUMULATIVE_VOL_WIDTH && (
<CumulativeVol
testId={`cumulative-vol-${price}`}
onClick={() =>
onClick &&
cumulativeValue &&
onClick({
size: addDecimal(cumulativeValue, positionDecimalPlaces),
})
}
positionDecimalPlaces={positionDecimalPlaces}
cumulativeValue={cumulativeValue}
/>
)}
</div>
</div>
);
+97 -9
View File
@@ -1,4 +1,5 @@
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
import { render, waitFor, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { generateMockData, VolumeType } from './orderbook-data';
import { Orderbook } from './orderbook';
import * as orderbookData from './orderbook-data';
@@ -33,6 +34,7 @@ describe('Orderbook', () => {
const decimalPlaces = 3;
beforeEach(() => {
jest.clearAllMocks();
mockOffsetSize(800, 768);
});
it('markPrice should be in the middle', async () => {
@@ -69,12 +71,17 @@ describe('Orderbook', () => {
await screen.findByTestId(`middle-mark-price-${params.midPrice}`)
).toBeInTheDocument();
// Before resolution change the price is 122.934
await fireEvent.click(await screen.getByTestId('price-122901'));
expect(onClickSpy).toBeCalledWith('122.901');
const resolutionSelect = screen.getByTestId(
'resolution'
) as HTMLSelectElement;
await fireEvent.change(resolutionSelect, { target: { value: '10' } });
await userEvent.click(await screen.getByTestId('price-122901'));
expect(onClickSpy).toBeCalledWith({ price: '122.901' });
await userEvent.click(screen.getByTestId('resolution'));
await waitFor(() => {
expect(screen.getByRole('menu')).toBeInTheDocument();
});
await userEvent.click(screen.getAllByRole('menuitem')[1]);
expect(orderbookData.compactRows).toHaveBeenCalledWith(
mockedData.bids,
VolumeType.bid,
@@ -85,7 +92,88 @@ describe('Orderbook', () => {
VolumeType.ask,
10
);
await fireEvent.click(await screen.getByTestId('price-12294'));
expect(onClickSpy).toBeCalledWith('122.94');
await userEvent.click(await screen.getByTestId('price-12294'));
expect(onClickSpy).toBeCalledWith({ price: '122.94' });
});
it('plus - minus buttons should change resolution', async () => {
const onClickSpy = jest.fn();
jest.spyOn(orderbookData, 'compactRows');
const mockedData = generateMockData(params);
render(
<Orderbook
decimalPlaces={decimalPlaces}
positionDecimalPlaces={0}
onClick={onClickSpy}
{...mockedData}
assetSymbol="USD"
/>
);
expect((orderbookData.compactRows as jest.Mock).mock.lastCall[2]).toEqual(
1
);
expect(screen.getByTestId('minus-button')).toBeDisabled();
userEvent.click(screen.getByTestId('plus-button'));
await waitFor(() => {
expect((orderbookData.compactRows as jest.Mock).mock.lastCall[2]).toEqual(
10
);
});
expect(screen.getByTestId('minus-button')).not.toBeDisabled();
userEvent.click(screen.getByTestId('minus-button'));
await waitFor(() => {
expect((orderbookData.compactRows as jest.Mock).mock.lastCall[2]).toEqual(
1
);
});
expect(screen.getByTestId('minus-button')).toBeDisabled();
await userEvent.click(screen.getByTestId('resolution'));
await waitFor(() => {
expect(screen.getByRole('menu')).toBeInTheDocument();
});
await userEvent.click(screen.getAllByRole('menuitem')[5]);
await waitFor(() => {
expect((orderbookData.compactRows as jest.Mock).mock.lastCall[2]).toEqual(
100000
);
});
expect(screen.getByTestId('plus-button')).toBeDisabled();
});
it('two columns', () => {
mockOffsetSize(200, 768);
const onClickSpy = jest.fn();
const mockedData = generateMockData(params);
render(
<Orderbook
decimalPlaces={decimalPlaces}
positionDecimalPlaces={0}
onClick={onClickSpy}
{...mockedData}
assetSymbol="USD"
/>
);
screen.getAllByTestId('bid-rows-container').forEach((item) => {
expect(item).toHaveClass('grid-cols-2');
});
});
it('one column', () => {
mockOffsetSize(140, 768);
const onClickSpy = jest.fn();
const mockedData = generateMockData(params);
render(
<Orderbook
decimalPlaces={decimalPlaces}
positionDecimalPlaces={0}
onClick={onClickSpy}
{...mockedData}
assetSymbol="USD"
/>
);
screen.getAllByTestId('ask-rows-container').forEach((item) => {
expect(item).toHaveClass('grid-cols-1');
});
});
});
+128 -26
View File
@@ -1,16 +1,25 @@
import { useMemo } from 'react';
import { useMemo, useRef, useState } from 'react';
import ReactVirtualizedAutoSizer from 'react-virtualized-auto-sizer';
import {
addDecimalsFormatNumber,
formatNumberFixed,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { usePrevious } from '@vegaprotocol/react-helpers';
import { OrderbookRow } from './orderbook-row';
import type { OrderbookRowData } from './orderbook-data';
import { compactRows, VolumeType } from './orderbook-data';
import { Splash } from '@vegaprotocol/ui-toolkit';
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
Splash,
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import classNames from 'classnames';
import { useState } from 'react';
import type { PriceLevelFieldsFragment } from './__generated__/MarketDepth';
// Sets row height, will be used to calculate number of rows that can be
@@ -19,6 +28,19 @@ export const rowHeight = 17;
const rowGap = 1;
const midHeight = 30;
type PriceChange = 'up' | 'down' | 'none';
const PRICE_CHANGE_ICON_MAP: Readonly<Record<PriceChange, VegaIconNames>> = {
up: VegaIconNames.ARROW_UP,
down: VegaIconNames.ARROW_DOWN,
none: VegaIconNames.BULLET,
};
const PRICE_CHANGE_CLASS_MAP: Readonly<Record<PriceChange, string>> = {
up: 'text-market-green-600 dark:text-market-green',
down: 'text-market-red dark:text-market-red',
none: 'text-vega-blue-500',
};
const OrderbookTable = ({
rows,
resolution,
@@ -26,13 +48,15 @@ const OrderbookTable = ({
decimalPlaces,
positionDecimalPlaces,
onClick,
width,
}: {
rows: OrderbookRowData[];
resolution: number;
decimalPlaces: number;
positionDecimalPlaces: number;
type: VolumeType;
onClick?: (price: string) => void;
onClick?: (args: { price?: string; size?: string }) => void;
width: number;
}) => {
return (
<div
@@ -59,6 +83,7 @@ const OrderbookTable = ({
cumulativeValue={data.cumulativeVol.value}
cumulativeRelativeValue={data.cumulativeVol.relativeValue}
type={type}
width={width}
/>
))}
</div>
@@ -69,7 +94,7 @@ const OrderbookTable = ({
interface OrderbookProps {
decimalPlaces: number;
positionDecimalPlaces: number;
onClick?: (price: string) => void;
onClick?: (args: { price?: string; size?: string }) => void;
midPrice?: string;
bids: PriceLevelFieldsFragment[];
asks: PriceLevelFieldsFragment[];
@@ -99,12 +124,50 @@ export const Orderbook = ({
const groupedBids = useMemo(() => {
return compactRows(bids, VolumeType.bid, resolution);
}, [bids, resolution]);
const [isOpen, setOpen] = useState(false);
const previousMidPrice = usePrevious(midPrice);
const priceChangeRef = useRef<'up' | 'down' | 'none'>('none');
if (midPrice && previousMidPrice !== midPrice) {
priceChangeRef.current =
(previousMidPrice || '') > midPrice ? 'down' : 'up';
}
const priceChangeIcon = (
<span
className={classNames(PRICE_CHANGE_CLASS_MAP[priceChangeRef.current])}
>
<VegaIcon name={PRICE_CHANGE_ICON_MAP[priceChangeRef.current]} />
</span>
);
const formatResolution = (r: number) => {
return formatNumberFixed(
Math.log10(r) - decimalPlaces > 0
? Math.pow(10, Math.log10(r) - decimalPlaces)
: 0,
decimalPlaces - Math.log10(r)
);
};
const increaseResolution = () => {
const index = resolutions.indexOf(resolution);
if (index < resolutions.length - 1) {
setResolution(resolutions[index + 1]);
}
};
const decreaseResolution = () => {
const index = resolutions.indexOf(resolution);
if (index > 0) {
setResolution(resolutions[index - 1]);
}
};
return (
<div className="h-full pl-1 text-xs grid grid-rows-[1fr_min-content]">
<div>
<ReactVirtualizedAutoSizer disableWidth>
{({ height }) => {
<ReactVirtualizedAutoSizer>
{({ width, height }) => {
const limit = Math.max(
1,
Math.floor((height - midHeight) / 2 / (rowHeight + rowGap))
@@ -116,6 +179,7 @@ export const Orderbook = ({
className="overflow-hidden grid"
data-testid="orderbook-grid-element"
style={{
width: width + 'px',
height: height + 'px',
gridTemplateRows: `1fr ${midHeight}px 1fr`, // cannot use tailwind here as tailwind will not parse a class string with interpolation
}}
@@ -129,6 +193,7 @@ export const Orderbook = ({
decimalPlaces={decimalPlaces}
positionDecimalPlaces={positionDecimalPlaces}
onClick={onClick}
width={width}
/>
<div className="flex items-center justify-center gap-2">
{midPrice && (
@@ -140,6 +205,7 @@ export const Orderbook = ({
{addDecimalsFormatNumber(midPrice, decimalPlaces)}
</span>
<span className="text-base">{assetSymbol}</span>
{priceChangeIcon}
</>
)}
</div>
@@ -150,6 +216,7 @@ export const Orderbook = ({
decimalPlaces={decimalPlaces}
positionDecimalPlaces={positionDecimalPlaces}
onClick={onClick}
width={width}
/>
</>
) : (
@@ -162,26 +229,61 @@ export const Orderbook = ({
}}
</ReactVirtualizedAutoSizer>
</div>
<div className="border-t border-default">
<select
onChange={(e) => {
setResolution(Number(e.currentTarget.value));
}}
value={resolution}
className="block bg-neutral-100 dark:bg-neutral-700 font-mono text-right"
data-testid="resolution"
<div className="border-t border-default flex">
<Button
onClick={increaseResolution}
size="xs"
disabled={resolutions.indexOf(resolution) >= resolutions.length - 1}
className="text-black dark:text-white rounded-none border-y-0 border-l-0 flex items-center border-r-1"
data-testid="plus-button"
>
{resolutions.map((r) => (
<option key={r} value={r}>
{formatNumberFixed(
Math.log10(r) - decimalPlaces > 0
? Math.pow(10, Math.log10(r) - decimalPlaces)
: 0,
decimalPlaces - Math.log10(r)
)}
</option>
))}
</select>
<VegaIcon size={12} name={VegaIconNames.PLUS} />
</Button>
<DropdownMenu
open={isOpen}
onOpenChange={(open) => setOpen(open)}
trigger={
<DropdownMenuTrigger
data-testid="resolution"
className="flex justify-between px-1 items-center"
style={{
width: `${
Math.max.apply(
null,
resolutions.map((item) => formatResolution(item).length)
) + 3
}ch`,
}}
>
<VegaIcon
size={12}
name={
isOpen ? VegaIconNames.CHEVRON_UP : VegaIconNames.CHEVRON_DOWN
}
/>
<div className="text-xs text-left">
{formatResolution(resolution)}
</div>
</DropdownMenuTrigger>
}
>
<DropdownMenuContent align="start">
{resolutions.map((r) => (
<DropdownMenuItem key={r} onClick={() => setResolution(r)}>
{formatResolution(r)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<Button
onClick={decreaseResolution}
size="xs"
disabled={resolutions.indexOf(resolution) <= 0}
className="text-black dark:text-white rounded-none border-y-0 border-l-1 flex items-center"
data-testid="minus-button"
>
<VegaIcon size={12} name={VegaIconNames.MINUS} />
</Button>
</div>
</div>
);
@@ -16,6 +16,16 @@ fragment DataSource on DataSourceDefinition {
}
}
}
... on DataSourceDefinitionInternal {
sourceType {
... on DataSourceSpecConfigurationTime {
conditions {
operator
value
}
}
}
}
}
}
@@ -3,14 +3,14 @@ import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type DataSourceFragment = { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null } } | { __typename?: 'DataSourceDefinitionInternal' } };
export type DataSourceFragment = { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', operator: Types.ConditionOperator, value?: string | null } | null> } } };
export type MarketInfoQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type MarketInfoQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, lpPriceRange: string, parentMarketID?: string | null, proposal?: { __typename?: 'Proposal', id?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string } } | null, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any }, openingAuction: { __typename?: 'AuctionDuration', durationSecs: number, volume: number }, accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string, asset: { __typename?: 'Asset', id: string } } } | null> | null } | null, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, priceMonitoringSettings: { __typename?: 'PriceMonitoringSettings', parameters?: { __typename?: 'PriceMonitoringParameters', triggers?: Array<{ __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number }> | null } | null }, riskFactors?: { __typename?: 'RiskFactor', market: string, short: string, long: string } | null, liquidityMonitoringParameters: { __typename?: 'LiquidityMonitoringParameters', triggeringRatio: string, targetStakeParameters: { __typename?: 'TargetStakeParameters', timeWindow: number, scalingFactor: number } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForSettlementData: { __typename?: 'DataSourceSpec', id: string, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null } } | { __typename?: 'DataSourceDefinitionInternal' } } }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null } } | { __typename?: 'DataSourceDefinitionInternal' } } }, dataSourceSpecBinding: { __typename?: 'DataSourceSpecToFutureBinding', settlementDataProperty: string, tradingTerminationProperty: string } } }, riskModel: { __typename?: 'LogNormalRiskModel', tau: number, riskAversionParameter: number, params: { __typename?: 'LogNormalModelParams', r: number, sigma: number, mu: number } } | { __typename?: 'SimpleRiskModel', params: { __typename?: 'SimpleRiskModelParams', factorLong: number, factorShort: number } }, marginCalculator?: { __typename?: 'MarginCalculator', scalingFactors: { __typename?: 'ScalingFactors', searchLevel: number, initialMargin: number, collateralRelease: number } } | null } } | null };
export type MarketInfoQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, lpPriceRange: string, parentMarketID?: string | null, proposal?: { __typename?: 'Proposal', id?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string } } | null, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any }, openingAuction: { __typename?: 'AuctionDuration', durationSecs: number, volume: number }, accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string, asset: { __typename?: 'Asset', id: string } } } | null> | null } | null, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, priceMonitoringSettings: { __typename?: 'PriceMonitoringSettings', parameters?: { __typename?: 'PriceMonitoringParameters', triggers?: Array<{ __typename?: 'PriceMonitoringTrigger', horizonSecs: number, probability: number, auctionExtensionSecs: number }> | null } | null }, riskFactors?: { __typename?: 'RiskFactor', market: string, short: string, long: string } | null, liquidityMonitoringParameters: { __typename?: 'LiquidityMonitoringParameters', triggeringRatio: string, targetStakeParameters: { __typename?: 'TargetStakeParameters', timeWindow: number, scalingFactor: number } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForSettlementData: { __typename?: 'DataSourceSpec', id: string, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', operator: Types.ConditionOperator, value?: string | null } | null> } } } }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', operator: Types.ConditionOperator, value?: string | null } | null> } } } }, dataSourceSpecBinding: { __typename?: 'DataSourceSpecToFutureBinding', settlementDataProperty: string, tradingTerminationProperty: string } } }, riskModel: { __typename?: 'LogNormalRiskModel', tau: number, riskAversionParameter: number, params: { __typename?: 'LogNormalModelParams', r: number, sigma: number, mu: number } } | { __typename?: 'SimpleRiskModel', params: { __typename?: 'SimpleRiskModelParams', factorLong: number, factorShort: number } }, marginCalculator?: { __typename?: 'MarginCalculator', scalingFactors: { __typename?: 'ScalingFactors', searchLevel: number, initialMargin: number, collateralRelease: number } } | null } } | null };
export const DataSourceFragmentDoc = gql`
fragment DataSource on DataSourceDefinition {
@@ -31,6 +31,16 @@ export const DataSourceFragmentDoc = gql`
}
}
}
... on DataSourceDefinitionInternal {
sourceType {
... on DataSourceSpecConfigurationTime {
conditions {
operator
value
}
}
}
}
}
}
`;
@@ -129,6 +129,7 @@ export const MarketInfoAccordion = ({
.filter((a) => a.type === Schema.AccountType.ACCOUNT_TYPE_INSURANCE)
.map((a) => (
<AccordionItem
key={`${a.type}:${a.asset.id}`}
itemId={`${a.type}:${a.asset.id}`}
title={t('Insurance pool')}
content={<InsurancePoolInfoPanel market={market} account={a} />}
@@ -203,6 +204,7 @@ export const MarketInfoAccordion = ({
{(market.priceMonitoringSettings?.parameters?.triggers || []).map(
(_, triggerIndex) => (
<AccordionItem
key={`trigger-${triggerIndex}`}
itemId={`trigger-${triggerIndex}`}
title={t(`Price monitoring bounds ${triggerIndex + 1}`)}
content={
+1
View File
@@ -141,6 +141,7 @@ export const createMarketFragment = (
},
__typename: 'TradableInstrument',
},
successorMarketID: null,
__typename: 'Market',
};
@@ -24,6 +24,12 @@ fragment OrderFields on Order {
reference
offset
}
icebergOrder {
__typename
peakSize
minimumVisibleSize
reservedRemaining
}
}
query OrderById($orderId: ID!) {
@@ -66,7 +72,6 @@ fragment OrderUpdateFields on OrderUpdate {
type
side
size
remaining
status
rejectionReason
price
@@ -81,6 +86,12 @@ fragment OrderUpdateFields on OrderUpdate {
reference
offset
}
icebergOrder {
__typename
peakSize
minimumVisibleSize
reservedRemaining
}
}
subscription OrdersUpdate($partyId: ID!, $marketIds: [ID!]) {
@@ -3,14 +3,14 @@ import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type OrderFieldsFragment = { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null };
export type OrderFieldsFragment = { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null };
export type OrderByIdQueryVariables = Types.Exact<{
orderId: Types.Scalars['ID'];
}>;
export type OrderByIdQuery = { __typename?: 'Query', orderByID: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null } };
export type OrderByIdQuery = { __typename?: 'Query', orderByID: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null } };
export type OrdersQueryVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
@@ -20,9 +20,9 @@ export type OrdersQueryVariables = Types.Exact<{
}>;
export type OrdersQuery = { __typename?: 'Query', party?: { __typename?: 'Party', id: string, ordersConnection?: { __typename?: 'OrderConnection', edges?: Array<{ __typename?: 'OrderEdge', cursor?: string | null, node: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null } }> | null, pageInfo?: { __typename?: 'PageInfo', startCursor: string, endCursor: string, hasNextPage: boolean, hasPreviousPage: boolean } | null } | null } | null };
export type OrdersQuery = { __typename?: 'Query', party?: { __typename?: 'Party', id: string, ordersConnection?: { __typename?: 'OrderConnection', edges?: Array<{ __typename?: 'OrderEdge', cursor?: string | null, node: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null } }> | null, pageInfo?: { __typename?: 'PageInfo', startCursor: string, endCursor: string, hasNextPage: boolean, hasPreviousPage: boolean } | null } | null } | null };
export type OrderUpdateFieldsFragment = { __typename?: 'OrderUpdate', id: string, marketId: string, type?: Types.OrderType | null, side: Types.Side, size: string, remaining: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, liquidityProvisionId?: string | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null };
export type OrderUpdateFieldsFragment = { __typename?: 'OrderUpdate', id: string, marketId: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, liquidityProvisionId?: string | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null };
export type OrdersUpdateSubscriptionVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
@@ -30,7 +30,7 @@ export type OrdersUpdateSubscriptionVariables = Types.Exact<{
}>;
export type OrdersUpdateSubscription = { __typename?: 'Subscription', orders?: Array<{ __typename?: 'OrderUpdate', id: string, marketId: string, type?: Types.OrderType | null, side: Types.Side, size: string, remaining: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, liquidityProvisionId?: string | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null }> | null };
export type OrdersUpdateSubscription = { __typename?: 'Subscription', orders?: Array<{ __typename?: 'OrderUpdate', id: string, marketId: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, liquidityProvisionId?: string | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null }> | null };
export const OrderFieldsFragmentDoc = gql`
fragment OrderFields on Order {
@@ -59,6 +59,12 @@ export const OrderFieldsFragmentDoc = gql`
reference
offset
}
icebergOrder {
__typename
peakSize
minimumVisibleSize
reservedRemaining
}
}
`;
export const OrderUpdateFieldsFragmentDoc = gql`
@@ -68,7 +74,6 @@ export const OrderUpdateFieldsFragmentDoc = gql`
type
side
size
remaining
status
rejectionReason
price
@@ -83,6 +88,12 @@ export const OrderUpdateFieldsFragmentDoc = gql`
reference
offset
}
icebergOrder {
__typename
peakSize
minimumVisibleSize
reservedRemaining
}
}
`;
export const OrderByIdDocument = gql`
@@ -63,6 +63,11 @@ export const mapOrderUpdateToOrder = (
return {
...order,
liquidityProvision: liquidityProvision,
icebergOrder: order.icebergOrder
? {
...order.icebergOrder,
}
: undefined,
market: {
__typename: 'Market',
id: marketId,
@@ -267,12 +267,14 @@ export const OrderListTable = memo<
<div className="flex gap-2 items-center justify-end">
{isOrderAmendable(data) && !props.isReadOnly && (
<>
<ButtonLink
data-testid="edit"
onClick={() => onEdit(data)}
>
{t('Edit')}
</ButtonLink>
{!data.icebergOrder && (
<ButtonLink
data-testid="edit"
onClick={() => onEdit(data)}
>
{t('Edit')}
</ButtonLink>
)}
<ButtonLink
data-testid="cancel"
onClick={() => onCancel(data)}
@@ -16,7 +16,13 @@ export type OrderObj = {
persist: boolean; // key used to determine if order should be kept in localStorage
postOnly?: boolean;
reduceOnly?: boolean;
iceberg?: boolean;
icebergOpts?: {
peakSize: string;
minimumVisibleSize: string;
};
};
type OrderMap = { [marketId: string]: OrderObj | undefined };
type UpdateOrder = (
@@ -6,6 +6,7 @@ import type { Position } from './positions-data-providers';
import * as Schema from '@vegaprotocol/types';
import { PositionStatus, PositionStatusMapping } from '@vegaprotocol/types';
import type { ICellRendererParams } from 'ag-grid-community';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
jest.mock('./liquidation-price', () => ({
LiquidationPrice: () => (
@@ -19,7 +20,7 @@ const singleRow: Position = {
assetSymbol: 'BTC',
averageEntryPrice: '133',
currentLeverage: 1.1,
decimals: 2,
decimals: 2, // this is settlementAsset.decimals
quantum: '0.1',
lossSocializationAmount: '0',
marginAccountBalance: '12345600',
@@ -177,12 +178,23 @@ it('displays allocated margin', async () => {
});
it('displays realised and unrealised PNL', async () => {
// pnl cells should be rendered with asset dps
const expectedRealised = addDecimalsFormatNumber(
singleRow.realisedPNL,
singleRow.decimals
);
const expectedUnrealised = addDecimalsFormatNumber(
singleRow.unrealisedPNL,
singleRow.decimals
);
await act(async () => {
render(<PositionsTable rowData={singleRowData} isReadOnly={false} />);
});
const cells = screen.getAllByRole('gridcell');
expect(cells[9].textContent).toEqual('12.3');
expect(cells[10].textContent).toEqual('45.6');
expect(cells[9].textContent).toEqual(expectedRealised);
expect(cells[10].textContent).toEqual(expectedUnrealised);
});
it('displays close button', async () => {
+3 -12
View File
@@ -375,10 +375,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
}: VegaValueFormatterParams<Position, 'realisedPNL'>) => {
return !data
? ''
: addDecimalsFormatNumber(
data.realisedPNL,
data.marketDecimalPlaces
);
: addDecimalsFormatNumber(data.realisedPNL, data.decimals);
},
headerTooltip: t(
'Profit or loss is realised whenever your position is reduced to zero and the margin is released back to your collateral balance. P&L excludes any fees paid.'
@@ -396,20 +393,14 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
valueGetter: ({ data }: VegaValueGetterParams<Position>) => {
return !data
? undefined
: toBigNum(
data.unrealisedPNL,
data.marketDecimalPlaces
).toNumber();
: toBigNum(data.unrealisedPNL, data.decimals).toNumber();
},
valueFormatter: ({
data,
}: VegaValueFormatterParams<Position, 'unrealisedPNL'>) =>
!data
? ''
: addDecimalsFormatNumber(
data.unrealisedPNL,
data.marketDecimalPlaces
),
: addDecimalsFormatNumber(data.unrealisedPNL, data.decimals),
headerTooltip: t(
'Unrealised profit is the current profit on your open position. Margin is still allocated to your position.'
),
File diff suppressed because one or more lines are too long
@@ -13,12 +13,12 @@ export type ProposalEventSubscriptionVariables = Types.Exact<{
export type ProposalEventSubscription = { __typename?: 'Subscription', proposals: { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null } };
export type UpdateNetworkParameterProposalFragment = { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } } };
export type UpdateNetworkParameterProposalFragment = { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } } };
export type OnUpdateNetworkParametersSubscriptionVariables = Types.Exact<{ [key: string]: never; }>;
export type OnUpdateNetworkParametersSubscription = { __typename?: 'Subscription', proposals: { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } } } };
export type OnUpdateNetworkParametersSubscription = { __typename?: 'Subscription', proposals: { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, datetime: any, terms: { __typename?: 'ProposalTerms', enactmentDatetime?: any | null, change: { __typename?: 'CancelTransfer' } | { __typename?: 'NewAsset' } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket' } | { __typename?: 'NewTransfer' } | { __typename?: 'UpdateAsset' } | { __typename?: 'UpdateMarket' } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } } } };
export type ProposalOfMarketQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
+6
View File
@@ -92,8 +92,12 @@ export enum AccountType {
ACCOUNT_TYPE_GLOBAL_INSURANCE = 'ACCOUNT_TYPE_GLOBAL_INSURANCE',
/** GlobalReward - a global account for the reward pool */
ACCOUNT_TYPE_GLOBAL_REWARD = 'ACCOUNT_TYPE_GLOBAL_REWARD',
/** AccountTypeHolding - an account for holding funds covering for active unfilled orders */
ACCOUNT_TYPE_HOLDING = 'ACCOUNT_TYPE_HOLDING',
/** Insurance pool account - only for 'system' party */
ACCOUNT_TYPE_INSURANCE = 'ACCOUNT_TYPE_INSURANCE',
/** Per liquidity provider, per market account for holding LPs' fees before distribution */
ACCOUNT_TYPE_LP_LIQUIDITY_FEES = 'ACCOUNT_TYPE_LP_LIQUIDITY_FEES',
/**
* Margin - The leverage account for parties, contains funds set aside for the margin needed to support
* a party's open positions. Each party will have a margin account for each market they have traded in.
@@ -3338,6 +3342,8 @@ export enum ProposalRejectionReason {
PROPOSAL_ERROR_OPENING_AUCTION_DURATION_TOO_SMALL = 'PROPOSAL_ERROR_OPENING_AUCTION_DURATION_TOO_SMALL',
/** Proposal declined because the participation threshold was not reached */
PROPOSAL_ERROR_PARTICIPATION_THRESHOLD_NOT_REACHED = 'PROPOSAL_ERROR_PARTICIPATION_THRESHOLD_NOT_REACHED',
/** Spot trading is disabled */
PROPOSAL_ERROR_SPOT_PRODUCT_DISABLED = 'PROPOSAL_ERROR_SPOT_PRODUCT_DISABLED',
/** Too many decimal places specified in market */
PROPOSAL_ERROR_TOO_MANY_MARKET_DECIMAL_PLACES = 'PROPOSAL_ERROR_TOO_MANY_MARKET_DECIMAL_PLACES',
/** Too many price monitoring triggers specified in market */
+14 -12
View File
@@ -44,6 +44,8 @@ export const AccountTypeMapping: {
ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS: 'Reward Market Proposers',
ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES: 'Reward Maker paid fees',
ACCOUNT_TYPE_SETTLEMENT: 'Settlement',
ACCOUNT_TYPE_HOLDING: 'Holding',
ACCOUNT_TYPE_LP_LIQUIDITY_FEES: 'LP Liquidity Fees',
};
/**
@@ -322,14 +324,14 @@ export const ProposalRejectionReasonMapping: {
PROPOSAL_ERROR_ERC20_ADDRESS_ALREADY_IN_USE:
'ERC20 address already in use by an existing asset',
PROPOSAL_ERROR_GOVERNANCE_CANCEL_TRANSFER_PROPOSAL_INVALID:
'PROPOSAL_ERROR_GOVERNANCE_CANCEL_TRANSFER_PROPOSAL_INVALID',
'Governance cancel transfer proposal invalid',
PROPOSAL_ERROR_GOVERNANCE_TRANSFER_PROPOSAL_FAILED:
'PROPOSAL_ERROR_GOVERNANCE_TRANSFER_PROPOSAL_FAILED',
'Governance transfer proposal failed',
PROPOSAL_ERROR_GOVERNANCE_TRANSFER_PROPOSAL_INVALID:
'PROPOSAL_ERROR_GOVERNANCE_TRANSFER_PROPOSAL_INVALID',
PROPOSAL_ERROR_INVALID_SPOT: 'PROPOSAL_ERROR_INVALID_SPOT',
PROPOSAL_ERROR_INVALID_SUCCESSOR_MARKET:
'PROPOSAL_ERROR_INVALID_SUCCESSOR_MARKET',
'Governance transfer proposal invalid',
PROPOSAL_ERROR_INVALID_SPOT: 'Invalid spot',
PROPOSAL_ERROR_INVALID_SUCCESSOR_MARKET: 'Invalid successor market',
PROPOSAL_ERROR_SPOT_PRODUCT_DISABLED: 'Spot product disabled',
};
/**
@@ -428,9 +430,9 @@ export const TransferTypeMapping: TransferTypeMap = {
TRANSFER_TYPE_TRANSFER_FUNDS_DISTRIBUTE: 'Transfer received',
TRANSFER_TYPE_CLEAR_ACCOUNT: 'Market accounts cleared',
TRANSFER_TYPE_CHECKPOINT_BALANCE_RESTORE: 'Balances restored',
TRANSFER_TYPE_HOLDING_LOCK: 'TRANSFER_TYPE_HOLDING_LOCK',
TRANSFER_TYPE_HOLDING_RELEASE: 'TRANSFER_TYPE_HOLDING_RELEASE',
TRANSFER_TYPE_SPOT: 'TRANSFER_TYPE_SPOT',
TRANSFER_TYPE_HOLDING_LOCK: 'Holding locked',
TRANSFER_TYPE_HOLDING_RELEASE: 'Holding released',
TRANSFER_TYPE_SPOT: 'Spot',
};
export const DescriptionTransferTypeMapping: TransferTypeMap = {
@@ -458,9 +460,9 @@ export const DescriptionTransferTypeMapping: TransferTypeMap = {
TRANSFER_TYPE_CLEAR_ACCOUNT: `Market-related accounts emptied, and balances moved, because the market has closed`,
TRANSFER_TYPE_UNSPECIFIED: 'Default value, always invalid',
TRANSFER_TYPE_CHECKPOINT_BALANCE_RESTORE: `Balances are being restored to the user's account following a checkpoint restart of the network`,
TRANSFER_TYPE_HOLDING_LOCK: '-',
TRANSFER_TYPE_HOLDING_RELEASE: '-',
TRANSFER_TYPE_SPOT: '-',
TRANSFER_TYPE_HOLDING_LOCK: 'Holdings locked',
TRANSFER_TYPE_HOLDING_RELEASE: 'Holdings released',
TRANSFER_TYPE_SPOT: 'Spot',
};
type DispatchMetricLabel = {
@@ -30,14 +30,14 @@ const primary = [
'enabled:active:bg-vega-yellow-550 enabled:active:border-vega-yellow-550',
];
const secondary = [
'text-white dark:text-black',
'text-white',
'border-vega-pink',
'dark:bg-vega-pink bg-vega-pink-550',
'enabled:hover:bg-vega-pink enabled:hover:border-vega-pink',
'enabled:active:bg-vega-pink enabled:active:border-vega-pink',
];
const ternary = [
'text-white dark:text-black',
'text-black',
'border-vega-green',
'dark:bg-vega-green bg-vega-green-550',
'enabled:hover:bg-vega-green enabled:hover:border-vega-green',
@@ -15,6 +15,13 @@ Default.args = {
label: 'Regular checkbox',
};
export const Overflow = Template.bind({});
Overflow.args = {
name: 'overflow',
label:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
};
export const Disabled = Template.bind({});
Disabled.args = {
disabled: true,
@@ -20,7 +20,7 @@ export const Checkbox = ({
disabled = false,
}: CheckboxProps) => {
const rootClasses = classNames(
'relative flex justify-center items-center w-[15px] h-[15px]',
'relative flex justify-center items-center w-[15px] h-[15px] mt-1',
'border rounded-sm overflow-hidden',
{
'opacity-40 cursor-default': disabled,
@@ -30,7 +30,7 @@ export const Checkbox = ({
);
return (
<div className="flex gap-1 items-center">
<div className="flex gap-1">
<CheckboxPrimitive.Root
name={name}
id={name}
@@ -4,7 +4,7 @@ import type { ReactNode } from 'react';
export interface FormGroupProps {
children: ReactNode;
className?: string;
label: string; // For accessibility reasons this must always be set for screen readers. If you want it to not show, then use the hideLabel prop"
label: string | ReactNode; // For accessibility reasons this must always be set for screen readers. If you want it to not show, then use the hideLabel prop"
labelFor: string; // Same as above
hideLabel?: boolean;
labelDescription?: string;
@@ -0,0 +1,18 @@
export const IconArrowUp = ({ size = 16 }: { size: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 16 16">
<path
d="M 7.47,3.63
C 7.47,3.63 2.37,8.72 2.37,8.72
2.37,8.72 1.63,7.98 1.63,7.98
1.63,7.98 8.00,1.60 8.00,1.60
8.00,1.60 14.37,7.98 14.37,7.98
14.37,7.98 13.63,8.72 13.63,8.72
13.63,8.72 8.53,3.63 8.53,3.63
8.53,3.63 8.53,14.35 8.53,14.35
8.53,14.35 7.47,14.35 7.47,14.35
7.47,14.35 7.47,3.63 7.47,3.63 Z"
/>
</svg>
);
};
@@ -0,0 +1,7 @@
export const IconBullet = ({ size = 16 }: { size: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 16 16">
<circle cx="8" cy="8" r="6" />
</svg>
);
};
@@ -0,0 +1,13 @@
export const IconMinus = ({ size = 16 }: { size: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 16 16">
<path
d="M 0.92,8.58
C 0.92,8.58 0.92,7.48 0.92,7.48
0.92,7.48 15.01,7.48 15.01,7.48
15.01,7.48 15.01,8.58 15.01,8.58
15.01,8.58 0.92,8.58 0.92,8.58 Z"
/>
</svg>
);
};
@@ -0,0 +1,21 @@
export const IconPlus = ({ size = 16 }: { size: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 16 16">
<path
d="M 7.43,15.24
C 7.43,15.24 7.43,8.58 7.43,8.58
7.43,8.58 0.92,8.58 0.92,8.58
0.92,8.58 0.92,7.48 0.92,7.48
0.92,7.48 7.43,7.48 7.43,7.48
7.43,7.48 7.43,0.85 7.43,0.85
7.43,0.85 8.48,0.85 8.48,0.85
8.48,0.85 8.48,7.48 8.48,7.48
8.48,7.48 15.01,7.48 15.01,7.48
15.01,7.48 15.01,8.58 15.01,8.58
15.01,8.58 8.48,8.58 8.48,8.58
8.48,8.58 8.48,15.24 8.48,15.24
8.48,15.24 7.43,15.24 7.43,15.24 Z"
/>
</svg>
);
};
@@ -1,6 +1,8 @@
import { IconArrowDown } from './svg-icons/icon-arrow-down';
import { IconArrowUp } from './svg-icons/icon-arrow-up';
import { IconArrowRight } from './svg-icons/icon-arrow-right';
import { IconBreakdown } from './svg-icons/icon-breakdown';
import { IconBullet } from './svg-icons/icon-bullet';
import { IconChevronDown } from './svg-icons/icon-chevron-down';
import { IconChevronLeft } from './svg-icons/icon-chevron-left';
import { IconChevronUp } from './svg-icons/icon-chevron-up';
@@ -13,9 +15,11 @@ import { IconGlobe } from './svg-icons/icon-globe';
import { IconInfo } from './svg-icons/icon-info';
import { IconKebab } from './svg-icons/icon-kebab';
import { IconLinkedIn } from './svg-icons/icon-linkedin';
import { IconMinus } from './svg-icons/icon-minus';
import { IconMoon } from './svg-icons/icon-moon';
import { IconOpenExternal } from './svg-icons/icon-open-external';
import { IconQuestionMark } from './svg-icons/icon-question-mark';
import { IconPlus } from './svg-icons/icon-plus';
import { IconTick } from './svg-icons/icon-tick';
import { IconTransfer } from './svg-icons/icon-transfer';
import { IconTrendUp } from './svg-icons/icon-trend-up';
@@ -24,8 +28,10 @@ import { IconWithdraw } from './svg-icons/icon-withdraw';
export enum VegaIconNames {
ARROW_DOWN = 'arrow-down',
ARROW_UP = 'arrow-up',
ARROW_RIGHT = 'arrow-right',
BREAKDOWN = 'breakdown',
BULLET = 'bullet',
CHEVRON_DOWN = 'chevron-down',
CHEVRON_LEFT = 'chevron-left',
CHEVRON_UP = 'chevron-up',
@@ -38,9 +44,11 @@ export enum VegaIconNames {
INFO = 'info',
KEBAB = 'kebab',
LINKEDIN = 'linkedin',
MINUS = 'minus',
MOON = 'moon',
OPEN_EXTERNAL = 'open-external',
QUESTION_MARK = 'question-mark',
PLUS = 'plus',
TICK = 'tick',
TRANSFER = 'transfer',
TREND_UP = 'trend-up',
@@ -53,6 +61,7 @@ export const VegaIconNameMap: Record<
({ size }: { size: number }) => JSX.Element
> = {
'arrow-down': IconArrowDown,
'arrow-up': IconArrowUp,
'arrow-right': IconArrowRight,
'chevron-down': IconChevronDown,
'chevron-left': IconChevronLeft,
@@ -61,6 +70,7 @@ export const VegaIconNameMap: Record<
'question-mark': IconQuestionMark,
'trend-up': IconTrendUp,
breakdown: IconBreakdown,
bullet: IconBullet,
copy: IconCopy,
cross: IconCross,
deposit: IconDeposit,
@@ -70,7 +80,9 @@ export const VegaIconNameMap: Record<
info: IconInfo,
kebab: IconKebab,
linkedin: IconLinkedIn,
minus: IconMinus,
moon: IconMoon,
plus: IconPlus,
tick: IconTick,
transfer: IconTransfer,
twitter: IconTwitter,
+2 -1
View File
@@ -23,6 +23,7 @@ export const Tabs = ({
}
return children[0].props.id;
});
return (
<TabsPrimitive.Root
{...props}
@@ -30,7 +31,7 @@ export const Tabs = ({
onValueChange={onValueChange || setActiveTab}
className="h-full grid grid-rows-[min-content_1fr]"
>
<div className="border-b border-default">
<div className="border-b border-default min-w-0">
<TabsPrimitive.List
className="flex flex-nowrap overflow-visible"
role="tablist"
+3 -2
View File
@@ -8,10 +8,11 @@ export const defaultFormElement = (hasError?: boolean) =>
'flex items-center w-full text-sm',
'p-2 border-2 rounded',
'bg-transparent',
'border border-vega-light-200 dark:border-vega-dark-200',
'border',
'focus:border-vega-light-300 dark:focus:border-vega-dark-300',
'disabled:opacity-60',
{
'border-vega-pink': hasError,
'border-vega-pink text-vega-pink': hasError,
'border-vega-light-200 dark:border-vega-dark-200': !hasError,
}
);
+1 -1
View File
@@ -7,7 +7,7 @@ import {
export const formatValue = (
value: string | number | null | undefined,
decimalPlaces: number,
quantum?: string,
quantum?: string | number,
formatDecimals?: number,
emptyValue = '-'
): string => {
@@ -47,6 +47,10 @@ export interface OrderSubmission {
expiresAt?: string;
postOnly?: boolean;
reduceOnly?: boolean;
icebergOpts?: {
peakSize: string;
minimumVisibleSize: string;
};
}
export interface OrderCancellation {
+7
View File
@@ -50,6 +50,13 @@ export const normalizeOrderSubmission = (
: undefined,
postOnly: order.postOnly,
reduceOnly: order.reduceOnly,
icebergOpts: order.icebergOpts && {
peakSize: removeDecimal(order.icebergOpts.peakSize, positionDecimalPlaces),
minimumVisibleSize: removeDecimal(
order.icebergOpts.minimumVisibleSize,
positionDecimalPlaces
),
},
});
export const normalizeOrderAmendment = <T extends Exact<OrderAmendment, T>>(
+4 -9
View File
@@ -11167,15 +11167,10 @@ caniuse-api@^3.0.0:
lodash.memoize "^4.1.2"
lodash.uniq "^4.5.0"
caniuse-lite@^1.0.0, caniuse-lite@^1.0.30001406, caniuse-lite@^1.0.30001426, caniuse-lite@^1.0.30001464, caniuse-lite@^1.0.30001503:
version "1.0.30001508"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001508.tgz#4461bbc895c692a96da399639cc1e146e7302a33"
integrity sha512-sdQZOJdmt3GJs1UMNpCCCyeuS2IEGLXnHyAo9yIO5JJDjbjoVRij4M1qep6P6gFpptD1PqIYgzM+gwJbOi92mw==
caniuse-lite@^1.0.30001400:
version "1.0.30001431"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001431.tgz#e7c59bd1bc518fae03a4656be442ce6c4887a795"
integrity sha512-zBUoFU0ZcxpvSt9IU66dXVT/3ctO1cy4y9cscs1szkPlcWb6pasYM144GqrUygUbT+k7cmUCW61cvskjcv0enQ==
caniuse-lite@^1.0.0, caniuse-lite@^1.0.30001400, caniuse-lite@^1.0.30001406, caniuse-lite@^1.0.30001426, caniuse-lite@^1.0.30001464, caniuse-lite@^1.0.30001503:
version "1.0.30001512"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001512.tgz"
integrity sha512-2S9nK0G/mE+jasCUsMPlARhRCts1ebcp2Ji8Y8PWi4NDE1iRdLCnEPHkEfeBrGC45L4isBx5ur3IQ6yTE2mRZw==
capital-case@^1.0.4:
version "1.0.4"