Merge pull request #165 from vegaprotocol/task/164-colocate-queries

Task/164 colocate queries
This commit is contained in:
Bartłomiej Głownia 2022-03-30 14:36:27 +02:00 committed by GitHub
commit fdf76aa88b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
174 changed files with 570 additions and 740 deletions

View File

@ -48,6 +48,13 @@
"ts-check": false,
"minimumDescriptionLength": 10
}
],
"@typescript-eslint/consistent-type-imports": [
"error",
{
"prefer": "type-imports",
"disallowTypeAnnotations": true
}
]
}
},

View File

@ -31,11 +31,11 @@ jobs:
run: yarn install
- name: Check formatting
run: yarn nx format:check
- name: Check formatting
run: yarn eslint
- name: Check formatting
- name: Lint affected
run: yarn nx affected:lint
- name: Test affected
run: yarn nx affected:test
- name: Check formatting
- name: Build affected
run: yarn nx affected:build
pr:
name: Test and lint - PR
@ -59,9 +59,9 @@ jobs:
run: yarn install
- name: Check formatting
run: yarn nx format:check
- name: Check formatting
run: yarn eslint
- name: Check formatting
- name: Lint affected
run: yarn nx affected:lint
- name: Test affected
run: yarn nx affected:test
- name: Check formatting
- name: Build affected
run: yarn nx affected:build

View File

