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,
"minimumDescriptionLength": 10
}
],
"@typescript-eslint/consistent-type-imports": [
"error",
{
"prefer": "type-imports",
"disallowTypeAnnotations": true
}
]
}
},

View File

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

View File

@ -1,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"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

View File

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

View File

@ -1,9 +1,10 @@
import React from 'react';
import { BlockMeta } from '../../routes/blocks/tendermint-blockchain-response';
import type { BlockMeta } from '../../routes/blocks/tendermint-blockchain-response';
import { Routes } from '../../routes/router-config';
import { Link } from 'react-router-dom';
import { SecondsAgo } from '../seconds-ago';
import { TableWithTbody, TableRow, TableCell } from '../table';
import { t } from '@vegaprotocol/react-helpers';
interface BlockProps {
block: BlockMeta;
@ -20,7 +21,7 @@ export const BlockData = ({ block, className }: BlockProps) => {
<TableCell
data-testid="block-height"
className="pl-4 py-2 font-mono"
aria-label="Block height"
aria-label={t('Block height')}
>
<Link
to={`/${Routes.BLOCKS}/${block.header?.height}`}
@ -32,16 +33,16 @@ export const BlockData = ({ block, className }: BlockProps) => {
<TableCell
data-testid="num-txs"
className="px-8 text-center"
aria-label="Number of transactions"
aria-label={t('Number of transactions')}
>
{block.num_txs === '1'
? '1 transaction'
: `${block.num_txs} transactions`}
? t('1 transaction')
: t(`${block.num_txs} transactions`)}
</TableCell>
<TableCell
data-testid="validator-link"
className="px-8 text-center font-mono"
aria-label="Validator"
aria-label={t('Validator')}
>
<Link to={`/${Routes.VALIDATORS}`}>
{block.header.proposer_address}
@ -50,7 +51,7 @@ export const BlockData = ({ block, className }: BlockProps) => {
<TableCell
data-testid="block-time"
className="text-center pr-28 text-neutral-300 w-[170px]"
aria-label="Block genesis"
aria-label={t('Block genesis')}
>
<SecondsAgo date={block.header?.time} />
</TableCell>

View File

@ -1,5 +1,6 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react';
import { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import type { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import { BlockData } from './block-data';
interface BlocksProps {
@ -9,12 +10,14 @@ interface BlocksProps {
export const BlocksData = ({ data, className }: BlocksProps) => {
if (!data?.result) {
return <div className={className}>Awaiting block data</div>;
return <div className={className}>{t('Awaiting block data')}</div>;
}
return (
<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}
>
{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';
interface BlocksRefetchProps {
@ -12,7 +13,7 @@ export const BlocksRefetch = ({ refetch }: BlocksRefetchProps) => {
className="mb-28"
data-testid="refresh"
>
Refresh to see latest blocks
{t('Refresh to see latest blocks')}
</Button>
);
};

View File

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

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { Routes } from '../../routes/router-config';
@ -22,8 +23,8 @@ export const JumpToBlock = () => {
return (
<JumpTo
label="Jump to block"
placeholder="Block number"
label={t('Jump to block')}
placeholder={t('Block number')}
inputId="block-input"
inputType="number"
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 { t } from '@vegaprotocol/react-helpers';
interface JumpToProps {
label: string;
@ -35,7 +36,7 @@ export const JumpTo = ({
className="max-w-[200px]"
/>
<Button variant="secondary" type="submit">
Go
{t('Go')}
</Button>
</div>
</form>

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react';
import { StatusMessage } from '../status-message';
@ -15,12 +16,16 @@ export const RenderFetched = ({
className,
}: RenderFetchedProps) => {
if (loading) {
return <StatusMessage className={className}>Loading...</StatusMessage>;
return (
<StatusMessage className={className}>{t('Loading...')}</StatusMessage>
);
}
if (error) {
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 React, { HTMLAttributes } from 'react';
import type { HTMLAttributes } from 'react';
import React from 'react';
interface RouteTitleProps extends HTMLAttributes<HTMLHeadingElement> {
children: React.ReactNode;

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,6 @@
import { t } from '@vegaprotocol/react-helpers';
import React from 'react';
import { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import type { TendermintBlockchainResponse } from '../../routes/blocks/tendermint-blockchain-response';
import { BlockData } from '../blocks';
import { TxsPerBlock } from './txs-per-block';
@ -13,12 +14,14 @@ export const BlockTxsData = ({ data, className }: TxsProps) => {
// Data for the block has already been fetched at this point, so no errors
// or loading to deal with. This is specifically the case
// 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 (
<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}
>
{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 {
data: TendermintUnconfirmedTransactionsResponse | undefined;
@ -6,7 +7,7 @@ interface TxsProps {
export const TxList = ({ data }: TxsProps) => {
if (!data) {
return <div>Awaiting transactions</div>;
return <div>{t('Awaiting transactions')}</div>;
}
return <div>{JSON.stringify(data, null, ' ')}</div>;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { StatusMessage } from '../../../components/status-message';
import { SyntaxHighlighter } from '../../../components/syntax-highlighter';
import {
@ -7,7 +8,7 @@ import {
TableRow,
} from '../../../components/table';
import { TxOrderType } from '../../../components/txs';
import { ChainExplorerTxResponse } from '../../types/chain-explorer-response';
import type { ChainExplorerTxResponse } from '../../types/chain-explorer-response';
interface TxContentProps {
data: ChainExplorerTxResponse | undefined;
@ -16,7 +17,9 @@ interface TxContentProps {
export const TxContent = ({ data }: TxContentProps) => {
if (!data?.Command) {
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">
<TableRow modifier="bordered">
<TableHeader scope="row" className="w-[160px]">
Type
{t('Type')}
</TableHeader>
<TableCell modifier="bordered">
<TxOrderType orderType={data.Type} />
@ -33,7 +36,7 @@ export const TxContent = ({ data }: TxContentProps) => {
</TableRow>
</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)} />
</>
);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,6 +2,7 @@ import { useRouter } from 'next/router';
import { Vega } from '../icons/vega';
import Link from 'next/link';
import { AnchorButton } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/react-helpers';
export const Navbar = () => {
return (
@ -12,8 +13,8 @@ export const Navbar = () => {
</a>
</Link>
{[
{ name: 'Trading', path: '/markets' },
{ name: 'Portfolio', path: '/portfolio' },
{ name: t('Trading'), path: '/markets' },
{ name: t('Portfolio'), path: '/portfolio' },
].map((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 { DocumentNode } from 'graphql';
import { ReactNode } from 'react';
import { AsyncRenderer } from '../async-renderer';
import type { OperationVariables, QueryHookOptions } from '@apollo/client';
import { useQuery } from '@apollo/client';
import type { DocumentNode } from 'graphql';
import type { ReactNode } from 'react';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
interface PageQueryContainerProps<TData, TVariables> {
query: DocumentNode;

View File

@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/react-helpers';
import { useVegaWallet } from '@vegaprotocol/wallet';
interface VegaWalletButtonProps {
@ -23,7 +24,7 @@ export const VegaWalletButton = ({
onClick={handleClick}
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>
);
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,8 @@
import * as Tabs from '@radix-ui/react-tabs';
import classNames from 'classnames';
import { useRouter } from 'next/router';
import {
Children,
isValidElement,
ReactElement,
ReactNode,
useEffect,
useState,
} from 'react';
import type { ReactElement, ReactNode } from 'react';
import { Children, isValidElement, useEffect, useState } from 'react';
interface GridTabsProps {
children: ReactElement<GridTabProps>[];
@ -25,7 +19,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
}
// 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
@ -51,7 +45,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
>
{Children.map(children, (child) => {
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', {
'text-black dark:text-vega-yellow': 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,
});
return (
<Tabs.Trigger value={child.props.name} className={triggerClass}>
<Tabs.Trigger value={child.props.id} className={triggerClass}>
{child.props.name}
</Tabs.Trigger>
);
@ -70,7 +64,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
{Children.map(children, (child) => {
if (!isValidElement(child)) return null;
return (
<Tabs.Content value={child.props.name} className="h-full">
<Tabs.Content value={child.props.id} className="h-full">
{child.props.children}
</Tabs.Content>
);
@ -82,6 +76,7 @@ export const GridTabs = ({ children, group }: GridTabsProps) => {
interface GridTabProps {
children: ReactNode;
id: string;
name: string;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -3,18 +3,47 @@
// @generated
// 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
// ====================================================
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 {
__typename: "Market";
__typename: 'Market';
/**
* Market full name
*/
@ -39,7 +68,7 @@ export interface OrderEvent_busEvents_event_Order_market {
}
export interface OrderEvent_busEvents_event_Order {
__typename: "Order";
__typename: 'Order';
/**
* Type the order type (defaults to PARTY)
*/
@ -74,10 +103,12 @@ export interface OrderEvent_busEvents_event_Order {
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 {
__typename: "BusEvent";
__typename: 'BusEvent';
/**
* 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 { OrderTimeInForce } from '@vegaprotocol/wallet';
import { TransactionStatus } from './deal-ticket';
import { Market_market } from '@vegaprotocol/graphql';
import type { TransactionStatus } from './deal-ticket';
import { ExpirySelector } from './expiry-selector';
import { SideSelector } from './side-selector';
import { SubmitButton } from './submit-button';
import { TimeInForceSelector } from './time-in-force-selector';
import { TypeSelector } from './type-selector';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
interface DealTicketLimitProps {
order: Order;
updateOrder: (order: Partial<Order>) => void;
transactionStatus: TransactionStatus;
market: Market_market;
market: DealTicketQuery_market;
}
export const DealTicketLimit = ({

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,16 @@
import { Button, InputError } from '@vegaprotocol/ui-toolkit';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/wallet';
import { Market_market } from '@vegaprotocol/graphql';
import { useMemo } from 'react';
import { Order } from './use-order-state';
import type { Order } from './use-order-state';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { TransactionStatus } from './deal-ticket';
import type { TransactionStatus } from './deal-ticket';
import type { DealTicketQuery_market } from './__generated__/DealTicketQuery';
import { MarketState, MarketTradingMode } from '@vegaprotocol/types';
import { t } from '@vegaprotocol/react-helpers';
interface SubmitButtonProps {
transactionStatus: TransactionStatus;
market: Market_market;
market: DealTicketQuery_market;
order: Order;
}
@ -21,29 +23,31 @@ export const SubmitButton = ({
const invalidText = useMemo(() => {
if (!keypair) {
return 'No public key selected';
return t('No public key selected');
}
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 !== 'Active') {
if (market.state === 'Suspended') {
return 'Market is currently suspended';
if (market.state !== MarketState.Active) {
if (market.state === MarketState.Suspended) {
return t('Market is currently suspended');
}
if (market.state === 'Proposed' || market.state === 'Pending') {
return 'Market is not active yet';
if (
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) {
return 'Only limit orders are permitted when market is in auction';
return t('Only limit orders are permitted when market is in auction');
}
if (
@ -53,7 +57,9 @@ export const SubmitButton = ({
OrderTimeInForce.GFN,
].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"
disabled={disabled}
>
{transactionStatus === 'pending' ? 'Pending...' : 'Place order'}
{transactionStatus === 'pending' ? t('Pending...') : t('Place order')}
</Button>
{invalidText && <InputError className="mb-8">{invalidText}</InputError>}
</>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -3,14 +3,14 @@
// @generated
// 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
// ====================================================
export interface MarketDataSub_marketData_market {
__typename: "Market";
__typename: 'Market';
/**
* Market ID
*/
@ -26,7 +26,7 @@ export interface MarketDataSub_marketData_market {
}
export interface MarketDataSub_marketData {
__typename: "MarketData";
__typename: 'MarketData';
/**
* market id of the associated mark price
*/

View File

@ -3,14 +3,14 @@
// @generated
// 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
// ====================================================
export interface Markets_markets_data_market {
__typename: "Market";
__typename: 'Market';
/**
* Market ID
*/
@ -26,7 +26,7 @@ export interface Markets_markets_data_market {
}
export interface Markets_markets_data {
__typename: "MarketData";
__typename: 'MarketData';
/**
* market id of the associated mark price
*/
@ -46,7 +46,7 @@ export interface Markets_markets_data {
}
export interface Markets_markets_tradableInstrument_instrument_product_settlementAsset {
__typename: "Asset";
__typename: 'Asset';
/**
* 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 {
__typename: "Future";
__typename: 'Future';
/**
* The name of the asset (string)
*/
@ -62,7 +62,7 @@ export interface Markets_markets_tradableInstrument_instrument_product {
}
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)
*/
@ -74,7 +74,7 @@ export interface Markets_markets_tradableInstrument_instrument {
}
export interface Markets_markets_tradableInstrument {
__typename: "TradableInstrument";
__typename: 'TradableInstrument';
/**
* An instance of or reference to a fully specified instrument.
*/
@ -82,7 +82,7 @@ export interface Markets_markets_tradableInstrument {
}
export interface Markets_markets {
__typename: "Market";
__typename: 'Market';
/**
* Market ID
*/

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,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
// 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[] } = {
status: [
{
title: 'Status',
title: t('Status'),
formatter: (status: string) => {
if (!status) {
return;
@ -22,123 +23,126 @@ export const statsFields: { [key in keyof IStats]: IStatFields[] } = {
goodThreshold: (status: string) =>
status === 'CONNECTED' || status === 'CHAIN_STATUS_CONNECTED',
promoted: true,
description:
'Status is either connected, replaying, unspecified or disconnected',
description: t(
'Status is either connected, replaying, unspecified or disconnected'
),
},
],
blockHeight: [
{
title: 'Height',
title: t('Height'),
goodThreshold: (height: number) => height >= 60,
promoted: true,
description: 'Block height',
description: t('Block height'),
},
],
totalNodes: [
{
title: 'Total nodes',
description: 'The total number of nodes registered on the network',
title: t('Total nodes'),
description: t('The total number of nodes registered on the network'),
},
],
validatingNodes: [
{
title: 'Validating nodes',
title: t('Validating nodes'),
promoted: true,
description: 'Nodes participating in consensus',
description: t('Nodes participating in consensus'),
},
],
inactiveNodes: [
{
title: 'Inactive nodes',
title: t('Inactive nodes'),
goodThreshold: (totalInactive: number) => totalInactive < 1,
description: 'Nodes that are registered but not validating',
description: t('Nodes that are registered but not validating'),
},
],
stakedTotal: [
{
title: 'Total staked',
title: t('Total staked'),
formatter: (total: string) =>
total.length > 18 &&
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: [
{
title: 'Backlog',
title: t('Backlog'),
goodThreshold: (length: number, blockDuration: number) => {
return (
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: [
{
title: 'Trades / second',
title: t('Trades / second'),
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: [
{
title: 'Orders / block',
title: t('Orders / block'),
goodThreshold: (orders: number) => orders >= 2,
description:
'Number of new orders processed in the last block. All pegged orders and liquidity provisions count as a single order',
description: t(
'Number of new orders processed in the last block. All pegged orders and liquidity provisions count as a single order'
),
},
],
ordersPerSecond: [
{
title: 'Orders / second',
title: t('Orders / second'),
goodThreshold: (orders: number) => orders >= 2,
description:
'Number of orders processed in the last second. All pegged orders and liquidity provisions count as a single order',
description: t(
'Number of orders processed in the last second. All pegged orders and liquidity provisions count as a single order'
),
},
],
txPerBlock: [
{
title: 'Transactions / block',
title: t('Transactions / block'),
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: [
{
title: 'Block time',
title: t('Block time'),
formatter: (duration: number) => (duration / 1000000000).toFixed(3),
goodThreshold: (blockDuration: number) =>
blockDuration > 0 && blockDuration <= 2000000000,
description: 'Seconds between the two most recent blocks',
description: t('Seconds between the two most recent blocks'),
},
],
vegaTime: [
{
title: 'Time',
title: t('Time'),
formatter: (time: Date) => new Date(time).toLocaleTimeString(),
goodThreshold: (time: Date) => {
const diff = new Date().getTime() - new Date(time).getTime();
return diff > 0 && diff < 5000;
},
description: 'The time on the blockchain',
description: t('The time on the blockchain'),
},
],
appVersion: [
{
title: 'App',
description: 'Vega node software version on this node',
title: t('App'),
description: t('Vega node software version on this node'),
},
],
chainVersion: [
{
title: 'Tendermint',
description: 'Tendermint software version on this node',
title: t('Tendermint'),
description: t('Tendermint software version on this node'),
},
],
uptime: [
{
title: 'Uptime',
title: t('Uptime'),
formatter: (t: string) => {
if (!t) {
return;
@ -152,23 +156,23 @@ export const statsFields: { [key in keyof IStats]: IStatFields[] } = {
return `${days}d ${hours}h ${mins}m ${secs}s`;
},
promoted: true,
description: 'Time since genesis',
description: t('Time since genesis'),
},
{
title: 'Up since',
title: t('Up since'),
formatter: (t: string) => {
if (!t) {
return;
}
return `${new Date(t).toLocaleString().replace(',', ' ')}`;
},
description: 'Genesis',
description: t('Genesis'),
},
],
chainId: [
{
title: 'Chain ID',
description: 'Identifier',
title: t('Chain ID'),
description: t('Identifier'),
},
],
};

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