Resolved merge conflicts with master, reduced warnings

This commit is contained in:
sam-keen 2022-03-31 14:20:36 +01:00
commit b6df83ede8
190 changed files with 961 additions and 1065 deletions

View File

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

View File

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

View File

@ -1,16 +0,0 @@
# App configuration variables
NX_CHAIN_EXPLORER_URL = "https://explorer.vega.trading/.netlify/functions/chain-explorer-api"
NX_TENDERMINT_URL = "https://lb.testnet.vega.xyz/tm"
NX_TENDERMINT_WEBSOCKET_URL = "wss://lb.testnet.vega.xyz/tm/websocket"
NX_VEGA_URL = "https://lb.testnet.vega.xyz/query"
NX_VEGA_ENV = 'Testnet'
NX_VEGA_REST = 'https://lb.testnet.vega.xyz/datanode/rest'
# App flags
NX_EXPLORER_ASSETS = 1
NX_EXPLORER_GENESIS = 1
NX_EXPLORER_GOVERNANCE = 1
NX_EXPLORER_MARKETS = 1
NX_EXPLORER_NETWORK_PARAMETERS = 1
NX_EXPLORER_PARTIES = 1
NX_EXPLORER_VALIDATORS = 1

View File

@ -1,6 +1,6 @@
{ {
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"], "extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"], "ignorePatterns": ["!**/*", "__generated__"],
"overrides": [ "overrides": [
{ {
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "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,9 +1,10 @@
import React from 'react'; 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 { Routes } from '../../routes/router-config';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { SecondsAgo } from '../seconds-ago'; import { SecondsAgo } from '../seconds-ago';
import { TableWithTbody, TableRow, TableCell } from '../table'; import { TableWithTbody, TableRow, TableCell } from '../table';
import { t } from '@vegaprotocol/react-helpers';
interface BlockProps { interface BlockProps {
block: BlockMeta; block: BlockMeta;
@ -20,7 +21,7 @@ export const BlockData = ({ block, className }: BlockProps) => {
<TableCell <TableCell
data-testid="block-height" data-testid="block-height"
className="pl-4 py-2 font-mono" className="pl-4 py-2 font-mono"
aria-label="Block height" aria-label={t('Block height')}
> >
<Link <Link
to={`/${Routes.BLOCKS}/${block.header?.height}`} to={`/${Routes.BLOCKS}/${block.header?.height}`}
@ -32,16 +33,16 @@ export const BlockData = ({ block, className }: BlockProps) => {
<TableCell <TableCell
data-testid="num-txs" data-testid="num-txs"
className="px-8 text-center" className="px-8 text-center"
aria-label="Number of transactions" aria-label={t('Number of transactions')}
> >
{block.num_txs === '1' {block.num_txs === '1'
? '1 transaction' ? t('1 transaction')
: `${block.num_txs} transactions`} : t(`${block.num_txs} transactions`)}
</TableCell> </TableCell>
<TableCell <TableCell
data-testid="validator-link" data-testid="validator-link"
className="px-8 text-center font-mono" className="px-8 text-center font-mono"
aria-label="Validator" aria-label={t('Validator')}
> >
<Link to={`/${Routes.VALIDATORS}`}> <Link to={`/${Routes.VALIDATORS}`}>
{block.header.proposer_address} {block.header.proposer_address}
@ -50,7 +51,7 @@ export const BlockData = ({ block, className }: BlockProps) => {
<TableCell <TableCell
data-testid="block-time" data-testid="block-time"
className="text-center pr-28 text-neutral-300 w-[170px]" className="text-center pr-28 text-neutral-300 w-[170px]"
aria-label="Block genesis" aria-label={t('Block genesis')}
> >
<SecondsAgo date={block.header?.time} /> <SecondsAgo date={block.header?.time} />
</TableCell> </TableCell>

View File

@ -1,5 +1,6 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; 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'; import { BlockData } from './block-data';
interface BlocksProps { interface BlocksProps {
@ -9,12 +10,14 @@ interface BlocksProps {
export const BlocksData = ({ data, className }: BlocksProps) => { export const BlocksData = ({ data, className }: BlocksProps) => {
if (!data?.result) { if (!data?.result) {
return <div className={className}>Awaiting block data</div>; return <div className={className}>{t('Awaiting block data')}</div>;
} }
return ( return (
<ul <ul
aria-label={`Showing ${data.result?.block_metas.length} most recently loaded blocks`} aria-label={t(
`Showing ${data.result?.block_metas.length} most recently loaded blocks`
)}
className={className} className={className}
> >
{data.result?.block_metas?.map((block, index) => { {data.result?.block_metas?.map((block, index) => {

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { Button } from '@vegaprotocol/ui-toolkit'; import { Button } from '@vegaprotocol/ui-toolkit';
interface BlocksRefetchProps { interface BlocksRefetchProps {
@ -12,7 +13,7 @@ export const BlocksRefetch = ({ refetch }: BlocksRefetchProps) => {
className="mb-28" className="mb-28"
data-testid="refresh" data-testid="refresh"
> >
Refresh to see latest blocks {t('Refresh to see latest blocks')}
</Button> </Button>
); );
}; };

View File

@ -1,4 +1,5 @@
import { ThemeSwitcher } from '@vegaprotocol/ui-toolkit'; import { ThemeSwitcher } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/react-helpers';
import { Search } from '../search'; import { Search } from '../search';
interface ThemeToggleProps { interface ThemeToggleProps {
@ -12,7 +13,7 @@ export const Header = ({ toggleTheme }: ThemeToggleProps) => {
className="text-h3 font-alpha uppercase calt" className="text-h3 font-alpha uppercase calt"
data-testid="explorer-header" data-testid="explorer-header"
> >
Vega Explorer {t('Vega Explorer')}
</h1> </h1>
<Search /> <Search />
<ThemeSwitcher onToggle={toggleTheme} /> <ThemeSwitcher onToggle={toggleTheme} />

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; import React from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Routes } from '../../routes/router-config'; import { Routes } from '../../routes/router-config';
@ -22,8 +23,8 @@ export const JumpToBlock = () => {
return ( return (
<JumpTo <JumpTo
label="Jump to block" label={t('Jump to block')}
placeholder="Block number" placeholder={t('Block number')}
inputId="block-input" inputId="block-input"
inputType="number" inputType="number"
inputName="blockNumber" inputName="blockNumber"

View File

@ -1,5 +1,6 @@
import { HTMLInputTypeAttribute, SyntheticEvent } from 'react'; import type { HTMLInputTypeAttribute, SyntheticEvent } from 'react';
import { Input, Button } from '@vegaprotocol/ui-toolkit'; import { Input, Button } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/react-helpers';
interface JumpToProps { interface JumpToProps {
label: string; label: string;
@ -35,7 +36,7 @@ export const JumpTo = ({
className="max-w-[200px]" className="max-w-[200px]"
/> />
<Button variant="secondary" type="submit"> <Button variant="secondary" type="submit">
Go {t('Go')}
</Button> </Button>
</div> </div>
</form> </form>

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; import React from 'react';
import { StatusMessage } from '../status-message'; import { StatusMessage } from '../status-message';
@ -15,12 +16,16 @@ export const RenderFetched = ({
className, className,
}: RenderFetchedProps) => { }: RenderFetchedProps) => {
if (loading) { if (loading) {
return <StatusMessage className={className}>Loading...</StatusMessage>; return (
<StatusMessage className={className}>{t('Loading...')}</StatusMessage>
);
} }
if (error) { if (error) {
return ( return (
<StatusMessage className={className}>Error retrieving data</StatusMessage> <StatusMessage className={className}>
{t('Error retrieving data')}
</StatusMessage>
); );
} }

View File

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

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; import React from 'react';
interface RouteErrorBoundaryProps { interface RouteErrorBoundaryProps {
@ -23,7 +24,7 @@ export class RouteErrorBoundary extends React.Component<
override render() { override render() {
if (this.state.hasError) { if (this.state.hasError) {
return <h1>Something went wrong</h1>; return <h1>{t('Something went wrong')}</h1>;
} }
return this.props.children; return this.props.children;

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { FormGroup, Input, InputError, Button } from '@vegaprotocol/ui-toolkit'; import { FormGroup, Input, InputError, Button } from '@vegaprotocol/ui-toolkit';
import React from 'react'; import React from 'react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
@ -28,23 +29,23 @@ export const Search = () => {
const search = fields.search; const search = fields.search;
if (!search) { if (!search) {
setError(new Error('Search required')); setError(new Error(t('Search required')));
} else if (isPrependedTransaction(search)) { } else if (isPrependedTransaction(search)) {
if (Number.isNaN(Number(search))) { if (Number.isNaN(Number(search))) {
setError(new Error('Transaction is not hexadecimal')); setError(new Error(t('Transaction is not hexadecimal')));
} else { } else {
navigate(`${Routes.TX}/${search}`); navigate(`${Routes.TX}/${search}`);
} }
} else if (isTransaction(search)) { } else if (isTransaction(search)) {
if (Number.isNaN(Number(`0x${search}`))) { if (Number.isNaN(Number(`0x${search}`))) {
setError(new Error('Transaction is not hexadecimal')); setError(new Error(t('Transaction is not hexadecimal')));
} else { } else {
navigate(`${Routes.TX}/0x${search}`); navigate(`${Routes.TX}/0x${search}`);
} }
} else if (isBlock(search)) { } else if (isBlock(search)) {
navigate(`${Routes.BLOCKS}/${Number(search)}`); navigate(`${Routes.BLOCKS}/${Number(search)}`);
} else { } else {
setError(new Error("Something doesn't look right")); setError(new Error(t("Something doesn't look right")));
} }
}, },
[navigate] [navigate]
@ -62,7 +63,7 @@ export const Search = () => {
hasError={Boolean(error?.message)} hasError={Boolean(error?.message)}
type="text" type="text"
autoFocus={true} autoFocus={true}
placeholder="Enter block number or transaction hash" placeholder={t('Enter block number or transaction hash')}
/> />
{error?.message && ( {error?.message && (
<InputError <InputError
@ -75,7 +76,7 @@ export const Search = () => {
)} )}
</FormGroup> </FormGroup>
<Button type="submit" variant="secondary" data-testid="search-button"> <Button type="submit" variant="secondary" data-testid="search-button">
Search {t('Search')}
</Button> </Button>
</form> </form>
); );

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
interface SecondsAgoProps { interface SecondsAgoProps {
@ -15,15 +16,18 @@ export const SecondsAgo = ({ date, ...props }: SecondsAgoProps) => {
}, [setNow]); }, [setNow]);
if (!date) { if (!date) {
return <>Date unknown</>; return <>{t('Date unknown')}</>;
} }
const timeAgoInSeconds = Math.floor((now - new Date(date).getTime()) / 1000); const timeAgoInSeconds = Math.floor((now - new Date(date).getTime()) / 1000);
return ( return (
<div {...props}> <div {...props}>
{timeAgoInSeconds === 1 ? '1 second' : `${timeAgoInSeconds} seconds`} ago {t(
`${
timeAgoInSeconds === 1 ? '1 second' : `${timeAgoInSeconds} seconds`
} ago`
)}
</div> </div>
); );
}; };

View File

@ -1,5 +1,5 @@
import classnames from 'classnames'; import classnames from 'classnames';
import { HTMLAttributes } from 'react'; import type { HTMLAttributes } from 'react';
interface SubHeadingProps extends HTMLAttributes<HTMLHeadingElement> { interface SubHeadingProps extends HTMLAttributes<HTMLHeadingElement> {
children: React.ReactNode; 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'; import classnames from 'classnames';
interface TableProps extends ThHTMLAttributes<HTMLTableElement> { interface TableProps extends ThHTMLAttributes<HTMLTableElement> {

View File

@ -1,5 +1,6 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; 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 { BlockData } from '../blocks';
import { TxsPerBlock } from './txs-per-block'; import { TxsPerBlock } from './txs-per-block';
@ -13,12 +14,14 @@ export const BlockTxsData = ({ data, className }: TxsProps) => {
// Data for the block has already been fetched at this point, so no errors // Data for the block has already been fetched at this point, so no errors
// or loading to deal with. This is specifically the case // or loading to deal with. This is specifically the case
// where the data object is not undefined, but lacks a result. // where the data object is not undefined, but lacks a result.
return <div className={className}>No data</div>; return <div className={className}>{t('No data')}</div>;
} }
return ( return (
<ul <ul
aria-label={`Showing ${data.result?.block_metas.length} most recently loaded blocks and transactions`} aria-label={t(
`Showing ${data.result?.block_metas.length} most recently loaded blocks and transactions`
)}
className={className} className={className}
> >
{data.result?.block_metas?.map((block, index) => { {data.result?.block_metas?.map((block, index) => {

View File

@ -1,4 +1,5 @@
import { TendermintUnconfirmedTransactionsResponse } from '../../routes/txs/tendermint-unconfirmed-transactions-response.d'; import { t } from '@vegaprotocol/react-helpers';
import type { TendermintUnconfirmedTransactionsResponse } from '../../routes/txs/tendermint-unconfirmed-transactions-response.d';
interface TxsProps { interface TxsProps {
data: TendermintUnconfirmedTransactionsResponse | undefined; data: TendermintUnconfirmedTransactionsResponse | undefined;
@ -6,7 +7,7 @@ interface TxsProps {
export const TxList = ({ data }: TxsProps) => { export const TxList = ({ data }: TxsProps) => {
if (!data) { if (!data) {
return <div>Awaiting transactions</div>; return <div>{t('Awaiting transactions')}</div>;
} }
return <div>{JSON.stringify(data, null, ' ')}</div>; return <div>{JSON.stringify(data, null, ' ')}</div>;

View File

@ -1,11 +1,12 @@
import useFetch from '../../hooks/use-fetch'; 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 { Routes } from '../../routes/router-config';
import { DATA_SOURCES } from '../../config'; import { DATA_SOURCES } from '../../config';
import { RenderFetched } from '../render-fetched'; import { RenderFetched } from '../render-fetched';
import { TruncatedLink } from '../truncate/truncated-link'; import { TruncatedLink } from '../truncate/truncated-link';
import { TxOrderType } from './tx-order-type'; import { TxOrderType } from './tx-order-type';
import { Table, TableRow, TableCell } from '../table'; import { Table, TableRow, TableCell } from '../table';
import { t } from '@vegaprotocol/react-helpers';
interface TxsPerBlockProps { interface TxsPerBlockProps {
blockHeight: string | undefined; blockHeight: string | undefined;
@ -36,9 +37,9 @@ export const TxsPerBlock = ({ blockHeight }: TxsPerBlockProps) => {
<Table> <Table>
<thead> <thead>
<TableRow modifier="bordered" className="font-mono"> <TableRow modifier="bordered" className="font-mono">
<td>Transaction</td> <td>{t('Transaction')}</td>
<td>From</td> <td>{t('From')}</td>
<td>Type</td> <td>{t('Type')}</td>
</TableRow> </TableRow>
</thead> </thead>
<tbody> <tbody>
@ -76,7 +77,7 @@ export const TxsPerBlock = ({ blockHeight }: TxsPerBlockProps) => {
</div> </div>
) : ( ) : (
<div className="font-mono mb-28"> <div className="font-mono mb-28">
No transactions in block {blockHeight} {t(`No transactions in block ${blockHeight}`)}
</div> </div>
)} )}
</RenderFetched> </RenderFetched>

View File

@ -1,5 +1,5 @@
import React from 'react'; 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; export type WebsocketContextShape = WebSocketHook;

View File

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

View File

@ -1,9 +1,10 @@
import { gql, useQuery } from '@apollo/client'; import { gql, useQuery } from '@apollo/client';
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; import React from 'react';
import { RouteTitle } from '../../components/route-title'; import { RouteTitle } from '../../components/route-title';
import { SubHeading } from '../../components/sub-heading'; import { SubHeading } from '../../components/sub-heading';
import { SyntaxHighlighter } from '../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { AssetsQuery } from '@vegaprotocol/graphql'; import type { AssetsQuery } from './__generated__/AssetsQuery';
export const ASSETS_QUERY = gql` export const ASSETS_QUERY = gql`
query AssetsQuery { query AssetsQuery {
@ -37,7 +38,7 @@ const Assets = () => {
if (!data || !data.assets) return null; if (!data || !data.assets) return null;
return ( return (
<section> <section>
<RouteTitle data-testid="assets-header">Assets</RouteTitle> <RouteTitle data-testid="assets-header">{t('Assets')}</RouteTitle>
{data?.assets.map((a) => ( {data?.assets.map((a) => (
<React.Fragment key={a.id}> <React.Fragment key={a.id}>
<SubHeading data-testid="asset-header"> <SubHeading data-testid="asset-header">

View File

@ -1,10 +1,11 @@
import { DATA_SOURCES } from '../../../config'; import { DATA_SOURCES } from '../../../config';
import useFetch from '../../../hooks/use-fetch'; 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 { RouteTitle } from '../../../components/route-title';
import { RenderFetched } from '../../../components/render-fetched'; import { RenderFetched } from '../../../components/render-fetched';
import { BlocksData, BlocksRefetch } from '../../../components/blocks'; import { BlocksData, BlocksRefetch } from '../../../components/blocks';
import { JumpToBlock } from '../../../components/jump-to-block'; import { JumpToBlock } from '../../../components/jump-to-block';
import { t } from '@vegaprotocol/react-helpers';
const Blocks = () => { const Blocks = () => {
const { const {
@ -16,7 +17,7 @@ const Blocks = () => {
return ( return (
<section> <section>
<RouteTitle>Blocks</RouteTitle> <RouteTitle>{t('Blocks')}</RouteTitle>
<RenderFetched error={error} loading={loading}> <RenderFetched error={error} loading={loading}>
<> <>
<BlocksRefetch refetch={refetch} /> <BlocksRefetch refetch={refetch} />

View File

@ -2,7 +2,7 @@ import React from 'react';
import { Link, useParams } from 'react-router-dom'; import { Link, useParams } from 'react-router-dom';
import { DATA_SOURCES } from '../../../config'; import { DATA_SOURCES } from '../../../config';
import useFetch from '../../../hooks/use-fetch'; 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 { RouteTitle } from '../../../components/route-title';
import { SecondsAgo } from '../../../components/seconds-ago'; import { SecondsAgo } from '../../../components/seconds-ago';
import { import {
@ -16,6 +16,7 @@ import { Button } from '@vegaprotocol/ui-toolkit';
import { Routes } from '../../router-config'; import { Routes } from '../../router-config';
import { RenderFetched } from '../../../components/render-fetched'; import { RenderFetched } from '../../../components/render-fetched';
import { HighlightedLink } from '../../../components/highlighted-link'; import { HighlightedLink } from '../../../components/highlighted-link';
import { t } from '@vegaprotocol/react-helpers';
const Block = () => { const Block = () => {
const { block } = useParams<{ block: string }>(); const { block } = useParams<{ block: string }>();
@ -27,12 +28,12 @@ const Block = () => {
const header = blockData?.result.block.header; const header = blockData?.result.block.header;
if (!header) { if (!header) {
return <p>Could not get block data</p>; return <p>{t('Could not get block data')}</p>;
} }
return ( return (
<section> <section>
<RouteTitle data-testid="block-header">BLOCK {block}</RouteTitle> <RouteTitle data-testid="block-header">{t(`BLOCK ${block}`)}</RouteTitle>
<RenderFetched error={error} loading={loading}> <RenderFetched error={error} loading={loading}>
<> <>
<div className="grid grid-cols-2 gap-16"> <div className="grid grid-cols-2 gap-16">

View File

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

View File

@ -1,8 +1,9 @@
import { t } from '@vegaprotocol/react-helpers';
import { RouteTitle } from '../../components/route-title'; import { RouteTitle } from '../../components/route-title';
import { SyntaxHighlighter } from '../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { DATA_SOURCES } from '../../config'; import { DATA_SOURCES } from '../../config';
import useFetch from '../../hooks/use-fetch'; import useFetch from '../../hooks/use-fetch';
import { TendermintGenesisResponse } from './tendermint-genesis-response'; import type { TendermintGenesisResponse } from './tendermint-genesis-response';
const Genesis = () => { const Genesis = () => {
const { const {
@ -13,7 +14,7 @@ const Genesis = () => {
if (!genesis?.result.genesis) return null; if (!genesis?.result.genesis) return null;
return ( return (
<section> <section>
<RouteTitle data-testid="genesis-header">Genesis</RouteTitle> <RouteTitle data-testid="genesis-header">{t('Genesis')}</RouteTitle>
<SyntaxHighlighter data={genesis?.result.genesis} /> <SyntaxHighlighter data={genesis?.result.genesis} />
</section> </section>
); );

View File

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

View File

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

View File

@ -1,25 +1,26 @@
import { gql, useQuery } from '@apollo/client'; import { gql, useQuery } from '@apollo/client';
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; import React from 'react';
import { RouteTitle } from '../../components/route-title'; import { RouteTitle } from '../../components/route-title';
import { SubHeading } from '../../components/sub-heading'; import { SubHeading } from '../../components/sub-heading';
import { SyntaxHighlighter } from '../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { import type {
ProposalsQuery, ProposalsQuery,
ProposalsQuery_proposals_terms_change, ProposalsQuery_proposals_terms_change,
} from '@vegaprotocol/graphql'; } from './__generated__/ProposalsQuery';
export function getProposalName(change: ProposalsQuery_proposals_terms_change) { export function getProposalName(change: ProposalsQuery_proposals_terms_change) {
if (change.__typename === 'NewAsset') { if (change.__typename === 'NewAsset') {
return `New asset: ${change.symbol}`; return t(`New asset: ${change.symbol}`);
} else if (change.__typename === 'NewMarket') { } else if (change.__typename === 'NewMarket') {
return `New market: ${change.instrument.name}`; return t(`New market: ${change.instrument.name}`);
} else if (change.__typename === 'UpdateMarket') { } else if (change.__typename === 'UpdateMarket') {
return `Update market: ${change.marketId}`; return t(`Update market: ${change.marketId}`);
} else if (change.__typename === 'UpdateNetworkParameter') { } else if (change.__typename === 'UpdateNetworkParameter') {
return `Update network: ${change.networkParameter.key}`; return t(`Update network: ${change.networkParameter.key}`);
} }
return 'Unknown proposal'; return t('Unknown proposal');
} }
const PROPOSAL_QUERY = gql` const PROPOSAL_QUERY = gql`
@ -105,7 +106,7 @@ const Governance = () => {
if (!data) return null; if (!data) return null;
return ( return (
<section> <section>
<RouteTitle data-testid="governance-header">Governance</RouteTitle> <RouteTitle data-testid="governance-header">{t('Governance')}</RouteTitle>
{data.proposals?.map((p) => ( {data.proposals?.map((p) => (
<React.Fragment key={p.id}> <React.Fragment key={p.id}>
<SubHeading>{getProposalName(p.terms.change)}</SubHeading> <SubHeading>{getProposalName(p.terms.change)}</SubHeading>

View File

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

View File

@ -1,10 +1,11 @@
import { gql, useQuery } from '@apollo/client'; import { gql, useQuery } from '@apollo/client';
import { MarketsQuery } from '@vegaprotocol/graphql'; import type { MarketsQuery } from './__generated__/MarketsQuery';
import React from 'react'; import React from 'react';
import { SyntaxHighlighter } from '../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { RouteTitle } from '../../components/route-title'; import { RouteTitle } from '../../components/route-title';
import { SubHeading } from '../../components/sub-heading'; import { SubHeading } from '../../components/sub-heading';
import { t } from '@vegaprotocol/react-helpers';
const MARKETS_QUERY = gql` const MARKETS_QUERY = gql`
query MarketsQuery { query MarketsQuery {
@ -151,7 +152,7 @@ const Markets = () => {
if (!data || !data.markets) return null; if (!data || !data.markets) return null;
return ( return (
<section> <section>
<RouteTitle data-testid="markets-heading">Markets</RouteTitle> <RouteTitle data-testid="markets-heading">{t('Markets')}</RouteTitle>
{data {data
? data.markets.map((m) => ( ? data.markets.map((m) => (

View File

@ -1,7 +1,8 @@
import { gql, useQuery } from '@apollo/client'; import { gql, useQuery } from '@apollo/client';
import { RouteTitle } from '../../components/route-title'; import { RouteTitle } from '../../components/route-title';
import { NetworkParametersQuery } from '@vegaprotocol/graphql'; import type { NetworkParametersQuery } from './__generated__/NetworkParametersQuery';
import { SyntaxHighlighter } from '../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { t } from '@vegaprotocol/react-helpers';
export const NETWORK_PARAMETERS_QUERY = gql` export const NETWORK_PARAMETERS_QUERY = gql`
query NetworkParametersQuery { query NetworkParametersQuery {
@ -17,7 +18,7 @@ const NetworkParameters = () => {
return ( return (
<section> <section>
<RouteTitle data-testid="network-param-header"> <RouteTitle data-testid="network-param-header">
Network Parameters {t('Network Parameters')}
</RouteTitle> </RouteTitle>
{data ? <SyntaxHighlighter data={data} /> : null} {data ? <SyntaxHighlighter data={data} /> : null}
</section> </section>

View File

@ -4,6 +4,7 @@ import { JumpTo } from '../../../components/jump-to';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Routes } from '../../router-config'; import { Routes } from '../../router-config';
import { t } from '@vegaprotocol/react-helpers';
export const JumpToParty = () => { export const JumpToParty = () => {
const navigate = useNavigate(); const navigate = useNavigate();
@ -23,8 +24,8 @@ export const JumpToParty = () => {
}; };
return ( return (
<JumpTo <JumpTo
label="Go to party" label={t('Go to party')}
placeholder="Party id" placeholder={t('Party id')}
inputId="party-input" inputId="party-input"
inputType="text" inputType="text"
inputName="partyId" inputName="partyId"
@ -36,7 +37,7 @@ export const JumpToParty = () => {
const Parties = () => { const Parties = () => {
return ( return (
<section> <section>
<RouteTitle data-testid="parties-header">Parties</RouteTitle> <RouteTitle data-testid="parties-header">{t('Parties')}</RouteTitle>
<JumpToParty /> <JumpToParty />
</section> </section>
); );

View File

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

View File

@ -1,5 +1,6 @@
import { useQuery } from '@apollo/client'; import { useQuery } from '@apollo/client';
import { gql } from '@apollo/client'; import { gql } from '@apollo/client';
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; import React from 'react';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import { RouteTitle } from '../../../components/route-title'; import { RouteTitle } from '../../../components/route-title';
@ -7,11 +8,11 @@ import { SubHeading } from '../../../components/sub-heading';
import { SyntaxHighlighter } from '../../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../../components/syntax-highlighter';
import { DATA_SOURCES } from '../../../config'; import { DATA_SOURCES } from '../../../config';
import useFetch from '../../../hooks/use-fetch'; import useFetch from '../../../hooks/use-fetch';
import { TendermintSearchTransactionResponse } from '../tendermint-transaction-response'; import type { TendermintSearchTransactionResponse } from '../tendermint-transaction-response';
import { import type {
PartyAssetsQuery, PartyAssetsQuery,
PartyAssetsQueryVariables, PartyAssetsQueryVariables,
} from '@vegaprotocol/graphql'; } from './__generated__/PartyAssetsQuery';
const PARTY_ASSETS_QUERY = gql` const PARTY_ASSETS_QUERY = gql`
query PartyAssetsQuery($partyId: ID!) { query PartyAssetsQuery($partyId: ID!) {
@ -71,17 +72,17 @@ const Party = () => {
return ( return (
<section> <section>
<RouteTitle data-testid="parties-header">Party</RouteTitle> <RouteTitle data-testid="parties-header">{t('Party')}</RouteTitle>
{data ? ( {data ? (
<> <>
<SubHeading>Asset data</SubHeading> <SubHeading>{t('Asset data')}</SubHeading>
<SyntaxHighlighter data={data} /> <SyntaxHighlighter data={data} />
</> </>
) : null} ) : null}
{partyData ? ( {partyData ? (
<> <>
<SubHeading>Tendermint Data</SubHeading> <SubHeading>{t('Tendermint Data')}</SubHeading>
<SyntaxHighlighter data={partyData} /> <SyntaxHighlighter data={partyData} />
</> </>
) : null} ) : null}

View File

@ -1,9 +1,10 @@
import React from 'react'; import React from 'react';
import { DATA_SOURCES } from '../../config'; import { DATA_SOURCES } from '../../config';
import useFetch from '../../hooks/use-fetch'; 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 { TxList } from '../../components/txs';
import { RouteTitle } from '../../components/route-title'; import { RouteTitle } from '../../components/route-title';
import { t } from '@vegaprotocol/react-helpers';
const PendingTxs = () => { const PendingTxs = () => {
const { const {
@ -15,11 +16,11 @@ const PendingTxs = () => {
return ( return (
<section> <section>
<RouteTitle data-testid="unconfirmed-transactions-header"> <RouteTitle data-testid="unconfirmed-transactions-header">
Unconfirmed transactions {t('Unconfirmed transactions')}
</RouteTitle> </RouteTitle>
https://lb.testnet.vega.xyz/tm/unconfirmed_txs https://lb.testnet.vega.xyz/tm/unconfirmed_txs
<br /> <br />
<div>Number: {unconfirmedTransactions?.result?.n_txs || 0}</div> <div>{t(`Number: ${unconfirmedTransactions?.result?.n_txs || 0}`)}</div>
<br /> <br />
<div> <div>
<br /> <br />

View File

@ -16,6 +16,7 @@ import { Tx } from './txs/id';
import { Txs as TxHome } from './txs/home'; import { Txs as TxHome } from './txs/home';
import { PendingTxs } from './pending'; import { PendingTxs } from './pending';
import flags from '../lib/flags'; import flags from '../lib/flags';
import { t } from '@vegaprotocol/react-helpers';
export const Routes = { export const Routes = {
HOME: '/', HOME: '/',
TX: 'txs', TX: 'txs',
@ -34,7 +35,7 @@ const partiesRoutes = flags.parties
{ {
path: Routes.PARTIES, path: Routes.PARTIES,
name: 'Parties', name: 'Parties',
text: 'Parties', text: t('Parties'),
element: <Party />, element: <Party />,
children: [ children: [
{ {
@ -54,7 +55,7 @@ const assetsRoutes = flags.assets
? [ ? [
{ {
path: Routes.ASSETS, path: Routes.ASSETS,
text: 'Assets', text: t('Assets'),
name: 'Assets', name: 'Assets',
element: <Assets />, element: <Assets />,
}, },
@ -66,7 +67,7 @@ const genesisRoutes = flags.genesis
{ {
path: Routes.GENESIS, path: Routes.GENESIS,
name: 'Genesis', name: 'Genesis',
text: 'Genesis Parameters', text: t('Genesis Parameters'),
element: <Genesis />, element: <Genesis />,
}, },
] ]
@ -77,7 +78,7 @@ const governanceRoutes = flags.governance
{ {
path: Routes.GOVERNANCE, path: Routes.GOVERNANCE,
name: 'Governance', name: 'Governance',
text: 'Proposals', text: t('Proposals'),
element: <Governance />, element: <Governance />,
}, },
] ]
@ -88,7 +89,7 @@ const marketsRoutes = flags.markets
{ {
path: Routes.MARKETS, path: Routes.MARKETS,
name: 'Markets', name: 'Markets',
text: 'Markets', text: t('Markets'),
element: <Markets />, element: <Markets />,
}, },
] ]
@ -99,7 +100,7 @@ const networkParametersRoutes = flags.networkParameters
{ {
path: Routes.NETWORK_PARAMETERS, path: Routes.NETWORK_PARAMETERS,
name: 'NetworkParameters', name: 'NetworkParameters',
text: 'Network Parameters', text: t('Network Parameters'),
element: <NetworkParameters />, element: <NetworkParameters />,
}, },
] ]
@ -109,7 +110,7 @@ const validators = flags.validators
{ {
path: Routes.VALIDATORS, path: Routes.VALIDATORS,
name: 'Validators', name: 'Validators',
text: 'Validators', text: t('Validators'),
element: <Validators />, element: <Validators />,
}, },
] ]
@ -119,14 +120,14 @@ const routerConfig = [
{ {
path: Routes.HOME, path: Routes.HOME,
name: 'Home', name: 'Home',
text: 'Home', text: t('Home'),
element: <Home />, element: <Home />,
index: true, index: true,
}, },
{ {
path: Routes.TX, path: Routes.TX,
name: 'Txs', name: 'Txs',
text: 'Transactions', text: t('Transactions'),
element: <Txs />, element: <Txs />,
children: [ children: [
{ {
@ -146,7 +147,7 @@ const routerConfig = [
{ {
path: Routes.BLOCKS, path: Routes.BLOCKS,
name: 'Blocks', name: 'Blocks',
text: 'Blocks', text: t('Blocks'),
element: <BlockPage />, element: <BlockPage />,
children: [ children: [
{ {

View File

@ -1,11 +1,12 @@
import useFetch from '../../../hooks/use-fetch'; 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 { DATA_SOURCES } from '../../../config';
import { RouteTitle } from '../../../components/route-title'; import { RouteTitle } from '../../../components/route-title';
import { BlocksRefetch } from '../../../components/blocks'; import { BlocksRefetch } from '../../../components/blocks';
import { RenderFetched } from '../../../components/render-fetched'; import { RenderFetched } from '../../../components/render-fetched';
import { BlockTxsData } from '../../../components/txs'; import { BlockTxsData } from '../../../components/txs';
import { JumpToBlock } from '../../../components/jump-to-block'; import { JumpToBlock } from '../../../components/jump-to-block';
import { t } from '@vegaprotocol/react-helpers';
const Txs = () => { const Txs = () => {
const { const {
@ -17,7 +18,7 @@ const Txs = () => {
return ( return (
<section> <section>
<RouteTitle>Transactions</RouteTitle> <RouteTitle>{t('Transactions')}</RouteTitle>
<RenderFetched error={error} loading={loading}> <RenderFetched error={error} loading={loading}>
<> <>
<BlocksRefetch refetch={refetch} /> <BlocksRefetch refetch={refetch} />

View File

@ -1,13 +1,14 @@
import React from 'react'; import React from 'react';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import useFetch from '../../../hooks/use-fetch'; import useFetch from '../../../hooks/use-fetch';
import { TendermintTransactionResponse } from '../tendermint-transaction-response.d'; import type { TendermintTransactionResponse } from '../tendermint-transaction-response.d';
import { ChainExplorerTxResponse } from '../../types/chain-explorer-response'; import type { ChainExplorerTxResponse } from '../../types/chain-explorer-response';
import { DATA_SOURCES } from '../../../config'; import { DATA_SOURCES } from '../../../config';
import { RouteTitle } from '../../../components/route-title'; import { RouteTitle } from '../../../components/route-title';
import { RenderFetched } from '../../../components/render-fetched'; import { RenderFetched } from '../../../components/render-fetched';
import { TxContent } from './tx-content'; import { TxContent } from './tx-content';
import { TxDetails } from './tx-details'; import { TxDetails } from './tx-details';
import { t } from '@vegaprotocol/react-helpers';
const Tx = () => { const Tx = () => {
const { txHash } = useParams<{ txHash: string }>(); const { txHash } = useParams<{ txHash: string }>();
@ -30,7 +31,7 @@ const Tx = () => {
return ( return (
<section> <section>
<RouteTitle>Transaction details</RouteTitle> <RouteTitle>{t('Transaction details')}</RouteTitle>
<RenderFetched error={tTxError} loading={tTxLoading}> <RenderFetched error={tTxError} loading={tTxLoading}>
<TxDetails <TxDetails
@ -40,7 +41,7 @@ const Tx = () => {
/> />
</RenderFetched> </RenderFetched>
<h2 className="text-h4 uppercase mb-16">Transaction content</h2> <h2 className="text-h4 uppercase mb-16">{t('Transaction content')}</h2>
<RenderFetched error={ceTxError} loading={ceTxLoading}> <RenderFetched error={ceTxError} loading={ceTxLoading}>
<TxContent data={ceTxData} /> <TxContent data={ceTxData} />
</RenderFetched> </RenderFetched>

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { StatusMessage } from '../../../components/status-message'; import { StatusMessage } from '../../../components/status-message';
import { SyntaxHighlighter } from '../../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../../components/syntax-highlighter';
import { import {
@ -7,7 +8,7 @@ import {
TableRow, TableRow,
} from '../../../components/table'; } from '../../../components/table';
import { TxOrderType } from '../../../components/txs'; import { TxOrderType } from '../../../components/txs';
import { ChainExplorerTxResponse } from '../../types/chain-explorer-response'; import type { ChainExplorerTxResponse } from '../../types/chain-explorer-response';
interface TxContentProps { interface TxContentProps {
data: ChainExplorerTxResponse | undefined; data: ChainExplorerTxResponse | undefined;
@ -16,7 +17,9 @@ interface TxContentProps {
export const TxContent = ({ data }: TxContentProps) => { export const TxContent = ({ data }: TxContentProps) => {
if (!data?.Command) { if (!data?.Command) {
return ( return (
<StatusMessage>Could not retrieve transaction content</StatusMessage> <StatusMessage>
{t('Could not retrieve transaction content')}
</StatusMessage>
); );
} }
@ -25,7 +28,7 @@ export const TxContent = ({ data }: TxContentProps) => {
<TableWithTbody className="mb-12"> <TableWithTbody className="mb-12">
<TableRow modifier="bordered"> <TableRow modifier="bordered">
<TableHeader scope="row" className="w-[160px]"> <TableHeader scope="row" className="w-[160px]">
Type {t('Type')}
</TableHeader> </TableHeader>
<TableCell modifier="bordered"> <TableCell modifier="bordered">
<TxOrderType orderType={data.Type} /> <TxOrderType orderType={data.Type} />
@ -33,7 +36,7 @@ export const TxContent = ({ data }: TxContentProps) => {
</TableRow> </TableRow>
</TableWithTbody> </TableWithTbody>
<h3 className="font-mono mb-8">Decoded transaction content</h3> <h3 className="font-mono mb-8">{t('Decoded transaction content')}</h3>
<SyntaxHighlighter data={JSON.parse(data.Command)} /> <SyntaxHighlighter data={JSON.parse(data.Command)} />
</> </>
); );

View File

@ -1,5 +1,5 @@
import { Routes } from '../../router-config'; import { Routes } from '../../router-config';
import { Result } from '../tendermint-transaction-response.d'; import type { Result } from '../tendermint-transaction-response.d';
import { import {
TableWithTbody, TableWithTbody,
TableCell, TableCell,
@ -7,8 +7,9 @@ import {
TableRow, TableRow,
} from '../../../components/table'; } from '../../../components/table';
import { TruncateInline } from '../../../components/truncate/truncate'; import { TruncateInline } from '../../../components/truncate/truncate';
import { HighlightedLink } from '../../../components/highlighted-link'; import { t } from '@vegaprotocol/react-helpers';
import { HighlightedLink } from '../../../components/highlighted-link';
interface TxDetailsProps { interface TxDetailsProps {
txData: Result | undefined; txData: Result | undefined;
pubKey: string | undefined; pubKey: string | undefined;
@ -19,27 +20,27 @@ const truncateLength = 30;
export const TxDetails = ({ txData, pubKey, className }: TxDetailsProps) => { export const TxDetails = ({ txData, pubKey, className }: TxDetailsProps) => {
if (!txData) { if (!txData) {
return <>Awaiting Tendermint transaction details</>; return <>{t('Awaiting Tendermint transaction details')}</>;
} }
return ( return (
<TableWithTbody className={className}> <TableWithTbody className={className}>
<TableRow modifier="bordered"> <TableRow modifier="bordered">
<TableCell>Hash</TableCell> <TableCell>{t('Hash')}</TableCell>
<TableCell modifier="bordered" data-testid="hash"> <TableCell modifier="bordered" data-testid="hash">
{txData.hash} {txData.hash}
</TableCell> </TableCell>
</TableRow> </TableRow>
<TableRow modifier="bordered"> <TableRow modifier="bordered">
<TableHeader scope="row" className="w-[160px]"> <TableHeader scope="row" className="w-[160px]">
Submitted by {t('Submitted by')}
</TableHeader> </TableHeader>
<TableCell modifier="bordered" data-testid="submitted-by"> <TableCell modifier="bordered" data-testid="submitted-by">
<HighlightedLink to={`/${Routes.PARTIES}/${pubKey}`} text={pubKey} /> <HighlightedLink to={`/${Routes.PARTIES}/${pubKey}`} text={pubKey} />
</TableCell> </TableCell>
</TableRow> </TableRow>
<TableRow modifier="bordered"> <TableRow modifier="bordered">
<TableCell>Block</TableCell> <TableCell>{t('Block')}</TableCell>
<TableCell modifier="bordered" data-testid="block"> <TableCell modifier="bordered" data-testid="block">
<HighlightedLink <HighlightedLink
to={`/${Routes.BLOCKS}/${txData.height}`} to={`/${Routes.BLOCKS}/${txData.height}`}
@ -48,7 +49,7 @@ export const TxDetails = ({ txData, pubKey, className }: TxDetailsProps) => {
</TableCell> </TableCell>
</TableRow> </TableRow>
<TableRow modifier="bordered"> <TableRow modifier="bordered">
<TableCell>Encoded txn</TableCell> <TableCell>{t('Encoded txn')}</TableCell>
<TableCell modifier="bordered" data-testid="encoded-tnx"> <TableCell modifier="bordered" data-testid="encoded-tnx">
<TruncateInline <TruncateInline
text={txData.tx} text={txData.tx}

View File

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

View File

@ -1,12 +1,13 @@
import { gql, useQuery } from '@apollo/client'; import { gql, useQuery } from '@apollo/client';
import { t } from '@vegaprotocol/react-helpers';
import React from 'react'; import React from 'react';
import { RouteTitle } from '../../components/route-title'; import { RouteTitle } from '../../components/route-title';
import { SubHeading } from '../../components/sub-heading'; import { SubHeading } from '../../components/sub-heading';
import { SyntaxHighlighter } from '../../components/syntax-highlighter'; import { SyntaxHighlighter } from '../../components/syntax-highlighter';
import { DATA_SOURCES } from '../../config'; import { DATA_SOURCES } from '../../config';
import useFetch from '../../hooks/use-fetch'; import useFetch from '../../hooks/use-fetch';
import { TendermintValidatorsResponse } from './tendermint-validator-response'; import type { TendermintValidatorsResponse } from './tendermint-validator-response';
import { NodesQuery } from '@vegaprotocol/graphql'; import type { NodesQuery } from './__generated__/NodesQuery';
const NODES_QUERY = gql` const NODES_QUERY = gql`
query NodesQuery { query NodesQuery {
@ -44,17 +45,17 @@ const Validators = () => {
return ( return (
<section> <section>
<RouteTitle data-testid="validators-header">Validators</RouteTitle> <RouteTitle data-testid="validators-header">{t('Validators')}</RouteTitle>
{data ? ( {data ? (
<> <>
<SubHeading data-testid="vega-header">Vega data</SubHeading> <SubHeading data-testid="vega-header">{t('Vega data')}</SubHeading>
<SyntaxHighlighter data-testid="vega-data" data={data} /> <SyntaxHighlighter data-testid="vega-data" data={data} />
</> </>
) : null} ) : null}
{validators ? ( {validators ? (
<> <>
<SubHeading data-testid="tendermint-header"> <SubHeading data-testid="tendermint-header">
Tendermint data {t('Tendermint data')}
</SubHeading> </SubHeading>
<SyntaxHighlighter data-testid="tendermint-data" data={validators} /> <SyntaxHighlighter data-testid="tendermint-data" data={validators} />
</> </>

View File

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

View File

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

View File

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

View File

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

View File

@ -2,6 +2,7 @@ import { useRouter } from 'next/router';
import { Vega } from '../icons/vega'; import { Vega } from '../icons/vega';
import Link from 'next/link'; import Link from 'next/link';
import { AnchorButton } from '@vegaprotocol/ui-toolkit'; import { AnchorButton } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/react-helpers';
export const Navbar = () => { export const Navbar = () => {
return ( return (
@ -12,8 +13,8 @@ export const Navbar = () => {
</a> </a>
</Link> </Link>
{[ {[
{ name: 'Trading', path: '/markets' }, { name: t('Trading'), path: '/markets' },
{ name: 'Portfolio', path: '/portfolio' }, { name: t('Portfolio'), path: '/portfolio' },
].map((route) => ( ].map((route) => (
<NavLink key={route.path} {...route} /> <NavLink key={route.path} {...route} />
))} ))}

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

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { useVegaWallet } from '@vegaprotocol/wallet'; import { useVegaWallet } from '@vegaprotocol/wallet';
interface VegaWalletButtonProps { interface VegaWalletButtonProps {
@ -23,7 +24,7 @@ export const VegaWalletButton = ({
onClick={handleClick} onClick={handleClick}
className="ml-auto inline-block text-ui sm:text-body-large" className="ml-auto inline-block text-ui sm:text-body-large"
> >
{isConnected ? 'Disconnect Vega wallet' : 'Connect Vega wallet'} {isConnected ? t('Disconnect Vega wallet') : t('Connect Vega wallet')}
</button> </button>
); );
}; };

View File

@ -1,7 +1,9 @@
import { t } from '@vegaprotocol/react-helpers';
import { Button, Splash } from '@vegaprotocol/ui-toolkit'; import { Button, Splash } from '@vegaprotocol/ui-toolkit';
import { Web3Provider, Web3ConnectDialog } from '@vegaprotocol/web3'; import { Web3Provider, Web3ConnectDialog } from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core'; 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'; import { Connectors } from '../../lib/web3-connectors';
interface Web3ContainerProps { interface Web3ContainerProps {
@ -41,8 +43,10 @@ export const Web3Content = ({ children, setDialogOpen }: Web3ContentProps) => {
if (error) { if (error) {
return ( return (
<SplashWrapper> <SplashWrapper>
<p className="mb-12">Something went wrong: {error.message}</p> <p className="mb-12">{t(`Something went wrong: ${error.message}`)}</p>
<Button onClick={() => connector.deactivate()}>Disconnect</Button> <Button onClick={() => connector.deactivate()}>
{t('Disconnect')}
</Button>
</SplashWrapper> </SplashWrapper>
); );
} }
@ -50,8 +54,8 @@ export const Web3Content = ({ children, setDialogOpen }: Web3ContentProps) => {
if (!isActive) { if (!isActive) {
return ( return (
<SplashWrapper> <SplashWrapper>
<p className="mb-12">Connect your Ethereum wallet</p> <p className="mb-12">{t('Connect your Ethereum wallet')}</p>
<Button onClick={() => setDialogOpen(true)}>Connect</Button> <Button onClick={() => setDialogOpen(true)}>{t('Connect')}</Button>
</SplashWrapper> </SplashWrapper>
); );
} }
@ -59,8 +63,12 @@ export const Web3Content = ({ children, setDialogOpen }: Web3ContentProps) => {
if (chainId !== appChainId) { if (chainId !== appChainId) {
return ( return (
<SplashWrapper> <SplashWrapper>
<p className="mb-12">This app only works on chain ID: {appChainId}</p> <p className="mb-12">
<Button onClick={() => connector.deactivate()}>Disconnect</Button> {t(`This app only works on chain ID: ${appChainId}`)}
</p>
<Button onClick={() => connector.deactivate()}>
{t('Disconnect')}
</Button>
</SplashWrapper> </SplashWrapper>
); );
} }

View File

@ -1,7 +1,7 @@
import { AppProps } from 'next/app'; import type { AppProps } from 'next/app';
import Head from 'next/head'; import Head from 'next/head';
import { Navbar } from '../components/navbar'; import { Navbar } from '../components/navbar';
import { ThemeContext } from '@vegaprotocol/react-helpers'; import { t, ThemeContext } from '@vegaprotocol/react-helpers';
import { VegaConnectDialog, VegaWalletProvider } from '@vegaprotocol/wallet'; import { VegaConnectDialog, VegaWalletProvider } from '@vegaprotocol/wallet';
import { Connectors } from '../lib/vega-connectors'; import { Connectors } from '../lib/vega-connectors';
import { useCallback, useMemo, useState } from 'react'; import { useCallback, useMemo, useState } from 'react';
@ -32,7 +32,7 @@ function VegaTradingApp({ Component, pageProps }: AppProps) {
<VegaWalletProvider> <VegaWalletProvider>
<AppLoader> <AppLoader>
<Head> <Head>
<title>Welcome to trading!</title> <title>{t('Welcome to Vega trading!')}</title>
<link <link
rel="icon" rel="icon"
href="https://vega.xyz/favicon-32x32.png" href="https://vega.xyz/favicon-32x32.png"

View File

@ -1,17 +1,6 @@
import { import { Button, Callout, Intent } from '@vegaprotocol/ui-toolkit';
AgGridDynamic as AgGrid,
Button,
Callout,
Intent,
} from '@vegaprotocol/ui-toolkit';
import { AgGridColumn } from 'ag-grid-react';
export function Index() { export function Index() {
const rowData = [
{ make: 'Toyota', model: 'Celica', price: 35000 },
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxter', price: 72000 },
];
return ( return (
<div className="m-24"> <div className="m-24">
<div className="mb-24"> <div className="mb-24">
@ -29,11 +18,6 @@ export function Index() {
</div> </div>
</Callout> </Callout>
</div> </div>
<AgGrid rowData={rowData} style={{ height: 400, width: 600 }}>
<AgGridColumn field="make"></AgGridColumn>
<AgGridColumn field="model"></AgGridColumn>
<AgGridColumn field="price"></AgGridColumn>
</AgGrid>
</div> </div>
); );
} }

View File

@ -1,11 +1,12 @@
import { gql } from '@apollo/client'; 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 { Splash } from '@vegaprotocol/ui-toolkit';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import debounce from 'lodash/debounce'; import debounce from 'lodash/debounce';
import { PageQueryContainer } from '../../components/page-query-container'; import { PageQueryContainer } from '../../components/page-query-container';
import { TradeGrid, TradePanels } from './trade-grid'; import { TradeGrid, TradePanels } from './trade-grid';
import { t } from '@vegaprotocol/react-helpers';
// Top level page query // Top level page query
const MARKET_QUERY = gql` const MARKET_QUERY = gql`
@ -13,34 +14,6 @@ const MARKET_QUERY = gql`
market(id: $marketId) { market(id: $marketId) {
id id
name name
decimalPlaces
state
tradingMode
tradableInstrument {
instrument {
product {
... on Future {
quoteName
settlementAsset {
id
symbol
name
}
}
}
}
}
trades {
id
price
size
createdAt
}
depth {
lastTrade {
price
}
}
} }
} }
`; `;
@ -57,7 +30,7 @@ const MarketPage = () => {
if (!marketId) { if (!marketId) {
return ( return (
<Splash> <Splash>
<p>Not found</p> <p>{t('Not found')}</p>
</Splash> </Splash>
); );
} }
@ -74,7 +47,7 @@ const MarketPage = () => {
> >
{({ market }) => { {({ market }) => {
if (!market) { if (!market) {
return <Splash>Market not found</Splash>; return <Splash>{t('Market not found')}</Splash>;
} }
return w > 960 ? ( return w > 960 ? (

View File

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

View File

@ -1,14 +1,8 @@
import * as Tabs from '@radix-ui/react-tabs'; import * as Tabs from '@radix-ui/react-tabs';
import classNames from 'classnames'; import classNames from 'classnames';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { import type { ReactElement, ReactNode } from 'react';
Children, import { Children, isValidElement, useEffect, useState } from 'react';
isValidElement,
ReactElement,
ReactNode,
useEffect,
useState,
} from 'react';
interface GridTabsProps { interface GridTabsProps {
children: ReactElement<GridTabProps>[]; children: ReactElement<GridTabProps>[];
@ -25,7 +19,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
} }
// Default to first tab // Default to first tab
return children[0].props.name; return children[0].props.id;
}); });
// Update the query string in the url when the active tab changes // Update the query string in the url when the active tab changes
@ -51,7 +45,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
> >
{Children.map(children, (child) => { {Children.map(children, (child) => {
if (!isValidElement(child)) return null; if (!isValidElement(child)) return null;
const isActive = child.props.name === activeTab; const isActive = child.props.id === activeTab;
const triggerClass = classNames('py-4', 'px-12', 'capitalize', { const triggerClass = classNames('py-4', 'px-12', 'capitalize', {
'text-black dark:text-vega-yellow': isActive, 'text-black dark:text-vega-yellow': isActive,
'bg-white dark:bg-black': isActive, 'bg-white dark:bg-black': isActive,
@ -59,7 +53,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
'bg-black-10 dark:bg-white-10': !isActive, 'bg-black-10 dark:bg-white-10': !isActive,
}); });
return ( return (
<Tabs.Trigger value={child.props.name} className={triggerClass}> <Tabs.Trigger value={child.props.id} className={triggerClass}>
{child.props.name} {child.props.name}
</Tabs.Trigger> </Tabs.Trigger>
); );
@ -70,7 +64,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
{Children.map(children, (child) => { {Children.map(children, (child) => {
if (!isValidElement(child)) return null; if (!isValidElement(child)) return null;
return ( return (
<Tabs.Content value={child.props.name} className="h-full"> <Tabs.Content value={child.props.id} className="h-full">
{child.props.children} {child.props.children}
</Tabs.Content> </Tabs.Content>
); );
@ -82,6 +76,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
interface GridTabProps { interface GridTabProps {
children: ReactNode; children: ReactNode;
id: string;
name: string; name: string;
} }

View File

@ -1,70 +1,7 @@
import { useRef, useCallback } from 'react'; import { MarketsContainer } from '@vegaprotocol/market-list';
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';
const Markets = () => { const Markets = () => {
const { pathname, push } = useRouter(); return <MarketsContainer />;
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>
);
}; };
export default Markets; export default Markets;

View File

@ -1,50 +1,42 @@
import { Market_market } from '@vegaprotocol/graphql';
import classNames from 'classnames'; import classNames from 'classnames';
import AutoSizer from 'react-virtualized-auto-sizer'; 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 { GridTab, GridTabs } from './grid-tabs';
import { DealTicketContainer } from '../../components/deal-ticket-container'; import { DealTicketContainer } from '@vegaprotocol/deal-ticket';
import { OrderListContainer } from '../..//components/order-list-container'; import { OrderListContainer } from '@vegaprotocol/order-list';
import { Splash } from '@vegaprotocol/ui-toolkit'; import { Splash } from '@vegaprotocol/ui-toolkit';
import { Positions } from './positions'; import { PositionsContainer } from '@vegaprotocol/positions';
import type { Market_market } from './__generated__/Market';
import { t } from '@vegaprotocol/react-helpers';
const Chart = () => ( const Chart = () => (
<Splash> <Splash>
<p>Chart</p> <p>{t('Chart')}</p>
</Splash> </Splash>
); );
const Orderbook = () => ( const Orderbook = () => (
<Splash> <Splash>
<p>Orderbook</p> <p>{t('Orderbook')}</p>
</Splash> </Splash>
); );
const Collateral = () => ( const Collateral = () => (
<Splash> <Splash>
<p>Collateral</p> <p>{t('Collateral')}</p>
</Splash> </Splash>
); );
const Trades = () => ( const Trades = () => (
<Splash> <Splash>
<p>Trades</p> <p>{t('Trades')}</p>
</Splash> </Splash>
); );
// enum TradingView {
// Chart = 'Chart',
// Ticket = 'Ticket',
// Orderbook = 'Orderbook',
// Orders = 'Orders',
// Positions = 'Positions',
// Collateral = 'Collateral',
// Trades = 'Trades',
// }
const TradingViews = { const TradingViews = {
Chart: Chart, Chart: Chart,
Ticket: DealTicketContainer, Ticket: DealTicketContainer,
Orderbook: Orderbook, Orderbook: Orderbook,
Orders: OrderListContainer, Orders: OrderListContainer,
Positions: Positions, Positions: PositionsContainer,
Collateral: Collateral, Collateral: Collateral,
Trades: Trades, Trades: Trades,
}; };
@ -65,33 +57,35 @@ export const TradeGrid = ({ market }: TradeGridProps) => {
return ( return (
<div className={wrapperClasses}> <div className={wrapperClasses}>
<header className="col-start-1 col-end-2 row-start-1 row-end-1 p-8"> <header className="col-start-1 col-end-2 row-start-1 row-end-1 p-8">
<h1>Market: {market.name}</h1> <h1>
{t('Market')}: {market.name}
</h1>
</header> </header>
<TradeGridChild className="col-start-1 col-end-2"> <TradeGridChild className="col-start-1 col-end-2">
<TradingViews.Chart /> <TradingViews.Chart />
</TradeGridChild> </TradeGridChild>
<TradeGridChild className="row-start-1 row-end-3"> <TradeGridChild className="row-start-1 row-end-3">
<TradingViews.Ticket market={market} /> <TradingViews.Ticket marketId={market.id} />
</TradeGridChild> </TradeGridChild>
<TradeGridChild className="row-start-1 row-end-3"> <TradeGridChild className="row-start-1 row-end-3">
<GridTabs group="trade"> <GridTabs group="trade">
<GridTab name="trades"> <GridTab id="trades" name={t('Trades')}>
<TradingViews.Trades /> <TradingViews.Trades />
</GridTab> </GridTab>
<GridTab name="orderbook"> <GridTab id="orderbook" name={t('Orderbook')}>
<TradingViews.Orderbook /> <TradingViews.Orderbook />
</GridTab> </GridTab>
</GridTabs> </GridTabs>
</TradeGridChild> </TradeGridChild>
<TradeGridChild className="col-span-3"> <TradeGridChild className="col-span-3">
<GridTabs group="portfolio"> <GridTabs group="portfolio">
<GridTab name="orders"> <GridTab id="orders" name={t('Orders')}>
<TradingViews.Orders /> <TradingViews.Orders />
</GridTab> </GridTab>
<GridTab name="positions"> <GridTab id="positions" name={t('Positions')}>
<TradingViews.Positions /> <TradingViews.Positions />
</GridTab> </GridTab>
<GridTab name="collateral"> <GridTab id="collateral" name={t('Collateral')}>
<TradingViews.Collateral /> <TradingViews.Collateral />
</GridTab> </GridTab>
</GridTabs> </GridTabs>
@ -134,13 +128,15 @@ export const TradePanels = ({ market }: TradePanelsProps) => {
throw new Error(`No component for view: ${view}`); throw new Error(`No component for view: ${view}`);
} }
return <Component market={market} />; return <Component marketId={market.id} />;
}; };
return ( return (
<div className="h-full grid grid-rows-[min-content_1fr_min-content]"> <div className="h-full grid grid-rows-[min-content_1fr_min-content]">
<header className="p-8"> <header className="p-8">
<h1>Market: {market.name}</h1> <h1>
{t('Market')}: {market.name}
</h1>
</header> </header>
<div className="h-full"> <div className="h-full">
<AutoSizer> <AutoSizer>

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { AnchorButton } from '@vegaprotocol/ui-toolkit'; import { AnchorButton } from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet'; import { useVegaWallet } from '@vegaprotocol/wallet';
@ -5,14 +6,10 @@ const Portfolio = () => {
const { keypair } = useVegaWallet(); const { keypair } = useVegaWallet();
return ( return (
<div> <div>
<h1>Portfolio</h1> <h1>{t('Portfolio')}</h1>
{keypair && ( {keypair && <p>{t(`Keypair: ${keypair.name} ${keypair.pub}`)}</p>}
<p>
Keypair: {keypair.name} {keypair.pub}
</p>
)}
<div className="flex gap-4"> <div className="flex gap-4">
<AnchorButton href="/portfolio/deposit">Deposit</AnchorButton> <AnchorButton href="/portfolio/deposit">{t('Deposit')}</AnchorButton>
</div> </div>
</div> </div>
); );

View File

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

View File

@ -3,102 +3,58 @@
// @generated // @generated
// This file was automatically generated and should not be edited. // This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes"; import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
// ==================================================== // ====================================================
// GraphQL query operation: Market // GraphQL query operation: DealTicketQuery
// ==================================================== // ====================================================
export interface Market_market_tradableInstrument_instrument_product_settlementAsset { export interface DealTicketQuery_market_tradableInstrument_instrument_product {
__typename: "Asset"; __typename: 'Future';
/**
* 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 {
__typename: "Future";
/** /**
* String representing the quote (e.g. BTCUSD -> USD is quote) * String representing the quote (e.g. BTCUSD -> USD is quote)
*/ */
quoteName: string; 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"; __typename: 'Instrument';
/** /**
* A reference to or instance of a fully specified product, including all required product parameters for that product (Product union) * 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"; __typename: 'TradableInstrument';
/** /**
* An instance of or reference to a fully specified instrument. * 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 { export interface DealTicketQuery_market_depth_lastTrade {
__typename: "Trade"; __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 {
__typename: "Trade";
/** /**
* The price of the trade (probably initially the passive order price, other determination algorithms are possible though) (uint64) * The price of the trade (probably initially the passive order price, other determination algorithms are possible though) (uint64)
*/ */
price: string; price: string;
} }
export interface Market_market_depth { export interface DealTicketQuery_market_depth {
__typename: "MarketDepth"; __typename: 'MarketDepth';
/** /**
* Last trade for the given market (if available) * 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"; __typename: 'Market';
/** /**
* Market ID * Market ID
*/ */
id: string; 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 * 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) * 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. * An instance of or reference to a tradable instrument.
*/ */
tradableInstrument: Market_market_tradableInstrument; tradableInstrument: DealTicketQuery_market_tradableInstrument;
/**
* Trades on a market
*/
trades: Market_market_trades[] | null;
/** /**
* Current depth on the order book for this market * 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 * 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; marketId: string;
} }

View File

@ -3,18 +3,47 @@
// @generated // @generated
// This file was automatically generated and should not be edited. // This file was automatically generated and should not be edited.
import { BusEventType, OrderType, OrderStatus, OrderRejectionReason } from "./globalTypes"; import {
BusEventType,
OrderType,
OrderStatus,
OrderRejectionReason,
} from '@vegaprotocol/types';
// ==================================================== // ====================================================
// GraphQL subscription operation: OrderEvent // GraphQL subscription operation: OrderEvent
// ==================================================== // ====================================================
export interface OrderEvent_busEvents_event_TimeUpdate { export interface OrderEvent_busEvents_event_TimeUpdate {
__typename: "TimeUpdate" | "MarketEvent" | "TransferResponses" | "PositionResolution" | "Trade" | "Account" | "Party" | "MarginLevels" | "Proposal" | "Vote" | "MarketData" | "NodeSignature" | "LossSocialization" | "SettlePosition" | "Market" | "Asset" | "MarketTick" | "SettleDistressed" | "AuctionEvent" | "RiskFactor" | "Deposit" | "Withdrawal" | "OracleSpec" | "LiquidityProvision"; __typename:
| 'TimeUpdate'
| 'MarketEvent'
| 'TransferResponses'
| 'PositionResolution'
| 'Trade'
| 'Account'
| 'Party'
| 'MarginLevels'
| 'Proposal'
| 'Vote'
| 'MarketData'
| 'NodeSignature'
| 'LossSocialization'
| 'SettlePosition'
| 'Market'
| 'Asset'
| 'MarketTick'
| 'SettleDistressed'
| 'AuctionEvent'
| 'RiskFactor'
| 'Deposit'
| 'Withdrawal'
| 'OracleSpec'
| 'LiquidityProvision';
} }
export interface OrderEvent_busEvents_event_Order_market { export interface OrderEvent_busEvents_event_Order_market {
__typename: "Market"; __typename: 'Market';
/** /**
* Market full name * Market full name
*/ */
@ -39,7 +68,7 @@ export interface OrderEvent_busEvents_event_Order_market {
} }
export interface OrderEvent_busEvents_event_Order { export interface OrderEvent_busEvents_event_Order {
__typename: "Order"; __typename: 'Order';
/** /**
* Type the order type (defaults to PARTY) * Type the order type (defaults to PARTY)
*/ */
@ -74,10 +103,12 @@ export interface OrderEvent_busEvents_event_Order {
market: OrderEvent_busEvents_event_Order_market | null; market: OrderEvent_busEvents_event_Order_market | null;
} }
export type OrderEvent_busEvents_event = OrderEvent_busEvents_event_TimeUpdate | OrderEvent_busEvents_event_Order; export type OrderEvent_busEvents_event =
| OrderEvent_busEvents_event_TimeUpdate
| OrderEvent_busEvents_event_Order;
export interface OrderEvent_busEvents { export interface OrderEvent_busEvents {
__typename: "BusEvent"; __typename: 'BusEvent';
/** /**
* the id for this event * the id for this event
*/ */

View File

@ -0,0 +1,55 @@
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';
import { t } from '@vegaprotocol/react-helpers';
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>{t('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 { FormGroup, Input } from '@vegaprotocol/ui-toolkit';
import { OrderTimeInForce } from '@vegaprotocol/wallet'; import { OrderTimeInForce } from '@vegaprotocol/wallet';
import { TransactionStatus } from './deal-ticket'; import type { TransactionStatus } from './deal-ticket';
import { Market_market } from '@vegaprotocol/graphql';
import { ExpirySelector } from './expiry-selector'; import { ExpirySelector } from './expiry-selector';
import { SideSelector } from './side-selector'; import { SideSelector } from './side-selector';
import { SubmitButton } from './submit-button'; import { SubmitButton } from './submit-button';
import { TimeInForceSelector } from './time-in-force-selector'; import { TimeInForceSelector } from './time-in-force-selector';
import { TypeSelector } from './type-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 { interface DealTicketLimitProps {
order: Order; order: Order;
updateOrder: (order: Partial<Order>) => void; updateOrder: (order: Partial<Order>) => void;
transactionStatus: TransactionStatus; transactionStatus: TransactionStatus;
market: Market_market; market: DealTicketQuery_market;
} }
export const DealTicketLimit = ({ 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 { 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 { OrderDialog } from './order-dialog';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
interface DealTicketContainerProps { interface DealTicketManagerProps {
market: Market_market; market: DealTicketQuery_market;
} }
export const DealTicketContainer = ({ market }: DealTicketContainerProps) => { export const DealTicketManager = ({ market }: DealTicketManagerProps) => {
const [orderDialogOpen, setOrderDialogOpen] = useState(false); const [orderDialogOpen, setOrderDialogOpen] = useState(false);
const { submit, transaction, finalizedOrder, reset } = useOrderSubmit(market); const { submit, transaction, finalizedOrder, reset } = useOrderSubmit(market);

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
import { FormGroup, Input } from '@vegaprotocol/ui-toolkit'; 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'; import { formatForInput } from '@vegaprotocol/react-helpers';
interface ExpirySelectorProps { interface ExpirySelectorProps {

View File

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

View File

@ -1,11 +1,9 @@
import { Icon, Loader } from '@vegaprotocol/ui-toolkit'; import { Icon, Loader } from '@vegaprotocol/ui-toolkit';
import { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { import type { OrderEvent_busEvents_event_Order } from './__generated__/OrderEvent';
TransactionState, import { formatNumber, t } from '@vegaprotocol/react-helpers';
VegaTxStatus, import type { TransactionState } from '@vegaprotocol/wallet';
} from '../../hooks/use-vega-transaction'; import { VegaTxStatus } from '@vegaprotocol/wallet';
import { OrderEvent_busEvents_event_Order } from '@vegaprotocol/graphql';
import { formatNumber } from '@vegaprotocol/react-helpers';
interface OrderDialogProps { interface OrderDialogProps {
transaction: TransactionState; transaction: TransactionState;
@ -42,7 +40,7 @@ export const OrderDialog = ({
icon={<Loader />} icon={<Loader />}
> >
{transaction.hash && ( {transaction.hash && (
<p className="break-all">Tx hash: {transaction.hash}</p> <p className="break-all">{t(`Tx hash: ${transaction.hash}`)}</p>
)} )}
</OrderDialogWrapper> </OrderDialogWrapper>
); );
@ -55,7 +53,7 @@ export const OrderDialog = ({
title="Order failed" title="Order failed"
icon={<Icon name="warning-sign" size={20} />} icon={<Icon name="warning-sign" size={20} />}
> >
<p>Reason: {finalizedOrder.rejectionReason}</p> <p>{t(`Reason: ${finalizedOrder.rejectionReason}`)}</p>
</OrderDialogWrapper> </OrderDialogWrapper>
); );
} }
@ -65,16 +63,19 @@ export const OrderDialog = ({
title="Order placed" title="Order placed"
icon={<Icon name="tick" size={20} />} icon={<Icon name="tick" size={20} />}
> >
<p>Status: {finalizedOrder.status}</p> <p>{t(`Status: ${finalizedOrder.status}`)}</p>
{finalizedOrder.market && <p>Market: {finalizedOrder.market.name}</p>} {finalizedOrder.market && (
<p>Type: {finalizedOrder.type}</p> <p>{t(`Market: {finalizedOrder.market.name}`)}</p>
<p>Amount: {finalizedOrder.size}</p> )}
<p>{t(`Type: ${finalizedOrder.type}`)}</p>
<p>{t(`Amount: ${finalizedOrder.size}`)}</p>
{finalizedOrder.type === 'Limit' && finalizedOrder.market && ( {finalizedOrder.type === 'Limit' && finalizedOrder.market && (
<p> <p>
Price:{' '} {t(
{formatNumber( `Price: ${formatNumber(
finalizedOrder.price, finalizedOrder.price,
finalizedOrder.market.decimalPlaces finalizedOrder.market.decimalPlaces
)}`
)} )}
</p> </p>
)} )}

View File

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

View File

@ -1,14 +1,16 @@
import { Button, InputError } from '@vegaprotocol/ui-toolkit'; import { Button, InputError } from '@vegaprotocol/ui-toolkit';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet'; import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { Market_market } from '@vegaprotocol/graphql';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { Order } from './use-order-state'; import type { Order } from './use-order-state';
import { useVegaWallet } from '@vegaprotocol/wallet'; 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';
import { t } from '@vegaprotocol/react-helpers';
interface SubmitButtonProps { interface SubmitButtonProps {
transactionStatus: TransactionStatus; transactionStatus: TransactionStatus;
market: Market_market; market: DealTicketQuery_market;
order: Order; order: Order;
} }
@ -21,29 +23,31 @@ export const SubmitButton = ({
const invalidText = useMemo(() => { const invalidText = useMemo(() => {
if (!keypair) { if (!keypair) {
return 'No public key selected'; return t('No public key selected');
} }
if (keypair.tainted) { if (keypair.tainted) {
return 'Selected public key has been tainted'; return t('Selected public key has been tainted');
} }
// TODO: Change these to use enums from @vegaprotocol/graphql if (market.state !== MarketState.Active) {
if (market.state !== 'Active') { if (market.state === MarketState.Suspended) {
if (market.state === 'Suspended') { return t('Market is currently suspended');
return 'Market is currently suspended';
} }
if (market.state === 'Proposed' || market.state === 'Pending') { if (
return 'Market is not active yet'; market.state === MarketState.Proposed ||
market.state === MarketState.Pending
) {
return t('Market is not active yet');
} }
return 'Market is no longer active'; return t('Market is no longer active');
} }
if (market.tradingMode !== 'Continuous') { if (market.tradingMode !== MarketTradingMode.Continuous) {
if (order.type === OrderType.Market) { if (order.type === OrderType.Market) {
return 'Only limit orders are permitted when market is in auction'; return t('Only limit orders are permitted when market is in auction');
} }
if ( if (
@ -53,7 +57,9 @@ export const SubmitButton = ({
OrderTimeInForce.GFN, OrderTimeInForce.GFN,
].includes(order.timeInForce) ].includes(order.timeInForce)
) { ) {
return 'Only GTT, GTC and GFA are permitted when market is in auction'; return t(
'Only GTT, GTC and GFA are permitted when market is in auction'
);
} }
} }
@ -70,7 +76,7 @@ export const SubmitButton = ({
type="submit" type="submit"
disabled={disabled} disabled={disabled}
> >
{transactionStatus === 'pending' ? 'Pending...' : 'Place order'} {transactionStatus === 'pending' ? t('Pending...') : t('Place order')}
</Button> </Button>
{invalidText && <InputError className="mb-8">{invalidText}</InputError>} {invalidText && <InputError className="mb-8">{invalidText}</InputError>}
</> </>

View File

@ -1,6 +1,6 @@
import { FormGroup, Select } from '@vegaprotocol/ui-toolkit'; import { FormGroup, Select } from '@vegaprotocol/ui-toolkit';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet'; import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { Order } from './use-order-state'; import type { Order } from './use-order-state';
interface TimeInForceSelectorProps { interface TimeInForceSelectorProps {
order: Order; order: Order;
@ -15,7 +15,7 @@ export const TimeInForceSelector = ({
order.type === OrderType.Limit order.type === OrderType.Limit
? Object.entries(OrderTimeInForce) ? Object.entries(OrderTimeInForce)
: Object.entries(OrderTimeInForce).filter( : Object.entries(OrderTimeInForce).filter(
([key, value]) => ([_, value]) =>
value === OrderTimeInForce.FOK || value === OrderTimeInForce.IOC value === OrderTimeInForce.FOK || value === OrderTimeInForce.IOC
); );

View File

@ -1,7 +1,7 @@
import { FormGroup } from '@vegaprotocol/ui-toolkit'; import { FormGroup } from '@vegaprotocol/ui-toolkit';
import { OrderType } from '@vegaprotocol/wallet'; import { OrderType } from '@vegaprotocol/wallet';
import { ButtonRadio } from './button-radio'; import { ButtonRadio } from './button-radio';
import { Order } from './use-order-state'; import type { Order } from './use-order-state';
interface TypeSelectorProps { interface TypeSelectorProps {
order: Order; 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'; import { useState, useCallback } from 'react';
export interface Order { export interface Order {

View File

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

View File

@ -2,15 +2,15 @@ import { useCallback, useEffect, useState } from 'react';
import { gql, useSubscription } from '@apollo/client'; import { gql, useSubscription } from '@apollo/client';
import { ethers } from 'ethers'; import { ethers } from 'ethers';
import { SHA3 } from 'sha3'; import { SHA3 } from 'sha3';
import { Order } from '@vegaprotocol/deal-ticket'; import type { Order } from './use-order-state';
import { OrderType, useVegaWallet } from '@vegaprotocol/wallet'; import { OrderType, useVegaWallet } from '@vegaprotocol/wallet';
import { useVegaTransaction } from './use-vega-transaction'; import { removeDecimal } from '@vegaprotocol/react-helpers';
import { import { useVegaTransaction } from '@vegaprotocol/wallet';
import type {
OrderEvent, OrderEvent,
OrderEventVariables, OrderEventVariables,
OrderEvent_busEvents_event_Order, OrderEvent_busEvents_event_Order,
} from '@vegaprotocol/graphql'; } from './__generated__/OrderEvent';
import { removeDecimal } from '@vegaprotocol/react-helpers';
const ORDER_EVENT_SUB = gql` const ORDER_EVENT_SUB = gql`
subscription OrderEvent($partyId: ID!) { subscription OrderEvent($partyId: ID!) {
@ -64,11 +64,7 @@ export const useOrderSubmit = (market: UseOrderSubmitMarket) => {
return false; return false;
} }
if (e.event.id === id) { return e.event.id === id;
return true;
}
return false;
}); });
if ( if (

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"], "extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"], "ignorePatterns": ["!**/*", "__generated__"],
"overrides": [ "overrides": [
{ {
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

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

View File

@ -3,14 +3,14 @@
// @generated // @generated
// This file was automatically generated and should not be edited. // This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes"; import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
// ==================================================== // ====================================================
// GraphQL fragment: MarketDataFields // GraphQL fragment: MarketDataFields
// ==================================================== // ====================================================
export interface MarketDataFields_market { export interface MarketDataFields_market {
__typename: "Market"; __typename: 'Market';
/** /**
* Market ID * Market ID
*/ */
@ -26,7 +26,7 @@ export interface MarketDataFields_market {
} }
export interface MarketDataFields { export interface MarketDataFields {
__typename: "MarketData"; __typename: 'MarketData';
/** /**
* market id of the associated mark price * market id of the associated mark price
*/ */

View File

@ -3,14 +3,14 @@
// @generated // @generated
// This file was automatically generated and should not be edited. // This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes"; import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
// ==================================================== // ====================================================
// GraphQL subscription operation: MarketDataSub // GraphQL subscription operation: MarketDataSub
// ==================================================== // ====================================================
export interface MarketDataSub_marketData_market { export interface MarketDataSub_marketData_market {
__typename: "Market"; __typename: 'Market';
/** /**
* Market ID * Market ID
*/ */
@ -26,7 +26,7 @@ export interface MarketDataSub_marketData_market {
} }
export interface MarketDataSub_marketData { export interface MarketDataSub_marketData {
__typename: "MarketData"; __typename: 'MarketData';
/** /**
* market id of the associated mark price * market id of the associated mark price
*/ */

View File

@ -3,14 +3,14 @@
// @generated // @generated
// This file was automatically generated and should not be edited. // This file was automatically generated and should not be edited.
import { MarketState, MarketTradingMode } from "./globalTypes"; import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
// ==================================================== // ====================================================
// GraphQL query operation: Markets // GraphQL query operation: Markets
// ==================================================== // ====================================================
export interface Markets_markets_data_market { export interface Markets_markets_data_market {
__typename: "Market"; __typename: 'Market';
/** /**
* Market ID * Market ID
*/ */
@ -26,7 +26,7 @@ export interface Markets_markets_data_market {
} }
export interface Markets_markets_data { export interface Markets_markets_data {
__typename: "MarketData"; __typename: 'MarketData';
/** /**
* market id of the associated mark price * market id of the associated mark price
*/ */
@ -46,7 +46,7 @@ export interface Markets_markets_data {
} }
export interface Markets_markets_tradableInstrument_instrument_product_settlementAsset { export interface Markets_markets_tradableInstrument_instrument_product_settlementAsset {
__typename: "Asset"; __typename: 'Asset';
/** /**
* The symbol of the asset (e.g: GBP) * The symbol of the asset (e.g: GBP)
*/ */
@ -54,7 +54,7 @@ export interface Markets_markets_tradableInstrument_instrument_product_settlemen
} }
export interface Markets_markets_tradableInstrument_instrument_product { export interface Markets_markets_tradableInstrument_instrument_product {
__typename: "Future"; __typename: 'Future';
/** /**
* The name of the asset (string) * The name of the asset (string)
*/ */
@ -62,7 +62,7 @@ export interface Markets_markets_tradableInstrument_instrument_product {
} }
export interface Markets_markets_tradableInstrument_instrument { export interface Markets_markets_tradableInstrument_instrument {
__typename: "Instrument"; __typename: 'Instrument';
/** /**
* A short non necessarily unique code used to easily describe the instrument (e.g: FX:BTCUSD/DEC18) (string) * A short non necessarily unique code used to easily describe the instrument (e.g: FX:BTCUSD/DEC18) (string)
*/ */
@ -74,7 +74,7 @@ export interface Markets_markets_tradableInstrument_instrument {
} }
export interface Markets_markets_tradableInstrument { export interface Markets_markets_tradableInstrument {
__typename: "TradableInstrument"; __typename: 'TradableInstrument';
/** /**
* An instance of or reference to a fully specified instrument. * An instance of or reference to a fully specified instrument.
*/ */
@ -82,7 +82,7 @@ export interface Markets_markets_tradableInstrument {
} }
export interface Markets_markets { export interface Markets_markets {
__typename: "Market"; __typename: 'Market';
/** /**
* Market ID * Market ID
*/ */

View File

@ -1,8 +1,8 @@
import { forwardRef } from 'react'; import { forwardRef } from 'react';
import type { ValueFormatterParams } from 'ag-grid-community'; import type { ValueFormatterParams } from 'ag-grid-community';
import { PriceCell, formatNumber } from '@vegaprotocol/react-helpers'; import { PriceCell, formatNumber, t } from '@vegaprotocol/react-helpers';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/ui-toolkit'; 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 { AgGridColumn } from 'ag-grid-react';
import type { AgGridReact } from 'ag-grid-react'; import type { AgGridReact } from 'ag-grid-react';
@ -18,7 +18,7 @@ export const MarketListTable = forwardRef<AgGridReact, MarketListTableProps>(
return ( return (
<AgGrid <AgGrid
style={{ width: '100%', height: '100%' }} style={{ width: '100%', height: '100%' }}
overlayNoRowsTemplate="No markets" overlayNoRowsTemplate={t('No markets')}
rowData={data} rowData={data}
getRowNodeId={getRowNodeId} getRowNodeId={getRowNodeId}
ref={ref} ref={ref}
@ -32,22 +32,22 @@ export const MarketListTable = forwardRef<AgGridReact, MarketListTableProps>(
components={{ PriceCell }} components={{ PriceCell }}
> >
<AgGridColumn <AgGridColumn
headerName="Market" headerName={t('Market')}
field="tradableInstrument.instrument.code" field="tradableInstrument.instrument.code"
/> />
<AgGridColumn <AgGridColumn
headerName="Settlement asset" headerName={t('Settlement asset')}
field="tradableInstrument.instrument.product.settlementAsset.symbol" field="tradableInstrument.instrument.product.settlementAsset.symbol"
/> />
<AgGridColumn <AgGridColumn
headerName="State" headerName={t('State')}
field="data" field="data"
valueFormatter={({ value }: ValueFormatterParams) => valueFormatter={({ value }: ValueFormatterParams) =>
`${value.market.state} (${value.market.tradingMode})` `${value.market.state} (${value.market.tradingMode})`
} }
/> />
<AgGridColumn <AgGridColumn
headerName="Best bid" headerName={t('Best bid')}
field="data.bestBidPrice" field="data.bestBidPrice"
type="rightAligned" type="rightAligned"
cellRenderer="PriceCell" cellRenderer="PriceCell"
@ -56,7 +56,7 @@ export const MarketListTable = forwardRef<AgGridReact, MarketListTableProps>(
} }
/> />
<AgGridColumn <AgGridColumn
headerName="Best offer" headerName={t('Best offer')}
field="data.bestOfferPrice" field="data.bestOfferPrice"
type="rightAligned" type="rightAligned"
valueFormatter={({ value, data }: ValueFormatterParams) => valueFormatter={({ value, data }: ValueFormatterParams) =>
@ -65,7 +65,7 @@ export const MarketListTable = forwardRef<AgGridReact, MarketListTableProps>(
cellRenderer="PriceCell" cellRenderer="PriceCell"
/> />
<AgGridColumn <AgGridColumn
headerName="Mark price" headerName={t('Mark price')}
field="data.markPrice" field="data.markPrice"
type="rightAligned" type="rightAligned"
cellRenderer="PriceCell" cellRenderer="PriceCell"
@ -73,7 +73,7 @@ export const MarketListTable = forwardRef<AgGridReact, MarketListTableProps>(
formatNumber(value, data.decimalPlaces) formatNumber(value, data.decimalPlaces)
} }
/> />
<AgGridColumn headerName="Description" field="name" /> <AgGridColumn headerName={t('Description')} field="name" />
</AgGrid> </AgGrid>
); );
} }

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 { gql } from '@apollo/client';
import { Markets, Markets_markets } from '../__generated__/Markets'; import type { Markets, Markets_markets } from './__generated__/Markets';
import { makeDataProvider } from './generic-data-provider'; import { makeDataProvider } from '@vegaprotocol/react-helpers';
import { import type {
MarketDataSub, MarketDataSub,
MarketDataSub_marketData, MarketDataSub_marketData,
} from '../__generated__/MarketDataSub'; } from './__generated__/MarketDataSub';
const MARKET_DATA_FRAGMENT = gql` const MARKET_DATA_FRAGMENT = gql`
fragment MarketDataFields on MarketData { 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 { interface GoodThresholdIndicatorProps {
goodThreshold: goodThreshold | undefined; goodThreshold: goodThreshold | undefined;

View File

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

View File

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

View File

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

View File

@ -1,4 +1,5 @@
import { Stats as IStats, StatFields as IStatFields } from './types'; import { t } from '@vegaprotocol/react-helpers';
import type { Stats as IStats, StatFields as IStatFields } from './types';
// Stats fields config. Keys will correspond to graphql queries when used, and values // 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 // contain the associated data and methods we need to render. A single query
@ -6,7 +7,7 @@ import { Stats as IStats, StatFields as IStatFields } from './types';
export const statsFields: { [key in keyof IStats]: IStatFields[] } = { export const statsFields: { [key in keyof IStats]: IStatFields[] } = {
status: [ status: [
{ {
title: 'Status', title: t('Status'),
formatter: (status: string) => { formatter: (status: string) => {
if (!status) { if (!status) {
return; return;
@ -22,123 +23,126 @@ export const statsFields: { [key in keyof IStats]: IStatFields[] } = {
goodThreshold: (status: string) => goodThreshold: (status: string) =>
status === 'CONNECTED' || status === 'CHAIN_STATUS_CONNECTED', status === 'CONNECTED' || status === 'CHAIN_STATUS_CONNECTED',
promoted: true, promoted: true,
description: description: t(
'Status is either connected, replaying, unspecified or disconnected', 'Status is either connected, replaying, unspecified or disconnected'
),
}, },
], ],
blockHeight: [ blockHeight: [
{ {
title: 'Height', title: t('Height'),
goodThreshold: (height: number) => height >= 60, goodThreshold: (height: number) => height >= 60,
promoted: true, promoted: true,
description: 'Block height', description: t('Block height'),
}, },
], ],
totalNodes: [ totalNodes: [
{ {
title: 'Total nodes', title: t('Total nodes'),
description: 'The total number of nodes registered on the network', description: t('The total number of nodes registered on the network'),
}, },
], ],
validatingNodes: [ validatingNodes: [
{ {
title: 'Validating nodes', title: t('Validating nodes'),
promoted: true, promoted: true,
description: 'Nodes participating in consensus', description: t('Nodes participating in consensus'),
}, },
], ],
inactiveNodes: [ inactiveNodes: [
{ {
title: 'Inactive nodes', title: t('Inactive nodes'),
goodThreshold: (totalInactive: number) => totalInactive < 1, goodThreshold: (totalInactive: number) => totalInactive < 1,
description: 'Nodes that are registered but not validating', description: t('Nodes that are registered but not validating'),
}, },
], ],
stakedTotal: [ stakedTotal: [
{ {
title: 'Total staked', title: t('Total staked'),
formatter: (total: string) => formatter: (total: string) =>
total.length > 18 && total.length > 18 &&
parseInt(total.substring(0, total.length - 18)).toLocaleString('en-US'), parseInt(total.substring(0, total.length - 18)).toLocaleString('en-US'),
description: 'Sum of VEGA associated with a Vega key', description: t('Sum of VEGA associated with a Vega key'),
}, },
], ],
backlogLength: [ backlogLength: [
{ {
title: 'Backlog', title: t('Backlog'),
goodThreshold: (length: number, blockDuration: number) => { goodThreshold: (length: number, blockDuration: number) => {
return ( return (
length < 1000 || (length >= 1000 && blockDuration / 1000000000 <= 1) length < 1000 || (length >= 1000 && blockDuration / 1000000000 <= 1)
); );
}, },
description: 'Number of transactions waiting to be processed', description: t('Number of transactions waiting to be processed'),
}, },
], ],
tradesPerSecond: [ tradesPerSecond: [
{ {
title: 'Trades / second', title: t('Trades / second'),
goodThreshold: (trades: number) => trades >= 2, goodThreshold: (trades: number) => trades >= 2,
description: 'Number of trades processed in the last second', description: t('Number of trades processed in the last second'),
}, },
], ],
averageOrdersPerBlock: [ averageOrdersPerBlock: [
{ {
title: 'Orders / block', title: t('Orders / block'),
goodThreshold: (orders: number) => orders >= 2, goodThreshold: (orders: number) => orders >= 2,
description: description: t(
'Number of new orders processed in the last block. All pegged orders and liquidity provisions count as a single order', 'Number of new orders processed in the last block. All pegged orders and liquidity provisions count as a single order'
),
}, },
], ],
ordersPerSecond: [ ordersPerSecond: [
{ {
title: 'Orders / second', title: t('Orders / second'),
goodThreshold: (orders: number) => orders >= 2, goodThreshold: (orders: number) => orders >= 2,
description: description: t(
'Number of orders processed in the last second. All pegged orders and liquidity provisions count as a single order', 'Number of orders processed in the last second. All pegged orders and liquidity provisions count as a single order'
),
}, },
], ],
txPerBlock: [ txPerBlock: [
{ {
title: 'Transactions / block', title: t('Transactions / block'),
goodThreshold: (tx: number) => tx > 2, goodThreshold: (tx: number) => tx > 2,
description: 'Number of transactions processed in the last block', description: t('Number of transactions processed in the last block'),
}, },
], ],
blockDuration: [ blockDuration: [
{ {
title: 'Block time', title: t('Block time'),
formatter: (duration: number) => (duration / 1000000000).toFixed(3), formatter: (duration: number) => (duration / 1000000000).toFixed(3),
goodThreshold: (blockDuration: number) => goodThreshold: (blockDuration: number) =>
blockDuration > 0 && blockDuration <= 2000000000, blockDuration > 0 && blockDuration <= 2000000000,
description: 'Seconds between the two most recent blocks', description: t('Seconds between the two most recent blocks'),
}, },
], ],
vegaTime: [ vegaTime: [
{ {
title: 'Time', title: t('Time'),
formatter: (time: Date) => new Date(time).toLocaleTimeString(), formatter: (time: Date) => new Date(time).toLocaleTimeString(),
goodThreshold: (time: Date) => { goodThreshold: (time: Date) => {
const diff = new Date().getTime() - new Date(time).getTime(); const diff = new Date().getTime() - new Date(time).getTime();
return diff > 0 && diff < 5000; return diff > 0 && diff < 5000;
}, },
description: 'The time on the blockchain', description: t('The time on the blockchain'),
}, },
], ],
appVersion: [ appVersion: [
{ {
title: 'App', title: t('App'),
description: 'Vega node software version on this node', description: t('Vega node software version on this node'),
}, },
], ],
chainVersion: [ chainVersion: [
{ {
title: 'Tendermint', title: t('Tendermint'),
description: 'Tendermint software version on this node', description: t('Tendermint software version on this node'),
}, },
], ],
uptime: [ uptime: [
{ {
title: 'Uptime', title: t('Uptime'),
formatter: (t: string) => { formatter: (t: string) => {
if (!t) { if (!t) {
return; return;
@ -152,23 +156,23 @@ export const statsFields: { [key in keyof IStats]: IStatFields[] } = {
return `${days}d ${hours}h ${mins}m ${secs}s`; return `${days}d ${hours}h ${mins}m ${secs}s`;
}, },
promoted: true, promoted: true,
description: 'Time since genesis', description: t('Time since genesis'),
}, },
{ {
title: 'Up since', title: t('Up since'),
formatter: (t: string) => { formatter: (t: string) => {
if (!t) { if (!t) {
return; return;
} }
return `${new Date(t).toLocaleString().replace(',', ' ')}`; return `${new Date(t).toLocaleString().replace(',', ' ')}`;
}, },
description: 'Genesis', description: t('Genesis'),
}, },
], ],
chainId: [ chainId: [
{ {
title: 'Chain ID', title: t('Chain ID'),
description: 'Identifier', description: t('Identifier'),
}, },
], ],
}; };

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