@ -1,6 +1,6 @@
{
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

@ -1,126 +0,0 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
//==============================================================
// START Enums and Input Objects
//==============================================================
/**
* The various account types we have (used by collateral)
*/
export enum AccountType {
Bond = "Bond",
FeeInfrastructure = "FeeInfrastructure",
FeeLiquidity = "FeeLiquidity",
General = "General",
GlobalInsurance = "GlobalInsurance",
Insurance = "Insurance",
LockWithdraw = "LockWithdraw",
Margin = "Margin",
Settlement = "Settlement",
}
export enum AuctionTrigger {
Batch = "Batch",
Liquidity = "Liquidity",
Opening = "Opening",
Price = "Price",
Unspecified = "Unspecified",
}
/**
* The current state of a market
*/
export enum MarketState {
Active = "Active",
Cancelled = "Cancelled",
Closed = "Closed",
Pending = "Pending",
Proposed = "Proposed",
Rejected = "Rejected",
Settled = "Settled",
Suspended = "Suspended",
TradingTerminated = "TradingTerminated",
}
/**
* What market trading mode are we in
*/
export enum MarketTradingMode {
BatchAuction = "BatchAuction",
Continuous = "Continuous",
MonitoringAuction = "MonitoringAuction",
OpeningAuction = "OpeningAuction",
}
export enum NodeStatus {
NonValidator = "NonValidator",
Validator = "Validator",
}
/**
* Reason for the proposal being rejected by the core node
*/
export enum ProposalRejectionReason {
CloseTimeTooLate = "CloseTimeTooLate",
CloseTimeTooSoon = "CloseTimeTooSoon",
CouldNotInstantiateMarket = "CouldNotInstantiateMarket",
EnactTimeTooLate = "EnactTimeTooLate",
EnactTimeTooSoon = "EnactTimeTooSoon",
IncompatibleTimestamps = "IncompatibleTimestamps",
InsufficientTokens = "InsufficientTokens",
InvalidAsset = "InvalidAsset",
InvalidAssetDetails = "InvalidAssetDetails",
InvalidFeeAmount = "InvalidFeeAmount",
InvalidFutureMaturityTimestamp = "InvalidFutureMaturityTimestamp",
InvalidFutureProduct = "InvalidFutureProduct",
InvalidInstrumentSecurity = "InvalidInstrumentSecurity",
InvalidRiskParameter = "InvalidRiskParameter",
InvalidShape = "InvalidShape",
MajorityThresholdNotReached = "MajorityThresholdNotReached",
MarketMissingLiquidityCommitment = "MarketMissingLiquidityCommitment",
MissingBuiltinAssetField = "MissingBuiltinAssetField",
MissingCommitmentAmount = "MissingCommitmentAmount",
MissingERC20ContractAddress = "MissingERC20ContractAddress",
NetworkParameterInvalidKey = "NetworkParameterInvalidKey",
NetworkParameterInvalidValue = "NetworkParameterInvalidValue",
NetworkParameterValidationFailed = "NetworkParameterValidationFailed",
NoProduct = "NoProduct",
NoRiskParameters = "NoRiskParameters",
NoTradingMode = "NoTradingMode",
NodeValidationFailed = "NodeValidationFailed",
OpeningAuctionDurationTooLarge = "OpeningAuctionDurationTooLarge",
OpeningAuctionDurationTooSmall = "OpeningAuctionDurationTooSmall",
ParticipationThresholdNotReached = "ParticipationThresholdNotReached",
ProductMaturityIsPassed = "ProductMaturityIsPassed",
UnsupportedProduct = "UnsupportedProduct",
UnsupportedTradingMode = "UnsupportedTradingMode",
}
/**
* Various states a proposal can transition through:
* Open ->
* - Passed -> Enacted.
* - Rejected.
* Proposal can enter Failed state from any other state.
*/
export enum ProposalState {
Declined = "Declined",
Enacted = "Enacted",
Failed = "Failed",
Open = "Open",
Passed = "Passed",
Rejected = "Rejected",
WaitingForNodeVote = "WaitingForNodeVote",
}
export enum VoteValue {
No = "No",
Yes = "Yes",
}
//==============================================================
// END Enums and Input Objects
//==============================================================

View File

@ -1,5 +1,5 @@
import React from 'react';
import { BlockMeta } from '../../routes/blocks/tendermint-blockchain-response';
import type { BlockMeta } from '../../routes/blocks/tendermint-blockchain-response';
import { Routes } from '../../routes/router-config';
import { Link } from 'react-router-dom';
import { SecondsAgo } from '../seconds-ago';

View File

@ -1,5 +1,5 @@
import React from 'react';
import { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import type { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import { BlockData } from './block-data';
interface BlocksProps {

View File

@ -1,4 +1,4 @@
import { HTMLInputTypeAttribute, SyntheticEvent } from 'react';
import type { HTMLInputTypeAttribute, SyntheticEvent } from 'react';
import { Input, Button } from '@vegaprotocol/ui-toolkit';
interface JumpToProps {

View File

@ -1,5 +1,6 @@
import classnames from 'classnames';
import React, { HTMLAttributes } from 'react';
import type { HTMLAttributes } from 'react';
import React from 'react';
interface RouteTitleProps extends HTMLAttributes<HTMLHeadingElement> {
children: React.ReactNode;

View File

@ -1,5 +1,5 @@
import classnames from 'classnames';
import { HTMLAttributes } from 'react';
import type { HTMLAttributes } from 'react';
interface SubHeadingProps extends HTMLAttributes<HTMLHeadingElement> {
children: React.ReactNode;

View File

@ -1,4 +1,5 @@
import React, { ThHTMLAttributes } from 'react';
import type { ThHTMLAttributes } from 'react';
import React from 'react';
import classnames from 'classnames';
interface TableProps extends ThHTMLAttributes<HTMLTableElement> {

View File

@ -1,5 +1,5 @@
import React from 'react';
import { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import type { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import { BlockData } from '../blocks';
import { TxsPerBlock } from './txs-per-block';

View File

@ -1,4 +1,4 @@
import { TendermintUnconfirmedTransactionsResponse } from '../../routes/txs/tendermint-unconfirmed-transactions-response.d';
import type { TendermintUnconfirmedTransactionsResponse } from '../../routes/txs/tendermint-unconfirmed-transactions-response.d';
interface TxsProps {
data: TendermintUnconfirmedTransactionsResponse | undefined;

View File

@ -1,5 +1,5 @@
import useFetch from '../../hooks/use-fetch';
import { ChainExplorerTxResponse } from '../../routes/types/chain-explorer-response';
import type { ChainExplorerTxResponse } from '../../routes/types/chain-explorer-response';
import { Routes } from '../../routes/router-config';
import { DATA_SOURCES } from '../../config';
import { Link } from 'react-router-dom';

View File

@ -1,5 +1,5 @@
import React from 'react';
import { WebSocketHook } from 'react-use-websocket/dist/lib/types';
import type { WebSocketHook } from 'react-use-websocket/dist/lib/types';
export type WebsocketContextShape = WebSocketHook;

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { AccountType } from "./globalTypes";
import { AccountType } from "./../../../../../../../libs/types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: AssetsQuery

View File

@ -3,7 +3,7 @@ import React from 'react';
import { RouteTitle } from '../../components/route-title';
import { SubHeading } from '../../components/sub-heading';
import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { AssetsQuery } from '@vegaprotocol/graphql';
import type { AssetsQuery } from './__generated__/AssetsQuery';
export const ASSETS_QUERY = gql`
query AssetsQuery {

View File

@ -1,6 +1,6 @@
import { DATA_SOURCES } from '../../../config';
import useFetch from '../../../hooks/use-fetch';
import { TendermintBlockchainResponse } from '../tendermint-blockchain-response';
import type { TendermintBlockchainResponse } from '../tendermint-blockchain-response';
import { RouteTitle } from '../../../components/route-title';
import { RenderFetched } from '../../../components/render-fetched';
import { BlocksData, BlocksRefetch } from '../../../components/blocks';

View File

@ -2,7 +2,7 @@ import React from 'react';
import { Link, useParams } from 'react-router-dom';
import { DATA_SOURCES } from '../../../config';
import useFetch from '../../../hooks/use-fetch';
import { TendermintBlocksResponse } from '../tendermint-blocks-response';
import type { TendermintBlocksResponse } from '../tendermint-blocks-response';
import { RouteTitle } from '../../../components/route-title';
import { SecondsAgo } from '../../../components/seconds-ago';
import {

View File

@ -63,6 +63,7 @@ export interface Block {
last_commit: LastCommit;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ResultBeginBlock {}
export interface ResultEndBlock {
@ -81,7 +82,7 @@ export interface Data {
}
export interface Events {
"tm.event": string[];
'tm.event': string[];
}
export interface Result {

View File

@ -2,7 +2,7 @@ import { RouteTitle } from '../../components/route-title';
import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { DATA_SOURCES } from '../../config';
import useFetch from '../../hooks/use-fetch';
import { TendermintGenesisResponse } from './tendermint-genesis-response';
import type { TendermintGenesisResponse } from './tendermint-genesis-response';
const Genesis = () => {
const {

View File

@ -13,6 +13,7 @@ export interface ValidatorAddresses {
pub_key_types: string[];
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Version {}
export interface ConsensusParams {

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { ProposalState, ProposalRejectionReason, VoteValue } from "./globalTypes";
import { ProposalState, ProposalRejectionReason, VoteValue } from "./../../../../../../../libs/types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: ProposalsQuery

View File

@ -3,10 +3,10 @@ import React from 'react';
import { RouteTitle } from '../../components/route-title';
import { SubHeading } from '../../components/sub-heading';
import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import {
import type {
ProposalsQuery,
ProposalsQuery_proposals_terms_change,
} from '@vegaprotocol/graphql';
} from './__generated__/ProposalsQuery';
export function getProposalName(change: ProposalsQuery_proposals_terms_change) {
if (change.__typename === 'NewAsset') {

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { MarketTradingMode, MarketState, AccountType, AuctionTrigger } from "./globalTypes";
import { MarketTradingMode, MarketState, AccountType, AuctionTrigger } from "./../../../../../../../libs/types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: MarketsQuery

View File

@ -1,5 +1,5 @@
import { gql, useQuery } from '@apollo/client';
import { MarketsQuery } from '@vegaprotocol/graphql';
import type { MarketsQuery } from './__generated__/MarketsQuery';
import React from 'react';
import { SyntaxHighlighter } from '../../components/syntax-highlighter';

View File

@ -1,6 +1,6 @@
import { gql, useQuery } from '@apollo/client';
import { RouteTitle } from '../../components/route-title';
import { NetworkParametersQuery } from '@vegaprotocol/graphql';
import type { NetworkParametersQuery } from './__generated__/NetworkParametersQuery';
import { SyntaxHighlighter } from '../../components/syntax-highlighter';
export const NETWORK_PARAMETERS_QUERY = gql`

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { AccountType } from "./globalTypes";
import { AccountType } from "./../../../../../../../../libs/types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: PartyAssetsQuery

View File

@ -7,11 +7,11 @@ import { SubHeading } from '../../../components/sub-heading';
import { SyntaxHighlighter } from '../../../components/syntax-highlighter';
import { DATA_SOURCES } from '../../../config';
import useFetch from '../../../hooks/use-fetch';
import { TendermintSearchTransactionResponse } from '../tendermint-transaction-response';
import {
import type { TendermintSearchTransactionResponse } from '../tendermint-transaction-response';
import type {
PartyAssetsQuery,
PartyAssetsQueryVariables,
} from '@vegaprotocol/graphql';
} from './__generated__/PartyAssetsQuery';
const PARTY_ASSETS_QUERY = gql`
query PartyAssetsQuery($partyId: ID!) {

View File

@ -1,7 +1,7 @@
import React from 'react';
import { DATA_SOURCES } from '../../config';
import useFetch from '../../hooks/use-fetch';
import { TendermintUnconfirmedTransactionsResponse } from '../txs/tendermint-unconfirmed-transactions-response.d';
import type { TendermintUnconfirmedTransactionsResponse } from '../txs/tendermint-unconfirmed-transactions-response.d';
import { TxList } from '../../components/txs';
import { RouteTitle } from '../../components/route-title';

View File

@ -1,5 +1,5 @@
import useFetch from '../../../hooks/use-fetch';
import { TendermintBlockchainResponse } from '../../blocks/tendermint-blockchain-response';
import type { TendermintBlockchainResponse } from '../../blocks/tendermint-blockchain-response';
import { DATA_SOURCES } from '../../../config';
import { RouteTitle } from '../../../components/route-title';
import { BlocksRefetch } from '../../../components/blocks';

View File

@ -1,8 +1,8 @@
import React from 'react';
import { useParams } from 'react-router-dom';
import useFetch from '../../../hooks/use-fetch';
import { TendermintTransactionResponse } from '../tendermint-transaction-response.d';
import { ChainExplorerTxResponse } from '../../types/chain-explorer-response';
import type { TendermintTransactionResponse } from '../tendermint-transaction-response.d';
import type { ChainExplorerTxResponse } from '../../types/chain-explorer-response';
import { DATA_SOURCES } from '../../../config';
import { RouteTitle } from '../../../components/route-title';
import { RenderFetched } from '../../../components/render-fetched';

View File

@ -7,7 +7,7 @@ import {
TableRow,
} from '../../../components/table';
import { TxOrderType } from '../../../components/txs';
import { ChainExplorerTxResponse } from '../../../routes/types/chain-explorer-response';
import type { ChainExplorerTxResponse } from '../../../routes/types/chain-explorer-response';
interface TxContentProps {
data: ChainExplorerTxResponse | undefined;

View File

@ -7,7 +7,7 @@ import {
} from '../../../components/table';
import { TruncateInline } from '../../../components/truncate/truncate';
import { Routes } from '../../../routes/router-config';
import { Result } from '../../../routes/txs/tendermint-transaction-response.d';
import type { Result } from '../../../routes/txs/tendermint-transaction-response.d';
interface TxDetailsProps {
txData: Result | undefined;

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { NodeStatus } from "./globalTypes";
import { NodeStatus } from "./../../../../../../../libs/types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: NodesQuery

View File

@ -5,8 +5,8 @@ import { SubHeading } from '../../components/sub-heading';
import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { DATA_SOURCES } from '../../config';
import useFetch from '../../hooks/use-fetch';
import { TendermintValidatorsResponse } from './tendermint-validator-response';
import { NodesQuery } from '@vegaprotocol/graphql';
import type { TendermintValidatorsResponse } from './tendermint-validator-response';
import type { NodesQuery } from './__generated__/NodesQuery';
const NODES_QUERY = gql`
query NodesQuery {

View File

@ -1,4 +1,4 @@
import { ReportHandler } from 'web-vitals';
import type { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {

View File

@ -5,7 +5,7 @@
"next",
"next/core-web-vitals"
],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

@ -1,5 +1,5 @@
import { useEagerConnect } from '../../hooks/use-vega-wallet-eager-connect';
import { ReactNode } from 'react';
import type { ReactNode } from 'react';
interface AppLoaderProps {
children: ReactNode;

View File

@ -1 +0,0 @@
export * from './deal-ticket-container';

View File

@ -1 +0,0 @@
export * from './order-list-container';

View File

@ -1,14 +0,0 @@
import { useOrders } from '../../hooks/use-orders';
import { OrderList } from '@vegaprotocol/order-list';
import { AsyncRenderer } from '../async-renderer';
import { OrderFields } from '@vegaprotocol/graphql';
export const OrderListContainer = () => {
const { orders, loading, error } = useOrders();
return (
<AsyncRenderer<OrderFields[]> loading={loading} error={error} data={orders}>
{(data) => <OrderList orders={data} />}
</AsyncRenderer>
);
};

View File

@ -1,7 +1,8 @@
import { OperationVariables, QueryHookOptions, useQuery } from '@apollo/client';
import { DocumentNode } from 'graphql';
import { ReactNode } from 'react';
import { AsyncRenderer } from '../async-renderer';
import type { OperationVariables, QueryHookOptions } from '@apollo/client';
import { useQuery } from '@apollo/client';
import type { DocumentNode } from 'graphql';
import type { ReactNode } from 'react';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
interface PageQueryContainerProps<TData, TVariables> {
query: DocumentNode;

View File

@ -1,7 +1,8 @@
import { Button, Splash } from '@vegaprotocol/ui-toolkit';
import { Web3Provider, Web3ConnectDialog } from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core';
import { ReactNode, useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';
import { Connectors } from '../../lib/web3-connectors';
interface Web3ContainerProps {

View File

@ -1,4 +1,4 @@
import { AppProps } from 'next/app';
import type { AppProps } from 'next/app';
import Head from 'next/head';
import { Navbar } from '../components/navbar';
import { ThemeContext } from '@vegaprotocol/react-helpers';

View File

@ -1,5 +1,5 @@
import { gql } from '@apollo/client';
import { Market, MarketVariables } from '@vegaprotocol/graphql';
import type { Market, MarketVariables } from './__generated__/Market';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react';
@ -13,34 +13,6 @@ const MARKET_QUERY = gql`
market(id: $marketId) {
id
name
decimalPlaces
state
tradingMode
tradableInstrument {
instrument {
product {
... on Future {
quoteName
settlementAsset {
id
symbol
name
}
}
}
}
}
trades {
id
price
size
createdAt
}
depth {
lastTrade {
price
}
}
}
}
`;

View File

@ -4,36 +4,28 @@
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: Guess
// GraphQL query operation: Market
// ====================================================
export interface Guess_party {
__typename: "Party";
/**
* Party identifier
*/
id: string;
}
export interface Guess_market {
export interface Market_market {
__typename: "Market";
/**
* Market ID
*/
id: string;
/**
* Market full name
*/
name: string;
}
export interface Guess {
/**
* An entity that is trading on the VEGA network
*/
party: Guess_party | null;
export interface Market {
/**
* An instrument that is trading on the VEGA network
*/
market: Guess_market | null;
market: Market_market | null;
}
export interface GuessVariables {
guess: string;
export interface MarketVariables {
marketId: string;
}

View File

@ -1,14 +1,8 @@
import * as Tabs from '@radix-ui/react-tabs';
import classNames from 'classnames';
import { useRouter } from 'next/router';
import {
Children,
isValidElement,
ReactElement,
ReactNode,
useEffect,
useState,
} from 'react';
import type { ReactElement, ReactNode } from 'react';
import { Children, isValidElement, useEffect, useState } from 'react';
interface GridTabsProps {
children: ReactElement<GridTabProps>[];

View File

@ -1,70 +1,7 @@
import { useRef, useCallback } from 'react';
import { produce } from 'immer';
import merge from 'lodash/merge';
import { useRouter } from 'next/router';
import { AsyncRenderer } from '../../components/async-renderer';
import { MarketListTable, getRowNodeId } from '@vegaprotocol/market-list';
import {
Markets_markets,
Markets_markets_data,
marketsDataProvider,
} from '@vegaprotocol/graphql';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import type { AgGridReact } from 'ag-grid-react';
import { MarketsContainer } from '@vegaprotocol/market-list';
const Markets = () => {
const { pathname, push } = useRouter();
const gridRef = useRef<AgGridReact | null>(null);
const update = useCallback(
(delta: Markets_markets_data) => {
const update: Markets_markets[] = [];
const add: Markets_markets[] = [];
if (!gridRef.current) {
return false;
}
const rowNode = gridRef.current.api.getRowNode(
getRowNodeId(delta.market)
);
if (rowNode) {
const updatedData = produce<Markets_markets_data>(
rowNode.data.data,
(draft: Markets_markets_data) => merge(draft, delta)
);
if (updatedData !== rowNode.data.data) {
update.push({ ...rowNode.data, data: updatedData });
}
}
// @TODO - else add new market
if (update.length || add.length) {
gridRef.current.api.applyTransactionAsync({
update,
add,
addIndex: 0,
});
}
return true;
},
[gridRef]
);
const { data, error, loading } = useDataProvider<
Markets_markets,
Markets_markets_data
>(marketsDataProvider, update);
return (
<AsyncRenderer loading={loading} error={error} data={data}>
{(data) => (
<MarketListTable
ref={gridRef}
data={data}
onRowClicked={(id) =>
push(`${pathname}/${id}?portfolio=orders&trade=orderbook`)
}
/>
)}
</AsyncRenderer>
);
return <MarketsContainer />;
};
export default Markets;

View File

@ -1,12 +1,13 @@
import { Market_market } from '@vegaprotocol/graphql';
import classNames from 'classnames';
import AutoSizer from 'react-virtualized-auto-sizer';
import { useState, ReactNode, ComponentType } from 'react';
import type { ReactNode } from 'react';
import { useState } from 'react';
import { GridTab, GridTabs } from './grid-tabs';
import { DealTicketContainer } from '../../components/deal-ticket-container';
import { OrderListContainer } from '../..//components/order-list-container';
import { DealTicketContainer } from '@vegaprotocol/deal-ticket';
import { OrderListContainer } from '@vegaprotocol/order-list';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { Positions } from './positions';
import { PositionsContainer } from '@vegaprotocol/positions';
import type { Market_market } from './__generated__/Market';
const Chart = () => (
<Splash>
@ -29,22 +30,12 @@ const Trades = () => (
</Splash>
);
// enum TradingView {
// Chart = 'Chart',
// Ticket = 'Ticket',
// Orderbook = 'Orderbook',
// Orders = 'Orders',
// Positions = 'Positions',
// Collateral = 'Collateral',
// Trades = 'Trades',
// }
const TradingViews = {
Chart: Chart,
Ticket: DealTicketContainer,
Orderbook: Orderbook,
Orders: OrderListContainer,
Positions: Positions,
Positions: PositionsContainer,
Collateral: Collateral,
Trades: Trades,
};
@ -71,7 +62,7 @@ export const TradeGrid = ({ market }: TradeGridProps) => {
<TradingViews.Chart />
</TradeGridChild>
<TradeGridChild className="row-start-1 row-end-3">
<TradingViews.Ticket market={market} />
<TradingViews.Ticket marketId={market.id} />
</TradeGridChild>
<TradeGridChild className="row-start-1 row-end-3">
<GridTabs group="trade">
@ -134,7 +125,7 @@ export const TradePanels = ({ market }: TradePanelsProps) => {
throw new Error(`No component for view: ${view}`);
}
return <Component market={market} />;
return <Component marketId={market.id} />;
};
return (

View File

@ -1,6 +1,6 @@
{
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

@ -3,77 +3,37 @@
// @generated
// This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes";
import { MarketState, MarketTradingMode } from "./../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: Market
// GraphQL query operation: DealTicketQuery
// ====================================================
export interface Market_market_tradableInstrument_instrument_product_settlementAsset {
__typename: "Asset";
/**
* The id of the asset
*/
id: string;
/**
* The symbol of the asset (e.g: GBP)
*/
symbol: string;
/**
* The full name of the asset (e.g: Great British Pound)
*/
name: string;
}
export interface Market_market_tradableInstrument_instrument_product {
export interface DealTicketQuery_market_tradableInstrument_instrument_product {
__typename: "Future";
/**
* String representing the quote (e.g. BTCUSD -> USD is quote)
*/
quoteName: string;
/**
* The name of the asset (string)
*/
settlementAsset: Market_market_tradableInstrument_instrument_product_settlementAsset;
}
export interface Market_market_tradableInstrument_instrument {
export interface DealTicketQuery_market_tradableInstrument_instrument {
__typename: "Instrument";
/**
* A reference to or instance of a fully specified product, including all required product parameters for that product (Product union)
*/
product: Market_market_tradableInstrument_instrument_product;
product: DealTicketQuery_market_tradableInstrument_instrument_product;
}
export interface Market_market_tradableInstrument {
export interface DealTicketQuery_market_tradableInstrument {
__typename: "TradableInstrument";
/**
* An instance of or reference to a fully specified instrument.
*/
instrument: Market_market_tradableInstrument_instrument;
instrument: DealTicketQuery_market_tradableInstrument_instrument;
}
export interface Market_market_trades {
__typename: "Trade";
/**
* The hash of the trade data
*/
id: string;
/**
* The price of the trade (probably initially the passive order price, other determination algorithms are possible though) (uint64)
*/
price: string;
/**
* The number of contracts trades, will always be <= the remaining size of both orders immediately before the trade (uint64)
*/
size: string;
/**
* RFC3339Nano time for when the trade occurred
*/
createdAt: string;
}
export interface Market_market_depth_lastTrade {
export interface DealTicketQuery_market_depth_lastTrade {
__typename: "Trade";
/**
* The price of the trade (probably initially the passive order price, other determination algorithms are possible though) (uint64)
@ -81,24 +41,20 @@ export interface Market_market_depth_lastTrade {
price: string;
}
export interface Market_market_depth {
export interface DealTicketQuery_market_depth {
__typename: "MarketDepth";
/**
* Last trade for the given market (if available)
*/
lastTrade: Market_market_depth_lastTrade | null;
lastTrade: DealTicketQuery_market_depth_lastTrade | null;
}
export interface Market_market {
export interface DealTicketQuery_market {
__typename: "Market";
/**
* Market ID
*/
id: string;
/**
* Market full name
*/
name: string;
/**
* decimalPlaces indicates the number of decimal places that an integer must be shifted by in order to get a correct
* number denominated in the currency of the Market. (uint64)
@ -127,24 +83,20 @@ export interface Market_market {
/**
* An instance of or reference to a tradable instrument.
*/
tradableInstrument: Market_market_tradableInstrument;
/**
* Trades on a market
*/
trades: Market_market_trades[] | null;
tradableInstrument: DealTicketQuery_market_tradableInstrument;
/**
* Current depth on the order book for this market
*/
depth: Market_market_depth;
depth: DealTicketQuery_market_depth;
}
export interface Market {
export interface DealTicketQuery {
/**
* An instrument that is trading on the VEGA network
*/
market: Market_market | null;
market: DealTicketQuery_market | null;
}
export interface MarketVariables {
export interface DealTicketQueryVariables {
marketId: string;
}

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { BusEventType, OrderType, OrderStatus, OrderRejectionReason } from "./globalTypes";
import { BusEventType, OrderType, OrderStatus, OrderRejectionReason } from "./../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL subscription operation: OrderEvent

View File

@ -0,0 +1,54 @@
import { AsyncRenderer, Splash } from '@vegaprotocol/ui-toolkit';
import { gql, useQuery } from '@apollo/client';
import { DealTicketManager } from './deal-ticket-manager';
import type { DealTicketQuery } from './__generated__/DealTicketQuery';
const DEAL_TICKET_QUERY = gql`
query DealTicketQuery($marketId: ID!) {
market(id: $marketId) {
id
decimalPlaces
state
tradingMode
tradableInstrument {
instrument {
product {
... on Future {
quoteName
}
}
}
}
depth {
lastTrade {
price
}
}
}
}
`;
interface DealTicketContainerProps {
marketId: string;
}
export const DealTicketContainer = ({ marketId }: DealTicketContainerProps) => {
const { data, loading, error } = useQuery(DEAL_TICKET_QUERY, {
variables: { marketId },
});
return (
<AsyncRenderer<DealTicketQuery> data={data} loading={loading} error={error}>
{(data) => {
if (!data.market) {
return (
<Splash>
<p>Could not load market</p>
</Splash>
);
}
return <DealTicketManager market={data.market} />;
}}
</AsyncRenderer>
);
};

View File

@ -1,19 +1,19 @@
import { FormGroup, Input } from '@vegaprotocol/ui-toolkit';
import { OrderTimeInForce } from '@vegaprotocol/wallet';
import { TransactionStatus } from './deal-ticket';
import { Market_market } from '@vegaprotocol/graphql';
import type { TransactionStatus } from './deal-ticket';
import { ExpirySelector } from './expiry-selector';
import { SideSelector } from './side-selector';
import { SubmitButton } from './submit-button';
import { TimeInForceSelector } from './time-in-force-selector';
import { TypeSelector } from './type-selector';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
interface DealTicketLimitProps {
order: Order;
updateOrder: (order: Partial<Order>) => void;
transactionStatus: TransactionStatus;
market: Market_market;
market: DealTicketQuery_market;
}
export const DealTicketLimit = ({

View File

@ -1,16 +1,17 @@
import { Dialog, Intent } from '@vegaprotocol/ui-toolkit';
import { DealTicket } from '@vegaprotocol/deal-ticket';
import { Market_market, OrderStatus } from '@vegaprotocol/graphql';
import { useOrderSubmit } from '../../hooks/use-order-submit';
import { useEffect, useState } from 'react';
import { VegaTxStatus } from '../../hooks/use-vega-transaction';
import { Dialog, Intent } from '@vegaprotocol/ui-toolkit';
import { OrderStatus } from '@vegaprotocol/types';
import { VegaTxStatus } from '@vegaprotocol/wallet';
import { DealTicket } from './deal-ticket';
import { useOrderSubmit } from './use-order-submit';
import { OrderDialog } from './order-dialog';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
interface DealTicketContainerProps {
market: Market_market;
interface DealTicketManagerProps {
market: DealTicketQuery_market;
}
export const DealTicketContainer = ({ market }: DealTicketContainerProps) => {
export const DealTicketManager = ({ market }: DealTicketManagerProps) => {
const [orderDialogOpen, setOrderDialogOpen] = useState(false);
const { submit, transaction, finalizedOrder, reset } = useOrderSubmit(market);

View File

@ -1,18 +1,18 @@
import { addDecimal } from '@vegaprotocol/react-helpers';
import { FormGroup, Input } from '@vegaprotocol/ui-toolkit';
import { Market_market } from '@vegaprotocol/graphql';
import { TransactionStatus } from './deal-ticket';
import type { TransactionStatus } from './deal-ticket';
import { SideSelector } from './side-selector';
import { SubmitButton } from './submit-button';
import { TimeInForceSelector } from './time-in-force-selector';
import { TypeSelector } from './type-selector';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
interface DealTicketMarketProps {
order: Order;
updateOrder: (order: Partial<Order>) => void;
transactionStatus: TransactionStatus;
market: Market_market;
market: DealTicketQuery_market;
}
export const DealTicketMarket = ({

View File

@ -6,8 +6,10 @@ import {
} from '@vegaprotocol/wallet';
import { addDecimal } from '@vegaprotocol/react-helpers';
import { fireEvent, render, screen } from '@testing-library/react';
import { DealTicket, Market } from './deal-ticket';
import { Order } from './use-order-state';
import { DealTicket } from './deal-ticket';
import type { Order } from './use-order-state';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
const order: Order = {
type: OrderType.Market,
@ -15,34 +17,42 @@ const order: Order = {
timeInForce: OrderTimeInForce.FOK,
side: null,
};
const market: Market = {
const market: DealTicketQuery_market = {
__typename: 'Market',
id: 'market-id',
decimalPlaces: 2,
tradingMode: 'Continuous',
state: 'Active',
tradingMode: MarketTradingMode.Continuous,
state: MarketState.Active,
tradableInstrument: {
__typename: 'TradableInstrument',
instrument: {
__typename: 'Instrument',
product: {
__typename: 'Future',
quoteName: 'quote-name',
settlementAsset: {
id: 'asset-id',
symbol: 'asset-symbol',
name: 'asset-name',
},
},
},
},
depth: {
__typename: 'MarketDepth',
lastTrade: {
__typename: 'Trade',
price: '100',
},
},
};
const submit = jest.fn();
const transactionStatus = 'default';
function generateJsx() {
return (
<VegaWalletContext.Provider value={{} as any}>
<DealTicket defaultOrder={order} market={market} />
<DealTicket
defaultOrder={order}
market={market}
submit={submit}
transactionStatus={transactionStatus}
/>
</VegaWalletContext.Provider>
);
}

View File

@ -1,9 +1,10 @@
import type { FormEvent } from 'react';
import { OrderSide, OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { Market_market } from '@vegaprotocol/graphql';
import { FormEvent } from 'react';
import { Order, useOrderState } from './use-order-state';
import type { Order } from './use-order-state';
import { useOrderState } from './use-order-state';
import { DealTicketMarket } from './deal-ticket-market';
import { DealTicketLimit } from './deal-ticket-limit';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
const DEFAULT_ORDER: Order = {
type: OrderType.Market,
@ -15,7 +16,7 @@ const DEFAULT_ORDER: Order = {
export type TransactionStatus = 'default' | 'pending';
export interface DealTicketProps {
market: Market_market;
market: DealTicketQuery_market;
submit: (order: Order) => void;
transactionStatus: TransactionStatus;
defaultOrder?: Order;

View File

@ -1,5 +1,5 @@
import { FormGroup, Input } from '@vegaprotocol/ui-toolkit';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
import { formatForInput } from '@vegaprotocol/react-helpers';
interface ExpirySelectorProps {

View File

@ -1,2 +1,3 @@
export * from './deal-ticket';
export * from './use-order-state';
export * from './deal-ticket-container';

View File

@ -1,11 +1,9 @@
import { Icon, Loader } from '@vegaprotocol/ui-toolkit';
import { ReactNode } from 'react';
import {
TransactionState,
VegaTxStatus,
} from '../../hooks/use-vega-transaction';
import { OrderEvent_busEvents_event_Order } from '@vegaprotocol/graphql';
import type { ReactNode } from 'react';
import type { OrderEvent_busEvents_event_Order } from './__generated__/OrderEvent';
import { formatNumber } from '@vegaprotocol/react-helpers';
import type { TransactionState } from '@vegaprotocol/wallet';
import { VegaTxStatus } from '@vegaprotocol/wallet';
interface OrderDialogProps {
transaction: TransactionState;

View File

@ -1,7 +1,7 @@
import { FormGroup } from '@vegaprotocol/ui-toolkit';
import { OrderSide } from '@vegaprotocol/wallet';
import { ButtonRadio } from './button-radio';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
interface SideSelectorProps {
order: Order;

View File

@ -1,14 +1,15 @@
import { Button, InputError } from '@vegaprotocol/ui-toolkit';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { Market_market } from '@vegaprotocol/graphql';
import { useMemo } from 'react';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { TransactionStatus } from './deal-ticket';
import type { TransactionStatus } from './deal-ticket';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
interface SubmitButtonProps {
transactionStatus: TransactionStatus;
market: Market_market;
market: DealTicketQuery_market;
order: Order;
}
@ -28,20 +29,22 @@ export const SubmitButton = ({
return 'Selected public key has been tainted';
}
// TODO: Change these to use enums from @vegaprotocol/graphql
if (market.state !== 'Active') {
if (market.state === 'Suspended') {
if (market.state !== MarketState.Active) {
if (market.state === MarketState.Suspended) {
return 'Market is currently suspended';
}
if (market.state === 'Proposed' || market.state === 'Pending') {
if (
market.state === MarketState.Proposed ||
market.state === MarketState.Pending
) {
return 'Market is not active yet';
}
return 'Market is no longer active';
}
if (market.tradingMode !== 'Continuous') {
if (market.tradingMode !== MarketTradingMode.Continuous) {
if (order.type === OrderType.Market) {
return 'Only limit orders are permitted when market is in auction';
}

View File

@ -1,6 +1,6 @@
import { FormGroup, Select } from '@vegaprotocol/ui-toolkit';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
interface TimeInForceSelectorProps {
order: Order;

View File

@ -1,7 +1,7 @@
import { FormGroup } from '@vegaprotocol/ui-toolkit';
import { OrderType } from '@vegaprotocol/wallet';
import { ButtonRadio } from './button-radio';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
interface TypeSelectorProps {
order: Order;

View File

@ -1,4 +1,5 @@
import { OrderSide, OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import type { OrderSide } from '@vegaprotocol/wallet';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { useState, useCallback } from 'react';
export interface Order {

View File

@ -1,15 +1,14 @@
import { MockedProvider } from '@apollo/client/testing';
import { act, renderHook } from '@testing-library/react-hooks';
import { Order } from '@vegaprotocol/deal-ticket';
import {
import type { Order } from './use-order-state';
import type {
VegaKeyExtended,
VegaWalletContext,
VegaWalletContextShape,
} from '@vegaprotocol/wallet';
import { VegaTxStatus, VegaWalletContext } from '@vegaprotocol/wallet';
import { OrderSide, OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { ReactNode } from 'react';
import type { ReactNode } from 'react';
import { useOrderSubmit } from './use-order-submit';
import { VegaTxStatus } from './use-vega-transaction';
const defaultWalletContext = {
keypair: null,

View File

@ -2,15 +2,15 @@ import { useCallback, useEffect, useState } from 'react';
import { gql, useSubscription } from '@apollo/client';
import { ethers } from 'ethers';
import { SHA3 } from 'sha3';
import { Order } from '@vegaprotocol/deal-ticket';
import type { Order } from './use-order-state';
import { OrderType, useVegaWallet } from '@vegaprotocol/wallet';
import { useVegaTransaction } from './use-vega-transaction';
import {
import { removeDecimal } from '@vegaprotocol/react-helpers';
import { useVegaTransaction } from '@vegaprotocol/wallet';
import type {
OrderEvent,
OrderEventVariables,
OrderEvent_busEvents_event_Order,
} from '@vegaprotocol/graphql';
import { removeDecimal } from '@vegaprotocol/react-helpers';
} from './__generated__/OrderEvent';
const ORDER_EVENT_SUB = gql`
subscription OrderEvent($partyId: ID!) {

View File

@ -1,7 +0,0 @@
# graphql
This library was generated with [Nx](https://nx.dev).
## Running unit tests
Run `nx test graphql` to execute the unit tests via [Jest](https://jestjs.io).

View File

@ -1,4 +0,0 @@
{
"name": "@vegaprotocol/graphql",
"version": "0.0.1"
}

View File

@ -1,3 +0,0 @@
export * from './markets-data-provider';
export * from './positions-data-provider';
export type { Subscribe } from './generic-data-provider';

View File

@ -1,21 +0,0 @@
export * from './__generated__/AssetsQuery';
export * from './__generated__/globalTypes';
export * from './__generated__/Guess';
export * from './__generated__/Market';
export * from './__generated__/MarketDataFields';
export * from './__generated__/MarketDataSub';
export * from './__generated__/Markets';
export * from './__generated__/MarketsQuery';
export * from './__generated__/NetworkParametersQuery';
export * from './__generated__/NodesQuery';
export * from './__generated__/OrderEvent';
export * from './__generated__/OrderFields';
export * from './__generated__/Orders';
export * from './__generated__/OrderSub';
export * from './__generated__/PartyAssetsQuery';
export * from './__generated__/PositionDetails';
export * from './__generated__/Positions';
export * from './__generated__/PositionSubscribe';
export * from './__generated__/ProposalsQuery';
export * from './data-providers';

View File

@ -1,6 +1,6 @@
{
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

@ -1 +1,2 @@
export * from './lib/market-list-table';
export * from './lib/markets-container';

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes";
import { MarketState, MarketTradingMode } from "./../../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL fragment: MarketDataFields

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes";
import { MarketState, MarketTradingMode } from "./../../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL subscription operation: MarketDataSub

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes";
import { MarketState, MarketTradingMode } from "./../../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: Markets

View File

@ -2,7 +2,7 @@ import { forwardRef } from 'react';
import type { ValueFormatterParams } from 'ag-grid-community';
import { PriceCell, formatNumber } from '@vegaprotocol/react-helpers';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/ui-toolkit';
import { Markets_markets } from '@vegaprotocol/graphql';
import type { Markets_markets } from './__generated__/Markets';
import { AgGridColumn } from 'ag-grid-react';
import type { AgGridReact } from 'ag-grid-react';

View File

@ -0,0 +1,67 @@
import { useRef, useCallback } from 'react';
import { produce } from 'immer';
import merge from 'lodash/merge';
import { useRouter } from 'next/router';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import { MarketListTable, getRowNodeId } from './market-list-table';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import type { AgGridReact } from 'ag-grid-react';
import type {
Markets_markets,
Markets_markets_data,
} from './__generated__/Markets';
import { marketsDataProvider } from './markets-data-provider';
export const MarketsContainer = () => {
const { pathname, push } = useRouter();
const gridRef = useRef<AgGridReact | null>(null);
const update = useCallback(
(delta: Markets_markets_data) => {
const update: Markets_markets[] = [];
const add: Markets_markets[] = [];
if (!gridRef.current) {
return false;
}
const rowNode = gridRef.current.api.getRowNode(
getRowNodeId(delta.market)
);
if (rowNode) {
const updatedData = produce<Markets_markets_data>(
rowNode.data.data,
(draft: Markets_markets_data) => merge(draft, delta)
);
if (updatedData !== rowNode.data.data) {
update.push({ ...rowNode.data, data: updatedData });
}
}
// @TODO - else add new market
if (update.length || add.length) {
gridRef.current.api.applyTransactionAsync({
update,
add,
addIndex: 0,
});
}
return true;
},
[gridRef]
);
const { data, error, loading } = useDataProvider<
Markets_markets,
Markets_markets_data
>(marketsDataProvider, update);
return (
<AsyncRenderer loading={loading} error={error} data={data}>
{(data) => (
<MarketListTable
ref={gridRef}
data={data}
onRowClicked={(id) =>
push(`${pathname}/${id}?portfolio=orders&trade=orderbook`)
}
/>
)}
</AsyncRenderer>
);
};

View File

@ -1,11 +1,11 @@
import { gql } from '@apollo/client';
import { Markets, Markets_markets } from '../__generated__/Markets';
import { makeDataProvider } from './generic-data-provider';
import type { Markets, Markets_markets } from './__generated__/Markets';
import { makeDataProvider } from '@vegaprotocol/react-helpers';
import {
import type {
MarketDataSub,
MarketDataSub_marketData,
} from '../__generated__/MarketDataSub';
} from './__generated__/MarketDataSub';
const MARKET_DATA_FRAGMENT = gql`
fragment MarketDataFields on MarketData {

View File

@ -1,4 +1,4 @@
import { value, goodThreshold } from '../../config/types';
import type { value, goodThreshold } from '../../config/types';
interface GoodThresholdIndicatorProps {
goodThreshold: goodThreshold | undefined;

View File

@ -1,5 +1,5 @@
import { Tooltip } from '../tooltip';
import { StatFields } from '../../config/types';
import type { StatFields } from '../../config/types';
import { defaultFieldFormatter } from '../table-row';
import { GoodThresholdIndicator } from '../good-threshold-indicator';

View File

@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import classnames from 'classnames';
import { statsFields } from '../../config/stats-fields';
import {
import type {
Stats as IStats,
StructuredStats as IStructuredStats,
} from '../../config/types';

View File

@ -1,5 +1,5 @@
import { Tooltip } from '../tooltip';
import { StatFields } from '../../config/types';
import type { StatFields } from '../../config/types';
import { GoodThresholdIndicator } from '../good-threshold-indicator';
export const defaultFieldFormatter = (field: unknown) =>

View File

@ -1,4 +1,4 @@
import { Stats as IStats, StatFields as IStatFields } from './types';
import type { Stats as IStats, StatFields as IStatFields } from './types';
// Stats fields config. Keys will correspond to graphql queries when used, and values
// contain the associated data and methods we need to render. A single query

View File

@ -1,6 +1,6 @@
{
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { OrderType, Side, OrderStatus, OrderRejectionReason, OrderTimeInForce } from "./globalTypes";
import { OrderType, Side, OrderStatus, OrderRejectionReason, OrderTimeInForce } from "./../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL fragment: OrderFields

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { OrderType, Side, OrderStatus, OrderRejectionReason, OrderTimeInForce } from "./globalTypes";
import { OrderType, Side, OrderStatus, OrderRejectionReason, OrderTimeInForce } from "./../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL subscription operation: OrderSub

View File

@ -3,7 +3,7 @@
// @generated
// This file was automatically generated and should not be edited.
import { OrderType, Side, OrderStatus, OrderRejectionReason, OrderTimeInForce } from "./globalTypes";
import { OrderType, Side, OrderStatus, OrderRejectionReason, OrderTimeInForce } from "./../../../types/src/__generated__/globalTypes";
// ====================================================
// GraphQL query operation: Orders

View File

@ -1 +1,2 @@
export * from './order-list';
export * from './order-list-container';

View File

@ -0,0 +1,13 @@
import { Splash } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { OrderListManager } from './order-list-manager';
export const OrderListContainer = () => {
const { keypair } = useVegaWallet();
if (!keypair) {
return <Splash>Please connect Vega wallet</Splash>;
}
return <OrderListManager partyId={keypair.pub} />;
};

View File

@ -1,9 +1,9 @@
import { OrderListContainer } from './order-list-container';
import * as useOrdersHook from '../../hooks/use-orders';
import { render, screen } from '@testing-library/react';
import { Orders_party_orders } from '@vegaprotocol/graphql';
import { OrderListManager } from './order-list-manager';
import * as useOrdersHook from './use-orders';
import type { Orders_party_orders } from './__generated__/Orders';
jest.mock('@vegaprotocol/order-list', () => ({
jest.mock('./order-list', () => ({
OrderList: () => <div>OrderList</div>,
}));
@ -13,7 +13,7 @@ test('Renders a loading state while awaiting orders', () => {
loading: true,
error: null,
});
render(<OrderListContainer />);
render(<OrderListManager partyId="0x123" />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
@ -24,18 +24,18 @@ test('Renders an error state', () => {
loading: false,
error: new Error(errorMsg),
});
render(<OrderListContainer />);
render(<OrderListManager partyId="0x123" />);
expect(
screen.getByText(`Something went wrong: ${errorMsg}`)
).toBeInTheDocument();
});
test('Renders the order list if orders provided', () => {
test('Renders the order list if orders provided', async () => {
jest.spyOn(useOrdersHook, 'useOrders').mockReturnValue({
orders: [{ id: '1' } as Orders_party_orders],
loading: false,
error: null,
});
render(<OrderListContainer />);
expect(screen.getByText('OrderList')).toBeInTheDocument();
render(<OrderListManager partyId="0x123" />);
expect(await screen.findByText('OrderList')).toBeInTheDocument();
});

View File

@ -0,0 +1,18 @@
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import { useOrders } from './use-orders';
import { OrderList } from './order-list';
import type { OrderFields } from './__generated__/OrderFields';
interface OrderListManagerProps {
partyId: string;
}
export const OrderListManager = ({ partyId }: OrderListManagerProps) => {
const { orders, loading, error } = useOrders(partyId);
return (
<AsyncRenderer<OrderFields[]> loading={loading} error={error} data={orders}>
{(data) => <OrderList orders={data} />}
</AsyncRenderer>
);
};

View File

@ -1,13 +1,13 @@
import { act, render, screen } from '@testing-library/react';
import { formatNumber, getDateTimeFormat } from '@vegaprotocol/react-helpers';
import { Orders_party_orders } from '@vegaprotocol/graphql';
import type { Orders_party_orders } from './__generated__/Orders';
import {
OrderStatus,
OrderTimeInForce,
OrderType,
Side,
OrderRejectionReason,
} from '@vegaprotocol/graphql';
} from '@vegaprotocol/types';
import { OrderList } from './order-list';
test('No orders message shown', async () => {

View File

@ -1,16 +1,12 @@
import {
Orders_party_orders,
OrderTimeInForce,
OrderStatus,
Side,
} from '@vegaprotocol/graphql';
import { OrderTimeInForce, OrderStatus, Side } from '@vegaprotocol/types';
import type { Orders_party_orders } from './__generated__/Orders';
import {
formatNumber,
getDateTimeFormat,
useApplyGridTransaction,
} from '@vegaprotocol/react-helpers';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/ui-toolkit';
import { GridApi, ValueFormatterParams } from 'ag-grid-community';
import type { GridApi, ValueFormatterParams } from 'ag-grid-community';
import { AgGridColumn } from 'ag-grid-react';
import { useRef, useState } from 'react';

View File

@ -1,32 +1,20 @@
import { MockedProvider, MockedResponse } from '@apollo/client/testing';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import { renderHook } from '@testing-library/react-hooks';
import type { OrderFields } from './__generated__/OrderFields';
import type { Orders } from './__generated__/Orders';
import type { OrderSub } from './__generated__/OrderSub';
import {
OrderFields,
Orders,
OrderStatus,
OrderSub,
OrderTimeInForce,
OrderType,
Side,
} from '@vegaprotocol/graphql';
import {
VegaKeyExtended,
VegaWalletContext,
VegaWalletContextShape,
} from '@vegaprotocol/wallet';
import { ReactNode } from 'react';
OrderType,
OrderTimeInForce,
} from '@vegaprotocol/types';
import {} from '@vegaprotocol/wallet';
import type { ReactNode } from 'react';
import { ORDERS_QUERY, ORDERS_SUB, useOrders } from './use-orders';
const keypair = { pub: '0x123' } as VegaKeyExtended;
const defaultWalletContext = {
keypair,
keypairs: [keypair],
sendTx: jest.fn().mockReturnValue(Promise.resolve(null)),
connect: jest.fn(),
disconnect: jest.fn(),
selectPublicKey: jest.fn(),
connector: null,
};
const partyId = '0x123';
function generateOrder(order?: Partial<OrderFields>): OrderFields {
return {
@ -60,20 +48,11 @@ function generateOrder(order?: Partial<OrderFields>): OrderFields {
};
}
function setup(
context?: Partial<VegaWalletContextShape>,
mocks: MockedResponse[] = []
) {
function setup(mocks: MockedResponse[] = [], id: string | null) {
const wrapper = ({ children }: { children: ReactNode }) => (
<MockedProvider mocks={mocks}>
<VegaWalletContext.Provider
value={{ ...defaultWalletContext, ...context }}
>
{children}
</VegaWalletContext.Provider>
</MockedProvider>
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
return renderHook(() => useOrders(), { wrapper });
return renderHook(() => useOrders(id as string), { wrapper });
}
test('Fetches and subscribes to orders and merges appropriately', async () => {
@ -81,13 +60,13 @@ test('Fetches and subscribes to orders and merges appropriately', async () => {
const mockOrderQuery: MockedResponse<Orders> = {
request: {
query: ORDERS_QUERY,
variables: { partyId: keypair.pub },
variables: { partyId },
},
result: {
data: {
party: {
__typename: 'Party',
id: keypair.pub,
id: partyId,
orders: [order],
},
},
@ -106,7 +85,7 @@ test('Fetches and subscribes to orders and merges appropriately', async () => {
const mockOrderSub: MockedResponse<OrderSub> = {
request: {
query: ORDERS_SUB,
variables: { partyId: keypair.pub },
variables: { partyId },
},
result: {
data: {
@ -115,10 +94,10 @@ test('Fetches and subscribes to orders and merges appropriately', async () => {
},
delay: 100,
};
const { result, waitForNextUpdate } = setup(defaultWalletContext, [
mockOrderQuery,
mockOrderSub,
]);
const { result, waitForNextUpdate } = setup(
[mockOrderQuery, mockOrderSub],
partyId
);
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(null);
await waitForNextUpdate();
@ -133,13 +112,11 @@ test('Returns an error if fetch fails', async () => {
const mockFailedOrderQuery: MockedResponse<Orders> = {
request: {
query: ORDERS_QUERY,
variables: { partyId: keypair.pub },
variables: { partyId },
},
error,
};
const { result, waitForNextUpdate } = setup(defaultWalletContext, [
mockFailedOrderQuery,
]);
const { result, waitForNextUpdate } = setup([mockFailedOrderQuery], partyId);
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(null);
await waitForNextUpdate();
@ -151,14 +128,11 @@ test('No queries are made if no pubkey provided', () => {
const mockQuery: MockedResponse<Orders> = {
request: {
query: ORDERS_QUERY,
variables: { partyId: keypair.pub },
variables: { partyId },
},
newData: jest.fn(),
};
const { result } = setup(
{ ...defaultWalletContext, keypair: null, keypairs: [] },
[mockQuery]
);
const { result } = setup([mockQuery], null);
expect(mockQuery.newData).not.toBeCalled();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(null);

View File

@ -1,15 +1,10 @@
import { gql, useApolloClient } from '@apollo/client';
import { useCallback, useEffect, useState } from 'react';
import {
OrderSub,
OrderSubVariables,
Orders,
OrdersVariables,
OrderFields,
} from '@vegaprotocol/graphql';
import { gql, useApolloClient } from '@apollo/client';
import uniqBy from 'lodash/uniqBy';
import orderBy from 'lodash/orderBy';
import { useVegaWallet } from '@vegaprotocol/wallet';
import type { Orders, OrdersVariables } from './__generated__/Orders';
import type { OrderSub, OrderSubVariables } from './__generated__/OrderSub';
import type { OrderFields } from './__generated__/OrderFields';
const ORDER_FRAGMENT = gql`
fragment OrderFields on Order {
@ -65,9 +60,8 @@ interface UseOrders {
loading: boolean;
}
export const useOrders = (): UseOrders => {
export const useOrders = (partyId: string): UseOrders => {
const client = useApolloClient();
const { keypair } = useVegaWallet();
const [orders, setOrders] = useState<OrderFields[]>([]);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(false);
@ -93,14 +87,14 @@ export const useOrders = (): UseOrders => {
// Make initial fetch
useEffect(() => {
const fetchOrders = async () => {
if (!keypair?.pub) return;
if (!partyId) return;
setLoading(true);
try {
const res = await client.query<Orders, OrdersVariables>({
query: ORDERS_QUERY,
variables: { partyId: keypair.pub },
variables: { partyId },
});
if (!res.data.party?.orders?.length) return;
@ -116,16 +110,16 @@ export const useOrders = (): UseOrders => {
};
fetchOrders();
}, [mergeOrders, keypair, client]);
}, [mergeOrders, partyId, client]);
// Start subscription
useEffect(() => {
if (!keypair?.pub) return;
if (!partyId) return;
const sub = client
.subscribe<OrderSub, OrderSubVariables>({
query: ORDERS_SUB,
variables: { partyId: keypair.pub },
variables: { partyId },
})
.subscribe(({ data }) => {
if (!data?.orders) {
@ -139,7 +133,7 @@ export const useOrders = (): UseOrders => {
sub.unsubscribe();
}
};
}, [client, keypair, mergeOrders]);
}, [client, partyId, mergeOrders]);
return { orders, error, loading };
};

View File

@ -1,6 +1,6 @@
{
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

@ -1 +1,3 @@
export * from './lib/positions-table';
export * from './lib/positions-container';
export * from './lib/positions-data-provider';

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