Compare commits

..
Author SHA1 Message Date
Matthew Russell fc101a74a9 chore: add missing depth chart 2024-02-16 12:51:40 -08:00
52 changed files with 701 additions and 2317 deletions
@@ -7,7 +7,6 @@ export type AssetBalanceProps = {
price: string;
showAssetLink?: boolean;
showAssetSymbol?: boolean;
rounded?: boolean;
};
/**
@@ -19,17 +18,12 @@ const AssetBalance = ({
price,
showAssetLink = true,
showAssetSymbol = false,
rounded = false,
}: AssetBalanceProps) => {
const { data: asset, loading } = useAssetDataProvider(assetId);
const label =
!loading && asset && asset.decimals
? addDecimalsFixedFormatNumber(
price,
asset.decimals,
rounded ? 0 : undefined
)
? addDecimalsFixedFormatNumber(price, asset.decimals)
: price;
return (
@@ -41,7 +41,6 @@ export const Header = () => {
Routes.ASSETS,
Routes.MARKETS,
Routes.GOVERNANCE,
Routes.TREASURY,
Routes.NETWORK_PARAMETERS,
Routes.GENESIS,
].map((n) => pages.find((r) => r.path === n))
@@ -32,17 +32,9 @@ export function getNameForParty(id: string, data?: ExplorerNodeNamesQuery) {
export type PartyLinkProps = Partial<ComponentProps<typeof Link>> & {
id: string;
truncate?: boolean;
networkLabel?: string;
truncateLength?: number;
};
const PartyLink = ({
id,
truncate = false,
truncateLength = 4,
networkLabel = t('Network'),
...props
}: PartyLinkProps) => {
const PartyLink = ({ id, truncate = false, ...props }: PartyLinkProps) => {
const { data } = useExplorerNodeNamesQuery();
const name = useMemo(() => getNameForParty(id, data), [data, id]);
const useName = name !== id;
@@ -52,7 +44,7 @@ const PartyLink = ({
if (id === SPECIAL_CASE_NETWORK || id === SPECIAL_CASE_NETWORK_ID) {
return (
<span className="font-mono" data-testid="network">
{networkLabel}
{t('Network')}
</span>
);
}
@@ -78,11 +70,7 @@ const PartyLink = ({
{useName ? (
name
) : (
<Hash
text={
truncate ? truncateMiddle(id, truncateLength, truncateLength) : id
}
/>
<Hash text={truncate ? truncateMiddle(id, 4, 4) : id} />
)}
</Link>
</span>
@@ -175,7 +175,6 @@ describe('Amend order details', () => {
const res = renderExistingAmend('123', 1, amend);
expect(await res.findByText('New size')).toBeInTheDocument();
expect(await res.findByText('Size ±')).toBeInTheDocument();
});
it('Renders Reference if provided', async () => {
@@ -82,7 +82,7 @@ const AmendOrderDetails = ({ id, version, amend }: AmendOrderDetailsProps) => {
{amend.sizeDelta && amend.sizeDelta !== '0' ? (
<div className="mb-12 md:mb-0">
<h2 className="text-dark mb-4 text-2xl font-bold">
{t('Size ±')}
{t('New size')}
</h2>
<h5
className={`mb-0 text-lg font-medium capitalize text-gray-500 ${getSideDeltaColour(
@@ -93,16 +93,6 @@ const AmendOrderDetails = ({ id, version, amend }: AmendOrderDetailsProps) => {
</h5>
</div>
) : null}
{o && (
<div className="">
<h2 className="text-dark mb-4 text-2xl font-bold">
{t('New size')}
</h2>
<h5 className="mb-0 text-lg font-medium text-gray-500">
{o ? o.size : null}
</h5>
</div>
)}
{amend.price && amend.price !== '0' ? (
<div className="">
@@ -34,7 +34,10 @@ export function TransferStatusView({ status, loading }: TransferStatusProps) {
) : (
<>
<p className="leading-10 my-2">
<TransferStatusIcon status={status} />
<Icon
name={getIconForStatus(status)}
className={getColourForStatus(status)}
/>
</p>
<p className="leading-10 my-2">{TransferStatusMapping[status]}</p>
</>
@@ -44,21 +47,6 @@ export function TransferStatusView({ status, loading }: TransferStatusProps) {
);
}
interface TransferStatusIconProps {
status: TransferStatus;
}
export function TransferStatusIcon({ status }: TransferStatusIconProps) {
return (
<span title={TransferStatusMapping[status]}>
<Icon
name={getIconForStatus(status)}
className={getColourForStatus(status)}
/>
</span>
);
}
/**
* Simple mapping from status to icon name
* @param status TransferStatus
@@ -72,8 +60,6 @@ export function getIconForStatus(status: TransferStatus): IconName {
return IconNames.TICK;
case TransferStatus.STATUS_REJECTED:
return IconNames.CROSS;
case TransferStatus.STATUS_CANCELLED:
return IconNames.CROSS;
default:
return IconNames.TIME;
}
@@ -92,8 +78,6 @@ export function getColourForStatus(status: TransferStatus): string {
return 'text-green-500';
case TransferStatus.STATUS_REJECTED:
return 'text-red-500';
case TransferStatus.STATUS_CANCELLED:
return 'text-red-600';
default:
return 'text-yellow-500';
}
@@ -12,5 +12,4 @@ export const Routes = {
ORACLES: 'oracles',
NETWORK_PARAMETERS: 'network-parameters',
DISCLAIMER: 'disclaimer',
TREASURY: 'treasury',
};
@@ -30,7 +30,6 @@ import { PartyAccountsByAsset } from './parties/id/accounts';
import { Disclaimer } from './pages/disclaimer';
import { useFeatureFlags } from '@vegaprotocol/environment';
import RestrictedPage from './restricted';
import { NetworkTreasury } from './treasury';
export type Navigable = {
path: string;
@@ -230,17 +229,6 @@ export const useRouterConfig = () => {
]
: [];
const treasuryRoutes: Route[] = [
{
path: Routes.TREASURY,
handle: {
name: t('Treasury'),
text: t('Treasury'),
breadcrumb: () => <Link to={Routes.TREASURY}>{t('Treasury')}</Link>,
},
element: <NetworkTreasury />,
},
];
const validators: Route[] = featureFlags.EXPLORER_VALIDATORS
? [
{
@@ -370,7 +358,6 @@ export const useRouterConfig = () => {
...marketsRoutes,
...networkParametersRoutes,
...validators,
...treasuryRoutes,
],
},
{
@@ -1,12 +0,0 @@
query ExplorerTreasury {
assetsConnection(pagination: { last: 1000 }) {
edges {
node {
id
networkTreasuryAccount {
balance
}
}
}
}
}
@@ -1,44 +0,0 @@
query ExplorerTreasuryTransfers {
transfersConnection(
partyId: "network"
direction: ToOrFrom
pagination: { last: 200 }
) {
pageInfo {
hasNextPage
}
edges {
node {
transfer {
timestamp
from
amount
to
status
reason
toAccountType
fromAccountType
asset {
id
}
id
status
kind {
... on OneOffTransfer {
deliverOn
}
... on RecurringTransfer {
startEpoch
}
... on OneOffGovernanceTransfer {
deliverOn
}
... on RecurringGovernanceTransfer {
endEpoch
}
}
}
}
}
}
}
@@ -1,52 +0,0 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerTreasuryQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ExplorerTreasuryQuery = { __typename?: 'Query', assetsConnection?: { __typename?: 'AssetsConnection', edges?: Array<{ __typename?: 'AssetEdge', node: { __typename?: 'Asset', id: string, networkTreasuryAccount?: { __typename?: 'AccountBalance', balance: string } | null } } | null> | null } | null };
export const ExplorerTreasuryDocument = gql`
query ExplorerTreasury {
assetsConnection(pagination: {last: 1000}) {
edges {
node {
id
networkTreasuryAccount {
balance
}
}
}
}
}
`;
/**
* __useExplorerTreasuryQuery__
*
* To run a query within a React component, call `useExplorerTreasuryQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerTreasuryQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useExplorerTreasuryQuery({
* variables: {
* },
* });
*/
export function useExplorerTreasuryQuery(baseOptions?: Apollo.QueryHookOptions<ExplorerTreasuryQuery, ExplorerTreasuryQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerTreasuryQuery, ExplorerTreasuryQueryVariables>(ExplorerTreasuryDocument, options);
}
export function useExplorerTreasuryLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerTreasuryQuery, ExplorerTreasuryQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerTreasuryQuery, ExplorerTreasuryQueryVariables>(ExplorerTreasuryDocument, options);
}
export type ExplorerTreasuryQueryHookResult = ReturnType<typeof useExplorerTreasuryQuery>;
export type ExplorerTreasuryLazyQueryHookResult = ReturnType<typeof useExplorerTreasuryLazyQuery>;
export type ExplorerTreasuryQueryResult = Apollo.QueryResult<ExplorerTreasuryQuery, ExplorerTreasuryQueryVariables>;
@@ -1,84 +0,0 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerTreasuryTransfersQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ExplorerTreasuryTransfersQuery = { __typename?: 'Query', transfersConnection?: { __typename?: 'TransferConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean }, edges?: Array<{ __typename?: 'TransferEdge', node: { __typename?: 'TransferNode', transfer: { __typename?: 'Transfer', timestamp: any, from: string, amount: string, to: string, status: Types.TransferStatus, reason?: string | null, toAccountType: Types.AccountType, fromAccountType: Types.AccountType, id: string, asset?: { __typename?: 'Asset', id: string } | null, kind: { __typename?: 'OneOffGovernanceTransfer', deliverOn?: any | null } | { __typename?: 'OneOffTransfer', deliverOn?: any | null } | { __typename?: 'RecurringGovernanceTransfer', endEpoch?: number | null } | { __typename?: 'RecurringTransfer', startEpoch: number } } } } | null> | null } | null };
export const ExplorerTreasuryTransfersDocument = gql`
query ExplorerTreasuryTransfers {
transfersConnection(
partyId: "network"
direction: ToOrFrom
pagination: {last: 200}
) {
pageInfo {
hasNextPage
}
edges {
node {
transfer {
timestamp
from
amount
to
status
reason
toAccountType
fromAccountType
asset {
id
}
id
status
kind {
... on OneOffTransfer {
deliverOn
}
... on RecurringTransfer {
startEpoch
}
... on OneOffGovernanceTransfer {
deliverOn
}
... on RecurringGovernanceTransfer {
endEpoch
}
}
}
}
}
}
}
`;
/**
* __useExplorerTreasuryTransfersQuery__
*
* To run a query within a React component, call `useExplorerTreasuryTransfersQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerTreasuryTransfersQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useExplorerTreasuryTransfersQuery({
* variables: {
* },
* });
*/
export function useExplorerTreasuryTransfersQuery(baseOptions?: Apollo.QueryHookOptions<ExplorerTreasuryTransfersQuery, ExplorerTreasuryTransfersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerTreasuryTransfersQuery, ExplorerTreasuryTransfersQueryVariables>(ExplorerTreasuryTransfersDocument, options);
}
export function useExplorerTreasuryTransfersLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerTreasuryTransfersQuery, ExplorerTreasuryTransfersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerTreasuryTransfersQuery, ExplorerTreasuryTransfersQueryVariables>(ExplorerTreasuryTransfersDocument, options);
}
export type ExplorerTreasuryTransfersQueryHookResult = ReturnType<typeof useExplorerTreasuryTransfersQuery>;
export type ExplorerTreasuryTransfersLazyQueryHookResult = ReturnType<typeof useExplorerTreasuryTransfersLazyQuery>;
export type ExplorerTreasuryTransfersQueryResult = Apollo.QueryResult<ExplorerTreasuryTransfersQuery, ExplorerTreasuryTransfersQueryVariables>;
@@ -1,37 +0,0 @@
// NOTE: These are a temporary measure, pulled from an old branch on console.
import { IconNames } from '@blueprintjs/icons';
import { Icon } from '@vegaprotocol/ui-toolkit';
import { USDc } from './usdc';
import { Vega } from './vega';
import { USDt } from './usdt';
export interface AssetIconProps {
symbol: string;
}
/**
* A poorly implemented, limited support for asset icons.
*
* These are committed as 'deprecated' to discourage use outside the Treasury page. Rather
* than use this, a better approach would be to use source contract addresses to match assets.
* This will be done separately.
*
* @deprecated
*/
export function AssetIcon({ symbol }: AssetIconProps) {
const s = symbol.toLowerCase();
switch (s) {
case 'a4a16e250a09a86061ec83c2f9466fc9dc33d332f86876ee74b6f128a5cd6710': // mainnet
case 'c9fe6fc24fce121b2cc72680543a886055abb560043fda394ba5376203b7527d': // mainnet
return <USDc size={32} />;
case 'd1984e3d365faa05bcafbe41f50f90e3663ee7c0da22bb1e24b164e9532691b2': // mainnet
case 'fc7fd956078fb1fc9db5c19b88f0874c4299b2a7639ad05a47a28c0aef291b55': // testnet
return <Vega size={32} />;
case 'bf1e88d19db4b3ca0d1d5bdb73718a01686b18cf731ca26adedf3c8b83802bba': // mainnet
case 'ede4076aef07fd79502d14326c54ab3911558371baaf697a19d077f4f89de399': // testnet
return <USDt size={32} />;
default:
return <Icon name={IconNames.BANK_ACCOUNT} size={8} />;
}
}
@@ -1,24 +0,0 @@
/**
* See note in index.tsx. This component is intended as a placeholder for a
* better, more generic solution.
*
* @deprecated
*/
export const USDc = ({ size = 16 }: { size?: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 2000 2000">
<path
d="M1000 2000c554.17 0 1000-445.83 1000-1000S1554.17 0 1000 0 0 445.83 0 1000s445.83 1000 1000 1000z"
fill="#2775ca"
/>
<path
d="M1275 1158.33c0-145.83-87.5-195.83-262.5-216.66-125-16.67-150-50-150-108.34s41.67-95.83 125-95.83c75 0 116.67 25 137.5 87.5 4.17 12.5 16.67 20.83 29.17 20.83h66.66c16.67 0 29.17-12.5 29.17-29.16v-4.17c-16.67-91.67-91.67-162.5-187.5-170.83v-100c0-16.67-12.5-29.17-33.33-33.34h-62.5c-16.67 0-29.17 12.5-33.34 33.34v95.83c-125 16.67-204.16 100-204.16 204.17 0 137.5 83.33 191.66 258.33 212.5 116.67 20.83 154.17 45.83 154.17 112.5s-58.34 112.5-137.5 112.5c-108.34 0-145.84-45.84-158.34-108.34-4.16-16.66-16.66-25-29.16-25h-70.84c-16.66 0-29.16 12.5-29.16 29.17v4.17c16.66 104.16 83.33 179.16 220.83 200v100c0 16.66 12.5 29.16 33.33 33.33h62.5c16.67 0 29.17-12.5 33.34-33.33v-100c125-20.84 208.33-108.34 208.33-220.84z"
fill="#fff"
/>
<path
d="M787.5 1595.83c-325-116.66-491.67-479.16-370.83-800 62.5-175 200-308.33 370.83-370.83 16.67-8.33 25-20.83 25-41.67V325c0-16.67-8.33-29.17-25-33.33-4.17 0-12.5 0-16.67 4.16-395.83 125-612.5 545.84-487.5 941.67 75 233.33 254.17 412.5 487.5 487.5 16.67 8.33 33.34 0 37.5-16.67 4.17-4.16 4.17-8.33 4.17-16.66v-58.34c0-12.5-12.5-29.16-25-37.5zM1229.17 295.83c-16.67-8.33-33.34 0-37.5 16.67-4.17 4.17-4.17 8.33-4.17 16.67v58.33c0 16.67 12.5 33.33 25 41.67 325 116.66 491.67 479.16 370.83 800-62.5 175-200 308.33-370.83 370.83-16.67 8.33-25 20.83-25 41.67V1700c0 16.67 8.33 29.17 25 33.33 4.17 0 12.5 0 16.67-4.16 395.83-125 612.5-545.84 487.5-941.67-75-237.5-258.34-416.67-487.5-491.67z"
fill="#fff"
/>
</svg>
);
};
@@ -1,20 +0,0 @@
/**
* See note in index.tsx. This component is intended as a placeholder for a
* better, more generic solution.
*
* @deprecated
*/
export const USDt = ({ size = 16 }: { size?: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 339.43 295.27">
<path
fill="#50af95"
d="M62.15,1.45l-61.89,130a2.52,2.52,0,0,0,.54,2.94L167.95,294.56a2.55,2.55,0,0,0,3.53,0L338.63,134.4a2.52,2.52,0,0,0,.54-2.94l-61.89-130A2.5,2.5,0,0,0,275,0H64.45a2.5,2.5,0,0,0-2.3,1.45h0Z"
/>
<path
fill="#fff"
d="M191.19,144.8v0c-1.2.09-7.4,0.46-21.23,0.46-11,0-18.81-.33-21.55-0.46v0c-42.51-1.87-74.24-9.27-74.24-18.13s31.73-16.25,74.24-18.15v28.91c2.78,0.2,10.74.67,21.74,0.67,13.2,0,19.81-.55,21-0.66v-28.9c42.42,1.89,74.08,9.29,74.08,18.13s-31.65,16.24-74.08,18.12h0Zm0-39.25V79.68h59.2V40.23H89.21V79.68H148.4v25.86c-48.11,2.21-84.29,11.74-84.29,23.16s36.18,20.94,84.29,23.16v82.9h42.78V151.83c48-2.21,84.12-11.73,84.12-23.14s-36.09-20.93-84.12-23.15h0Zm0,0h0Z"
/>
</svg>
);
};
@@ -1,28 +0,0 @@
/**
* See note in index.tsx. This component is intended as a placeholder for a
* better, more generic solution.
*
* @deprecated
*/
export const Vega = ({ size = 16 }: { size?: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 42 42">
<rect width="42" height="42" rx="21" fill="black" />
<path d="M13 27.2726H16.4545V10H13V27.2726Z" fill="white" />
<path d="M25.667 23.8181H29.1215V10H25.667V23.8181Z" fill="white" />
<path d="M19.333 33.6059H22.7875V30.1514H19.333V33.6059Z" fill="white" />
<path
d="M22.7871 30.7271H26.2416V27.2726H22.7871V30.7271Z"
fill="white"
/>
<path
d="M29.1211 27.2726H31.9999V23.8181H29.1211V27.2726Z"
fill="white"
/>
<path
d="M16.4551 30.7271H19.3339V27.2726H16.4551V30.7271Z"
fill="white"
/>
</svg>
);
};
@@ -1,171 +0,0 @@
import type { DeepPartial } from '@apollo/client/utilities';
import { parseResultsToAccounts } from './network-accounts-table';
import {
ExplorerTreasuryDocument,
type ExplorerTreasuryQuery,
} from '../__generated__/Treasury';
import { render, screen } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing';
import { MemoryRouter } from 'react-router-dom';
import { NetworkAccountsTable } from './network-accounts-table';
describe('parseResultsToAccounts', () => {
it('should return an array of non-zero treasury accounts', () => {
const data: DeepPartial<ExplorerTreasuryQuery> = {
assetsConnection: {
edges: [
{
node: {
id: 'asset1',
networkTreasuryAccount: {
balance: '100',
},
},
},
{
node: {
id: 'has0assets',
networkTreasuryAccount: {
balance: '0',
},
},
},
{
node: {
id: 'asset3',
networkTreasuryAccount: {
balance: '50',
},
},
},
{
node: {
id: 'hasnonetworktreasuryaccount',
},
},
],
},
};
const result = parseResultsToAccounts(data as ExplorerTreasuryQuery);
expect(result).toHaveLength(2);
expect(result).toEqual([
{
assetId: 'asset1',
balance: '100',
type: 'ACCOUNT_TYPE_NETWORK_TREASURY',
},
{
assetId: 'asset3',
balance: '50',
type: 'ACCOUNT_TYPE_NETWORK_TREASURY',
},
]);
});
it('should return an empty array if no non-zero accounts are found', () => {
const data: DeepPartial<ExplorerTreasuryQuery> = {
assetsConnection: {
edges: [
{
node: {
id: 'asset1',
networkTreasuryAccount: {
balance: '0',
},
},
},
{
node: {
id: 'asset2',
networkTreasuryAccount: {
balance: '0',
},
},
},
],
},
};
const result = parseResultsToAccounts(data as ExplorerTreasuryQuery);
expect(result).toHaveLength(0);
expect(result).toEqual([]);
});
it('should handle missing data', () => {
const result = parseResultsToAccounts(
undefined as unknown as ExplorerTreasuryQuery
);
expect(result).toHaveLength(0);
expect(result).toEqual([]);
});
});
describe('NetworkAccountsTable', () => {
const mockData: ExplorerTreasuryQuery = {
assetsConnection: {
edges: [
{
node: {
id: 'asset1',
networkTreasuryAccount: {
balance: '100',
},
},
},
{
node: {
id: 'asset2',
networkTreasuryAccount: {
balance: '50',
},
},
},
],
},
};
const mocks = [
{
request: {
query: ExplorerTreasuryDocument,
},
result: {
data: mockData,
},
},
];
it('should render network accounts (as many as match - often just 1)', async () => {
render(
<MockedProvider mocks={mocks} addTypename={false}>
<MemoryRouter>
<NetworkAccountsTable />
</MemoryRouter>
</MockedProvider>
);
// Wait for the data to load
await screen.findByText('Loading...');
// Assert that the network accounts are rendered
expect(screen.getByText('asset1')).toBeInTheDocument();
expect(screen.getByText('asset2')).toBeInTheDocument();
});
it('should handle loading state', async () => {
render(
<MockedProvider mocks={mocks} addTypename={false}>
<MemoryRouter>
<NetworkAccountsTable />
</MemoryRouter>
</MockedProvider>
);
// Assert that the loading state is rendered
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
});
@@ -1,87 +0,0 @@
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import {
type ExplorerTreasuryQuery,
useExplorerTreasuryQuery,
} from '../__generated__/Treasury';
import AssetBalance from '../../../components/asset-balance/asset-balance';
import { AssetLink } from '../../../components/links';
import { useMemo } from 'react';
import { useScreenDimensions } from '@vegaprotocol/react-helpers';
import { AssetIcon } from './asset-icon';
import { type NonZeroAccount } from '../network-treasury';
import { AccountType } from '@vegaprotocol/types';
import { removePaginationWrapper } from '@vegaprotocol/utils';
export const NetworkAccountsTable = () => {
const { data, loading, error } = useExplorerTreasuryQuery({
// This needs to ignore error as old assets may no longer properly resolve
errorPolicy: 'ignore',
});
const { screenSize } = useScreenDimensions();
const shouldRound = useMemo(
() => ['xs', 'sm', 'md', 'lg'].includes(screenSize),
[screenSize]
);
return (
<AsyncRenderer
data={data}
loading={loading}
error={error}
render={(data) => {
const c = parseResultsToAccounts(data);
return (
<section className="md:flex md:flex-row flex-wrap">
{c.map((a) => (
<div className="basis-1/2 md:basis-1/4">
<div className="bg-white rounded overflow-hidden shadow-lg dark:bg-black dark:border-slate-500 dark:border">
<div className="text-center p-6 bg-gray-100 dark:bg-slate-900 border-b dark:border-slate-500">
<p className="flex justify-center">
<AssetIcon symbol={a.assetId} />
</p>
<p className="mt-3" data-testid="name">
<AssetLink assetId={a.assetId} />
</p>
</div>
<div className="text-center py-5" data-testid="balance">
<AssetBalance
assetId={a.assetId}
price={a.balance}
showAssetSymbol={true}
rounded={shouldRound}
/>
</div>
</div>
</div>
))}
</section>
);
}}
/>
);
};
export function parseResultsToAccounts(
data: ExplorerTreasuryQuery
): NonZeroAccount[] {
const nonZeroAccounts: NonZeroAccount[] = [];
if (data?.assetsConnection?.edges) {
const edges = removePaginationWrapper(data?.assetsConnection?.edges);
if (edges) {
edges.forEach((edge) => {
if (
edge.networkTreasuryAccount &&
edge.networkTreasuryAccount?.balance !== '0'
) {
nonZeroAccounts.push({
assetId: edge.id,
balance: edge.networkTreasuryAccount?.balance,
type: AccountType.ACCOUNT_TYPE_NETWORK_TREASURY,
});
}
});
}
}
return nonZeroAccounts;
}
@@ -1,262 +0,0 @@
import { AccountType } from '@vegaprotocol/types';
import {
typeLabel,
getToAccountTypeLabel,
filterAccountTransfers,
} from './network-transfers-table';
import { render, screen } from '@testing-library/react';
import { NetworkTransfersTable } from './network-transfers-table';
import { MockedProvider } from '@apollo/client/testing';
import { MemoryRouter } from 'react-router-dom';
import {
ExplorerTreasuryTransfersDocument,
type ExplorerTreasuryTransfersQuery,
} from '../__generated__/TreasuryTransfers';
import type { DeepPartial } from '@apollo/client/utilities';
describe('typeLabel', () => {
it('should return "Transfer" for "OneOffTransfer" kind', () => {
expect(typeLabel('OneOffTransfer')).toBe('Transfer');
});
it('should return "Transfer" for "RecurringTransfer" kind', () => {
expect(typeLabel('RecurringTransfer')).toBe('Transfer');
});
it('should return "Governance" for "OneOffGovernanceTransfer" kind', () => {
expect(typeLabel('OneOffGovernanceTransfer')).toBe('Governance');
});
it('should return "Governance" for "RecurringGovernanceTransfer" kind', () => {
expect(typeLabel('RecurringGovernanceTransfer')).toBe('Governance');
});
it('should return "Unknown" for unknown kind', () => {
expect(typeLabel()).toBe('Unknown');
expect(typeLabel('')).toBe('Unknown');
expect(typeLabel('InvalidKind')).toBe('Unknown');
});
});
describe('getToAccountTypeLabel', () => {
it('should return "Treasury" when type is ACCOUNT_TYPE_NETWORK_TREASURY', () => {
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_NETWORK_TREASURY)
).toBe('Treasury');
});
it('should return "Fees" when type is any of the fee account types', () => {
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_FEES_INFRASTRUCTURE)
).toBe('Fees');
expect(getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_FEES_MAKER)).toBe(
'Fees'
);
expect(getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_FEES_LIQUIDITY)).toBe(
'Fees'
);
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_LP_LIQUIDITY_FEES)
).toBe('Fees');
expect(
getToAccountTypeLabel(
AccountType.ACCOUNT_TYPE_PENDING_FEE_REFERRAL_REWARD
)
).toBe('Fees');
});
it('should return "Insurance" when type is ACCOUNT_TYPE_GLOBAL_INSURANCE', () => {
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_GLOBAL_INSURANCE)
).toBe('Insurance');
});
it('should return "Rewards" when type is any of the reward account types', () => {
expect(getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_GLOBAL_REWARD)).toBe(
'Rewards'
);
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION)
).toBe('Rewards');
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES)
).toBe('Rewards');
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES)
).toBe('Rewards');
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES)
).toBe('Rewards');
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS)
).toBe('Rewards');
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_RELATIVE_RETURN)
).toBe('Rewards');
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_RETURN_VOLATILITY)
).toBe('Rewards');
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_REWARD_VALIDATOR_RANKING)
).toBe('Rewards');
expect(getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_VESTED_REWARDS)).toBe(
'Rewards'
);
expect(
getToAccountTypeLabel(AccountType.ACCOUNT_TYPE_VESTING_REWARDS)
).toBe('Rewards');
});
it('should return "Other" for any other type', () => {
expect(getToAccountTypeLabel(undefined)).toBe('Other');
expect(getToAccountTypeLabel('unknown' as AccountType)).toBe('Other');
});
});
describe('filterAccountTransfers', () => {
it('filters out transactions that are not to or from a treasury account', () => {
const data: DeepPartial<ExplorerTreasuryTransfersQuery> = {
transfersConnection: {
edges: [
{
node: {
transfer: {
toAccountType: AccountType.ACCOUNT_TYPE_NETWORK_TREASURY,
fromAccountType: AccountType.ACCOUNT_TYPE_FEES_INFRASTRUCTURE,
},
},
},
{
node: {
transfer: {
toAccountType: AccountType.ACCOUNT_TYPE_NETWORK_TREASURY,
fromAccountType:
AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION,
},
},
},
{
node: {
transfer: {
toAccountType: AccountType.ACCOUNT_TYPE_FEES_INFRASTRUCTURE,
fromAccountType: AccountType.ACCOUNT_TYPE_NETWORK_TREASURY,
},
},
},
{
node: {
transfer: {
toAccountType: AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION,
fromAccountType:
AccountType.ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES,
},
},
},
],
},
};
const result = filterAccountTransfers(
data as ExplorerTreasuryTransfersQuery
);
expect(result).toHaveLength(3);
});
it('should return an empty array if no transfers match the filter', () => {
const data: DeepPartial<ExplorerTreasuryTransfersQuery> = {
transfersConnection: {
edges: [
{
node: {
transfer: {
toAccountType: AccountType.ACCOUNT_TYPE_FEES_INFRASTRUCTURE,
fromAccountType: AccountType.ACCOUNT_TYPE_FEES_INFRASTRUCTURE,
},
},
},
{
node: {
transfer: {
toAccountType: AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION,
fromAccountType:
AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION,
},
},
},
],
},
};
const result = filterAccountTransfers(
data as ExplorerTreasuryTransfersQuery
);
expect(result).toHaveLength(0);
});
});
describe('NetworkTransfersTable', () => {
it('renders table headers correctly', async () => {
const mocks = [
{
request: {
query: ExplorerTreasuryTransfersDocument,
},
result: {
data: {
transfersConnection: {
edges: [
{
node: {
transfer: {
id: '123',
toAccountType: AccountType.ACCOUNT_TYPE_NETWORK_TREASURY,
fromAccountType:
AccountType.ACCOUNT_TYPE_NETWORK_TREASURY,
amount: '100',
asset: {
id: '1',
},
timestamp: '2022-01-01T00:00:00Z',
from: 'network',
to: '7100a8a82ef45adb9efa070cc821c6c5c48172d6dc5f842431549490fe5897a0',
reason: '',
status: 'COMPLETED',
kind: {
__typename: 'OneOffGovernanceTransfer',
deliverOn: '123',
},
},
},
},
],
},
},
},
},
];
render(
<MockedProvider mocks={mocks} addTypename={true}>
<MemoryRouter>
<NetworkTransfersTable />
</MemoryRouter>
</MockedProvider>
);
expect(await screen.findByText('Amount')).toBeInTheDocument();
expect(screen.getByText('Asset')).toBeInTheDocument();
expect(screen.getByText('Age')).toBeInTheDocument();
expect(screen.getByText('From')).toBeInTheDocument();
expect(screen.getByText('To')).toBeInTheDocument();
expect(screen.getByText('Status')).toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByTestId('from-account').textContent).toEqual('Treasury');
expect(screen.getByTestId('to-account').textContent).toEqual('7100…97a0');
expect(screen.getByTestId('transfer-kind').textContent).toEqual(
'Governance'
);
});
});
@@ -1,253 +0,0 @@
import { AsyncRenderer, Icon } from '@vegaprotocol/ui-toolkit';
import AssetBalance from '../../../components/asset-balance/asset-balance';
import { AccountType, AccountTypeMapping } from '@vegaprotocol/types';
import { AssetLink, PartyLink } from '../../../components/links';
import {
type ExplorerTreasuryTransfersQuery,
useExplorerTreasuryTransfersQuery,
} from '../__generated__/TreasuryTransfers';
import { TimeAgo } from '../../../components/time-ago';
import { TransferStatusIcon } from '../../../components/txs/details/transfer/blocks/transfer-status';
import { t } from '@vegaprotocol/i18n';
import { IconNames } from '@blueprintjs/icons';
import { useMemo } from 'react';
import { useScreenDimensions } from '@vegaprotocol/react-helpers';
export const colours = {
INCOMING: '!fill-vega-green-600 text-vega-green-600 mr-2',
OUTGOING: '!fill-vega-pink-600 text-vega-pink-600 mr-2',
};
export const theadClasses =
'py-2 border text-center bg-vega-light-150 dark:bg-vega-dark-150';
export function getToAccountTypeLabel(type?: AccountType): string {
switch (type) {
case AccountType.ACCOUNT_TYPE_NETWORK_TREASURY:
return t('Treasury');
case AccountType.ACCOUNT_TYPE_FEES_INFRASTRUCTURE:
case AccountType.ACCOUNT_TYPE_FEES_MAKER:
case AccountType.ACCOUNT_TYPE_FEES_LIQUIDITY:
case AccountType.ACCOUNT_TYPE_LP_LIQUIDITY_FEES:
case AccountType.ACCOUNT_TYPE_PENDING_FEE_REFERRAL_REWARD:
return t('Fees');
case AccountType.ACCOUNT_TYPE_GLOBAL_INSURANCE:
return t('Insurance');
case AccountType.ACCOUNT_TYPE_GLOBAL_REWARD:
case AccountType.ACCOUNT_TYPE_REWARD_AVERAGE_POSITION:
case AccountType.ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES:
case AccountType.ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES:
case AccountType.ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES:
case AccountType.ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS:
case AccountType.ACCOUNT_TYPE_REWARD_RELATIVE_RETURN:
case AccountType.ACCOUNT_TYPE_REWARD_RETURN_VOLATILITY:
case AccountType.ACCOUNT_TYPE_REWARD_VALIDATOR_RANKING:
case AccountType.ACCOUNT_TYPE_VESTED_REWARDS:
case AccountType.ACCOUNT_TYPE_VESTING_REWARDS:
return t('Rewards');
default:
return t('Other');
}
}
export function typeLabel(kind?: string): string {
switch (kind) {
case 'OneOffTransfer':
case 'RecurringTransfer':
return t('Transfer');
case 'OneOffGovernanceTransfer':
case 'RecurringGovernanceTransfer':
return t('Governance');
default:
return t('Unknown');
}
}
export function filterAccountTransfers(data: ExplorerTreasuryTransfersQuery) {
return data.transfersConnection?.edges
?.filter((edge) => {
if (
edge?.node.transfer.toAccountType ===
AccountType.ACCOUNT_TYPE_NETWORK_TREASURY
) {
return true;
} else if (
edge?.node.transfer.fromAccountType ===
AccountType.ACCOUNT_TYPE_NETWORK_TREASURY
) {
return true;
}
return false;
})
.map((edge) => {
return edge?.node.transfer;
});
}
export const NetworkTransfersTable = () => {
const { data, loading, error } = useExplorerTreasuryTransfersQuery({
// This needs to ignore error as old assets may no longer properly resolve
errorPolicy: 'ignore',
});
const { screenSize } = useScreenDimensions();
const shouldRound = useMemo(
() => ['xs', 'sm', 'md', 'lg'].includes(screenSize),
[screenSize]
);
const shouldTruncate = useMemo(
() => ['xs', 'sm', 'md', 'lg', 'xl'].includes(screenSize),
[screenSize]
);
const shouldHideColumns = useMemo(
() => ['xs', 'sm'].includes(screenSize),
[screenSize]
);
return (
<section>
<AsyncRenderer
data={data}
loading={loading}
error={error}
render={(data) => {
const c = filterAccountTransfers(data);
if (!c) {
return null;
}
return (
<table className="table-fixed border-spacing-3">
<thead>
<tr>
<th className={theadClasses}>{t('Amount')}</th>
<th className={theadClasses}>{t('Asset')}</th>
<th className={theadClasses}>{t('Age')}</th>
<th className={theadClasses}>{t('From')}</th>
<th className={theadClasses}>{t('To')}</th>
<th
className={`${theadClasses} ${
shouldHideColumns ? 'hidden' : ''
}`}
>
{t('Status')}
</th>
<th
className={`${theadClasses} ${
shouldHideColumns ? 'hidden' : ''
}`}
>
{t('Type')}
</th>
</tr>
</thead>
<tbody>
{c.map((a) => {
const isIncoming =
a?.toAccountType ===
AccountType.ACCOUNT_TYPE_NETWORK_TREASURY;
return (
<tr>
{a && a.amount && a.asset && (
<td
className={`px-2 py-1 border whitespace-nowrap text-right ${
isIncoming ? colours.INCOMING : colours.OUTGOING
}`}
title={a.amount}
>
{a &&
a.toAccountType ===
AccountType.ACCOUNT_TYPE_NETWORK_TREASURY ? (
<Icon
name={IconNames.PLUS}
className={colours.INCOMING}
/>
) : (
<Icon
name={IconNames.MINUS}
className={colours.OUTGOING}
/>
)}
<AssetBalance
assetId={a.asset.id}
price={a.amount}
showAssetLink={false}
rounded={shouldRound}
/>
</td>
)}
<td className="px-2 py-1 border whitespace-nowrap">
{a && a.amount && a.asset && (
<AssetLink
assetId={a.asset.id}
showAssetSymbol={true}
/>
)}
</td>
<td className="px-2 py-1 border">
{a && a.timestamp && <TimeAgo date={a.timestamp} />}
</td>
<td
className="px-2 py-1 border"
data-testid="from-account"
>
{a && a.from && (
<PartyLink
id={a.from}
truncate={true}
truncateLength={shouldTruncate ? 4 : 15}
networkLabel={t('Treasury')}
/>
)}
</td>
<td className="px-2 py-1 border" data-testid="to-account">
{a && a.to && (
<PartyLink
id={a.to}
networkLabel={t('Treasury')}
truncate={true}
truncateLength={shouldTruncate ? 4 : 15}
/>
)}
{a && !a.to && (
<span
className="underline decoration-dotted"
title={AccountTypeMapping[a.toAccountType]}
>
{getToAccountTypeLabel(a.toAccountType)}
</span>
)}
</td>
<td
className={`px-2 py-1 border text-center ${
shouldHideColumns ? 'hidden' : ''
}`}
>
{a && a.status && (
<TransferStatusIcon status={a.status} />
)}
</td>
<td
className={`px-2 py-1 border ${
shouldHideColumns ? 'hidden' : ''
}`}
>
<span
className="underline decoration-dotted"
title={a?.kind.__typename}
data-testid="transfer-kind"
>
{a && typeLabel(a.kind.__typename)}
</span>
</td>
</tr>
);
})}
</tbody>
</table>
);
}}
/>
</section>
);
};
@@ -1 +0,0 @@
export * from './network-treasury';
@@ -1,28 +0,0 @@
import { useDocumentTitle } from '../../hooks/use-document-title';
import type { AccountType } from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
import { RouteTitle } from '../../components/route-title';
import { NetworkAccountsTable } from './components/network-accounts-table';
import { NetworkTransfersTable } from './components/network-transfers-table';
export type NonZeroAccount = {
assetId: string;
balance: string;
type: AccountType;
};
export const NetworkTreasury = () => {
useDocumentTitle(['Network Treasury']);
return (
<section>
<RouteTitle data-testid="block-header">{t(`Treasury`)}</RouteTitle>
<div>
<NetworkAccountsTable />
</div>
<div className="mt-5">
<h2 className="text-3xl mb-2">{t('Transfers')}</h2>
<NetworkTransfersTable />
</div>
</section>
);
};
-3
View File
@@ -62,9 +62,6 @@ const cache: InMemoryCacheConfig = {
Account: {
keyFields: false,
},
Instrument: {
keyFields: ['code'],
},
Delegation: {
keyFields: false,
// Only get full updates
@@ -160,7 +160,7 @@ describe('Proposal header', () => {
screen.queryByTestId('proposal-description')
).not.toBeInTheDocument();
expect(screen.getByTestId('proposal-details')).toHaveTextContent(
'Update to market: MarketId'
'Update to market ID: MarketId'
);
});
@@ -36,8 +36,6 @@ import { type Proposal, type BatchProposal } from '../../types';
import { type ProposalTermsFieldsFragment } from '../../__generated__/Proposals';
import { differenceInHours, format, formatDistanceToNowStrict } from 'date-fns';
import { DATE_FORMAT_DETAILED } from '../../../../lib/date-formats';
import { getIndicatorStyle } from '../proposal/colours';
import { MarketName } from '../proposal/market-name';
const ProposalTypeTags = ({
proposal,
@@ -140,77 +138,50 @@ const ProposalDetails = ({
);
}
case 'UpdateMarketState': {
const marketPageLink = consoleLink(
CONSOLE_MARKET_PAGE.replace(':marketId', terms.change.market.id)
);
return (
<span>
{featureFlags.UPDATE_MARKET_STATE &&
terms.change?.market?.id &&
terms.change.updateType ? (
<>
<span>{t(terms.change.updateType)}: </span>
<span className="inline-flex gap-2">
<span className="break-all">
<MarketName marketId={terms.change.market.id} />
</span>
<span className="inline-flex items-end gap-0">
<CopyWithTooltip
text={terms.change.market.id}
description={t('copyId')}
>
<button className="inline-block px-1">
<VegaIcon size={20} name={VegaIconNames.COPY} />
</button>
</CopyWithTooltip>
<Tooltip description={t('OpenInConsole')} align="center">
<Link
className="inline-block px-1"
to={marketPageLink}
target="_blank"
>
<VegaIcon
size={20}
name={VegaIconNames.OPEN_EXTERNAL}
/>
</Link>
</Tooltip>
</span>
</span>
{t(terms.change.updateType)}:{' '}
{truncateMiddle(terms.change.market.id)}
</>
) : null}
</span>
);
}
case 'UpdateMarket': {
const marketPageLink = consoleLink(
CONSOLE_MARKET_PAGE.replace(':marketId', terms.change.marketId)
);
return (
<>
<span>{t('UpdateToMarket')}: </span>
<span>{t('UpdateToMarket')}:</span>{' '}
<span className="inline-flex items-start gap-2">
<span className="break-all">
<MarketName marketId={terms.change.marketId} />
</span>
<span className="break-all">{terms.change.marketId} </span>
<span className="inline-flex items-end gap-0">
<CopyWithTooltip
text={terms.change.marketId}
description={t('copyId')}
description={t('copyToClipboard')}
>
<button className="inline-block px-1">
<VegaIcon size={20} name={VegaIconNames.COPY} />
</button>
</CopyWithTooltip>
<Tooltip description={t('OpenInConsole')} align="center">
<Link
<button
className="inline-block px-1"
target="_blank"
to={marketPageLink}
onClick={() => {
const marketPageLink = consoleLink(
CONSOLE_MARKET_PAGE.replace(
':marketId',
// @ts-ignore ts doesn't like this field even though its already a string above???
terms.change.marketId
)
);
window.open(marketPageLink, '_blank');
}}
>
<VegaIcon size={20} name={VegaIconNames.OPEN_EXTERNAL} />
</Link>
</button>
</Tooltip>
</span>
</span>
@@ -315,15 +286,12 @@ const ProposalDetails = ({
{proposal.subProposals.map((p, i) => {
if (!p?.terms) return null;
return (
<li key={i} className="flex gap-3">
<span className={getIndicatorStyle(i + 1)}>{i + 1}</span>
<span>
<div>{renderDetails(p.terms)}</div>
<SubProposalStateText
state={proposal.state}
enactmentDatetime={p.terms.enactmentDatetime}
/>
</span>
<li key={i}>
<div>{renderDetails(p.terms)}</div>
<SubProposalStateText
state={proposal.state}
enactmentDatetime={p.terms.enactmentDatetime}
/>
</li>
);
})}
@@ -9,7 +9,6 @@ import { useState } from 'react';
import { CollapsibleToggle } from '../../../../components/collapsible-toggle';
import { SubHeading } from '../../../../components/heading';
import { type UpdateMarketStatesFragment } from '../../__generated__/Proposals';
import { MarketUpdateTypeMapping } from '@vegaprotocol/types';
interface ProposalUpdateMarketStateProps {
change: UpdateMarketStatesFragment | null;
@@ -50,12 +49,6 @@ export const ProposalUpdateMarketState = ({
{t('marketId')}
{market?.id}
</KeyValueTableRow>
<KeyValueTableRow>
{t('State')}
<span className="bg-vega-green-650 px-1">
{MarketUpdateTypeMapping[change.updateType]}
</span>
</KeyValueTableRow>
<KeyValueTableRow>
{t('marketName')}
{market?.tradableInstrument?.instrument?.name}
@@ -1,33 +0,0 @@
import classNames from 'classnames';
// rainbow-ish order
const COLOURS = ['red', 'pink', 'orange', 'yellow', 'green', 'blue', 'purple'];
const getColour = (indicator: number, max = COLOURS.length) => {
const available =
max < COLOURS.length ? COLOURS.slice(COLOURS.length - max) : COLOURS;
const tiers = Object.keys(available).length;
let index = Math.abs(indicator - 1);
if (indicator >= tiers) {
index = index % tiers;
}
return available[index];
};
export const getStyle = (indicator: number, max = COLOURS.length) =>
classNames({
'bg-vega-yellow-400': 'yellow' === getColour(indicator, max),
'bg-vega-green-400': 'green' === getColour(indicator, max),
'bg-vega-blue-400': 'blue' === getColour(indicator, max),
'bg-vega-purple-400': 'purple' === getColour(indicator, max),
'bg-vega-pink-400': 'pink' === getColour(indicator, max),
'bg-vega-orange-400': 'orange' === getColour(indicator, max),
'bg-vega-red-400': 'red' === getColour(indicator, max),
'bg-vega-clight-600': 'none' === getColour(indicator, max),
});
export const getIndicatorStyle = (indicator: number) =>
classNames(
'rounded-sm text-black inline-block px-1 py-1 font-alpha calt h-8',
getStyle(indicator)
);
@@ -1,14 +0,0 @@
import { useMarketInfoQuery } from '@vegaprotocol/markets';
export const MarketName = ({ marketId }: { marketId?: string }) => {
const { data } = useMarketInfoQuery({
variables: {
marketId: marketId || '',
},
skip: !marketId,
});
return (
<span>{data?.market?.tradableInstrument.instrument.code || marketId}</span>
);
};
@@ -12,26 +12,21 @@ import {
import { ProposalUpdateBenefitTiers } from '../proposal-update-benefit-tiers';
import { ProposalUpdateMarketState } from '../proposal-update-market-state';
import { ProposalVolumeDiscountProgramDetails } from '../proposal-volume-discount-program-details';
import { getIndicatorStyle } from './colours';
export const ProposalChangeDetails = ({
proposal,
terms,
restData,
indicator,
}: {
proposal: Proposal | BatchProposal;
terms: ProposalTermsFieldsFragment;
// eslint-disable-next-line
restData: any;
indicator?: number;
}) => {
let details = null;
switch (terms.change.__typename) {
case 'NewAsset': {
if (proposal.id && terms.change.source.__typename === 'ERC20') {
details = (
return (
<div>
<ListAsset
assetId={proposal.id}
@@ -42,81 +37,62 @@ export const ProposalChangeDetails = ({
</div>
);
}
break;
return null;
}
case 'UpdateAsset': {
if (proposal.id) {
details = (
return (
<ProposalAssetDetails
change={terms.change}
assetId={terms.change.assetId}
/>
);
}
break;
return null;
}
case 'NewMarket': {
if (proposal.id) {
details = <ProposalMarketData proposalId={proposal.id} />;
return <ProposalMarketData proposalId={proposal.id} />;
}
break;
return null;
}
case 'UpdateMarket': {
if (proposal.id) {
const marketId = terms.change.marketId;
const proposalData = restData?.data?.proposal;
let updatedProposal = null;
// single proposal
if ('terms' in proposalData) {
updatedProposal = proposalData?.terms?.updateMarket?.changes;
}
// batch proposal - need to fish for the actual changes
if (
'batchTerms' in proposalData &&
Array.isArray(proposalData.batchTerms?.changes)
) {
updatedProposal = proposalData?.batchTerms?.changes.find(
(ch: { updateMarket?: { marketId: string } }) =>
ch?.updateMarket?.marketId === marketId
)?.updateMarket?.changes;
}
details = (
return (
<div className="flex flex-col gap-4">
<ProposalMarketData proposalId={proposal.id} />
<ProposalMarketChanges
marketId={terms.change.marketId}
updatedProposal={updatedProposal}
updatedProposal={
restData?.data?.proposal?.terms?.updateMarket?.changes
}
/>
</div>
);
}
break;
return null;
}
case 'NewTransfer': {
if (proposal.id) {
details = <ProposalTransferDetails proposalId={proposal.id} />;
return <ProposalTransferDetails proposalId={proposal.id} />;
}
break;
return null;
}
case 'CancelTransfer': {
if (proposal.id) {
details = <ProposalCancelTransferDetails proposalId={proposal.id} />;
return <ProposalCancelTransferDetails proposalId={proposal.id} />;
}
break;
return null;
}
case 'UpdateMarketState': {
details = <ProposalUpdateMarketState change={terms.change} />;
break;
return <ProposalUpdateMarketState change={terms.change} />;
}
case 'UpdateReferralProgram': {
details = <ProposalReferralProgramDetails change={terms.change} />;
break;
return <ProposalReferralProgramDetails change={terms.change} />;
}
case 'UpdateVolumeDiscountProgram': {
details = <ProposalVolumeDiscountProgramDetails change={terms.change} />;
break;
return <ProposalVolumeDiscountProgramDetails change={terms.change} />;
}
case 'UpdateNetworkParameter': {
if (
@@ -124,27 +100,18 @@ export const ProposalChangeDetails = ({
terms.change.networkParameter.key ===
'rewards.activityStreak.benefitTiers'
) {
details = <ProposalUpdateBenefitTiers change={terms.change} />;
return <ProposalUpdateBenefitTiers change={terms.change} />;
}
break;
return null;
}
case 'NewFreeform':
case 'NewSpotMarket':
case 'UpdateSpotMarket':
case 'UpdateSpotMarket': {
return null;
}
default: {
break;
return null;
}
}
if (indicator != null) {
details = (
<div className="flex gap-3 mb-3">
<div className={getIndicatorStyle(indicator)}>{indicator}</div>
<div>{details}</div>
</div>
);
}
return details;
};
@@ -70,7 +70,6 @@ export const Proposal = ({ proposal, restData }: ProposalProps) => {
if (!p?.terms) return null;
return (
<ProposalChangeDetails
indicator={i + 1}
key={i}
proposal={proposal}
terms={p.terms}
@@ -15,7 +15,6 @@ import {
type VoteFieldsFragment,
} from '../../__generated__/Proposals';
import { useBatchVoteInformation } from '../../hooks/use-vote-information';
import { getIndicatorStyle } from '../proposal/colours';
export const CompactVotes = ({ number }: { number: BigNumber }) => (
<CompactNumber
@@ -177,7 +176,6 @@ const VoteBreakdownBatch = ({ proposal }: { proposal: BatchProposal }) => {
if (!p?.terms) return null;
return (
<VoteBreakdownBatchSubProposal
indicator={i + 1}
key={i}
proposal={proposal}
votes={proposal.votes}
@@ -257,12 +255,10 @@ const VoteBreakdownBatchSubProposal = ({
proposal,
votes,
terms,
indicator,
}: {
proposal: BatchProposal;
votes: VoteFieldsFragment;
terms: ProposalTermsFieldsFragment;
indicator?: number;
}) => {
const { t } = useTranslation();
const voteInfo = useVoteInformation({
@@ -273,16 +269,9 @@ const VoteBreakdownBatchSubProposal = ({
const isProposalOpen = proposal?.state === ProposalState.STATE_OPEN;
const isUpdateMarket = terms?.change?.__typename === 'UpdateMarket';
const indicatorElement = indicator && (
<span className={getIndicatorStyle(indicator)}>{indicator}</span>
);
return (
<div>
<div className="flex items-baseline gap-3">
{indicatorElement}
<h4>{t(terms.change.__typename)}</h4>
</div>
<h4>{t(terms.change.__typename)}</h4>
<VoteBreakDownUI
voteInfo={voteInfo}
isProposalOpen={isProposalOpen}
@@ -333,6 +322,7 @@ const VoteBreakDownUI = ({
noPercentage,
noLPPercentage,
yesPercentage,
yesLPPercentage,
yesTokens,
noTokens,
totalEquityLikeShareWeight,
@@ -345,7 +335,6 @@ const VoteBreakDownUI = ({
majorityLPMet,
willPassByTokenVote,
willPassByLPVote,
lpVoteWeight,
} = voteInfo;
const participationThresholdProgress = BigNumber.min(
@@ -425,7 +414,7 @@ const VoteBreakDownUI = ({
data-testid="lp-majority-breakdown"
>
<VoteProgress
percentageFor={lpVoteWeight}
percentageFor={yesLPPercentage}
colourfulBg={true}
testId="lp-majority-progress"
>
@@ -444,10 +433,10 @@ const VoteBreakDownUI = ({
<span>{t('liquidityProviderVotesFor')}:</span>
<Tooltip
description={
<span>{lpVoteWeight.toFixed(defaultDP)}%</span>
<span>{yesLPPercentage.toFixed(defaultDP)}%</span>
}
>
<button>{lpVoteWeight.toFixed(1)}%</button>
<button>{yesLPPercentage.toFixed(1)}%</button>
</Tooltip>
</div>
@@ -273,74 +273,4 @@ describe('use-vote-information', () => {
expect(current?.willPassByTokenVote).toEqual(false);
expect(current?.willPassByLPVote).toEqual(true);
});
it('mainnet recreation: only yes LP votes equal passing', () => {
const yesVotes = 0;
const noVotes = 70;
const yesEquityLikeShareWeight = '0.21';
const noEquityLikeShareWeight = '0';
const fixedTokenValue = 1000000000000000000;
const proposal = generateProposal({
terms: {
change: {
__typename: 'UpdateMarket',
marketId: '12345',
},
},
votes: {
__typename: 'ProposalVotes',
yes: generateYesVotes(
yesVotes,
fixedTokenValue,
yesEquityLikeShareWeight
),
no: generateNoVotes(noVotes, fixedTokenValue, noEquityLikeShareWeight),
},
});
const {
result: { current },
} = renderHook(() =>
useVoteInformation({ terms: proposal.terms, votes: proposal.votes })
);
expect(current?.willPassByTokenVote).toEqual(false);
expect(current?.willPassByLPVote).toEqual(true);
});
it('mainnet recreation: mixed yes and no LP votes equal failing', () => {
const yesVotes = 0;
const noVotes = 70;
const yesEquityLikeShareWeight = '0.21';
const noEquityLikeShareWeight = '0.22';
const fixedTokenValue = 1000000000000000000;
const proposal = generateProposal({
terms: {
change: {
__typename: 'UpdateMarket',
marketId: '12345',
},
},
votes: {
__typename: 'ProposalVotes',
yes: generateYesVotes(
yesVotes,
fixedTokenValue,
yesEquityLikeShareWeight
),
no: generateNoVotes(noVotes, fixedTokenValue, noEquityLikeShareWeight),
},
});
const {
result: { current },
} = renderHook(() =>
useVoteInformation({ terms: proposal.terms, votes: proposal.votes })
);
expect(current?.willPassByTokenVote).toEqual(false);
expect(current?.willPassByLPVote).toEqual(false);
});
});
@@ -123,19 +123,15 @@ const getVoteData = (
totalSupply.multipliedBy(params.requiredParticipation)
);
const lpVoteWeight = yesEquityLikeShareWeight
.dividedBy(totalEquityLikeShareWeight)
.multipliedBy(100);
const participationLPMet = params.requiredParticipationLP
? lpVoteWeight.isGreaterThan(params.requiredParticipationLP)
? totalEquityLikeShareWeight.isGreaterThan(params.requiredParticipationLP)
: false;
const majorityMet = yesPercentage.isGreaterThanOrEqualTo(
requiredMajorityPercentage
);
const majorityLPMet = lpVoteWeight.isGreaterThanOrEqualTo(
const majorityLPMet = yesLPPercentage.isGreaterThanOrEqualTo(
requiredMajorityLPPercentage
);
@@ -153,12 +149,14 @@ const getVoteData = (
const willPassByLPVote =
participationLPMet &&
lpVoteWeight.isGreaterThanOrEqualTo(requiredMajorityLPPercentage);
new BigNumber(yesLPPercentage).isGreaterThanOrEqualTo(
requiredMajorityLPPercentage
);
let willPass = false;
if (changeType === 'UpdateMarket' || changeType === 'UpdateMarketState') {
willPass = willPassByTokenVote || willPassByLPVote;
willPass = willPassByTokenVote && willPassByLPVote;
} else {
willPass = willPassByTokenVote;
}
@@ -184,7 +182,6 @@ const getVoteData = (
totalLPTokensPercentage,
willPassByTokenVote,
willPassByLPVote,
lpVoteWeight: lpVoteWeight.isNaN() ? new BigNumber(0) : lpVoteWeight,
yesVotes: new BigNumber(votes.yes.totalNumber ?? 0),
noVotes: new BigNumber(votes.no.totalNumber ?? 0),
totalVotes: new BigNumber(votes.yes.totalNumber ?? 0).plus(
@@ -1,12 +1,9 @@
import { useT } from '../../lib/use-t';
import { ErrorBoundary } from '@sentry/react';
import { CompetitionsHeader } from '../../components/competitions/competitions-header';
import {
ExternalLink,
Intent,
Loader,
TradingButton,
} from '@vegaprotocol/ui-toolkit';
import { Intent, Loader, TradingButton } from '@vegaprotocol/ui-toolkit';
import { useGameCards } from '../../lib/hooks/use-game-cards';
import { useEpochInfoQuery } from '../../lib/hooks/__generated__/Epoch';
import { Link, useNavigate } from 'react-router-dom';
import { Links } from '../../lib/links';
@@ -21,9 +18,6 @@ import take from 'lodash/take';
import { usePageTitle } from '../../lib/hooks/use-page-title';
import { TeamCard } from '../../components/competitions/team-card';
import { useMyTeam } from '../../lib/hooks/use-my-team';
import { useRewards } from '../../lib/hooks/use-rewards';
import { Trans } from 'react-i18next';
import { DocsLinks } from '@vegaprotocol/environment';
export const CompetitionsHome = () => {
const t = useT();
@@ -34,9 +28,9 @@ export const CompetitionsHome = () => {
const { data: epochData } = useEpochInfoQuery();
const currentEpoch = Number(epochData?.epoch.id);
const { data: gamesData, loading: gamesLoading } = useRewards({
const { data: gamesData, loading: gamesLoading } = useGameCards({
onlyActive: true,
scopeToTeams: true,
currentEpoch,
});
const { data: teamsData, loading: teamsLoading } = useTeams();
@@ -51,34 +45,10 @@ export const CompetitionsHome = () => {
return (
<ErrorBoundary>
<CompetitionsHeader title={t('Competitions')}>
<p className="text-lg mb-3">
<Trans
i18nKey={
'Check the cards below to see what community-created, on-chain games are active and how to compete. Joining a team also lets you take part in the on-chain <0>referral program</0>.'
}
components={[
<Link className="underline" key="ref-prog" to={Links.REFERRALS()}>
referral program
</Link>,
]}
/>
</p>
<p className="text-lg mb-1">
<Trans
i18nKey={
'Got an idea for a competition? Anyone can define and fund one -- <0>propose an on-chain game</0> yourself.'
}
components={[
<ExternalLink
className="underline"
key="propose"
href={DocsLinks?.ASSET_TRANSFER_PROPOSAL}
>
propose an on-chain game
</ExternalLink>,
]}
/>
{/** Docs: https://docs.vega.xyz/mainnet/tutorials/proposals/asset-transfer-proposal */}
{t(
'Be a team player! Participate in games and work together to rake in as much profit to win.'
)}
</p>
</CompetitionsHeader>
@@ -105,7 +75,7 @@ export const CompetitionsHome = () => {
variant="A"
title={t('Create a team')}
description={t(
'Create a new team, share your code with potential members, or set a whitelist for an exclusive group.'
'Lorem ipsum dolor sit amet, consectetur adipisicing elit placeat ipsum minus nemo error dicta.'
)}
actionElement={
<TradingButton
@@ -124,7 +94,7 @@ export const CompetitionsHome = () => {
variant="B"
title={t('Solo team / lone wolf')}
description={t(
'Want to compete but think the best team size is one? This is the option for you.'
'Lorem ipsum dolor sit amet, consectetur adipisicing elit placeat ipsum minus nemo error dicta.'
)}
actionElement={
<TradingButton
@@ -142,7 +112,7 @@ export const CompetitionsHome = () => {
variant="C"
title={t('Join a team')}
description={t(
'Browse existing public teams to find your perfect match.'
'Lorem ipsum dolor sit amet, consectetur adipisicing elit placeat ipsum minus nemo error dicta.'
)}
actionElement={
<TradingButton
@@ -161,57 +131,27 @@ export const CompetitionsHome = () => {
)}
{/** List of available games */}
<h2 className="text-2xl mb-1">{t('Games')}</h2>
<p className="mb-6 text-sm">
<Trans
i18nKey={
'See all the live games on the cards below. Every on-chain game is community funded and designed. <0>Find out how to create one</0>.'
}
components={[
<ExternalLink
className="underline"
key="find-out"
href={DocsLinks?.ASSET_TRANSFER_PROPOSAL}
>
Find out how to create one
</ExternalLink>,
]}
/>
{/** Docs: https://docs.vega.xyz/mainnet/tutorials/proposals/asset-transfer-proposal */}
</p>
<h2 className="text-2xl mb-6">{t('Games')}</h2>
<div className="mb-12 flex">
{gamesLoading ? (
<Loader size="small" />
) : (
<GamesContainer data={gamesData} currentEpoch={currentEpoch} />
)}
</div>
{gamesLoading ? (
<Loader size="small" />
) : (
<GamesContainer data={gamesData} currentEpoch={currentEpoch} />
)}
{/** The teams ranking */}
<div className="mb-1 flex flex-row items-baseline gap-3 justify-between">
<h2 className="text-2xl">
<Link to={Links.COMPETITIONS_TEAMS()} className=" underline">
{t('Leaderboard')}
</Link>
</h2>
<div className="mb-6 flex flex-row items-baseline justify-between">
<h2 className="text-2xl">{t('Leaderboard')}</h2>
<Link to={Links.COMPETITIONS_TEAMS()} className="text-sm underline">
{t('View all teams')}
</Link>
</div>
<p className="mb-6 text-sm">
{t(
'Teams can earn rewards if they meet the goals set in the on-chain trading competitions. Track your earned rewards here, and see which teams are top of the leaderboard this month.'
)}
</p>
<div className="flex">
{teamsLoading ? (
<Loader size="small" />
) : (
<CompetitionsLeaderboard data={take(teamsData, 10)} />
)}
</div>
{teamsLoading ? (
<Loader size="small" />
) : (
<CompetitionsLeaderboard data={take(teamsData, 10)} />
)}
</ErrorBoundary>
);
};
@@ -10,7 +10,11 @@ import {
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { TransferStatus, type Asset } from '@vegaprotocol/types';
import {
TransferStatus,
type Asset,
type RecurringTransfer,
} from '@vegaprotocol/types';
import classNames from 'classnames';
import { useT } from '../../lib/use-t';
import { Table } from '../../components/table';
@@ -40,6 +44,11 @@ import {
areTeamGames,
} from '../../lib/hooks/use-games';
import { useEpochInfoQuery } from '../../lib/hooks/__generated__/Epoch';
import {
type EnrichedTransfer,
isScopedToTeams,
useGameCards,
} from '../../lib/hooks/use-game-cards';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
import {
ActiveRewardCard,
@@ -47,11 +56,6 @@ import {
} from '../../components/rewards-container/active-rewards';
import { type MarketMap, useMarketsMapProvider } from '@vegaprotocol/markets';
import format from 'date-fns/format';
import {
type EnrichedRewardTransfer,
isScopedToTeams,
useRewards,
} from '../../lib/hooks/use-rewards';
export const CompetitionsTeam = () => {
const t = useT();
@@ -74,9 +78,10 @@ const TeamPageContainer = ({ teamId }: { teamId: string | undefined }) => {
const { data: games, loading: gamesLoading } = useGames(teamId);
const { data: transfersData, loading: transfersLoading } = useRewards({
const { data: epochData, loading: epochLoading } = useEpochInfoQuery();
const { data: transfersData, loading: transfersLoading } = useGameCards({
currentEpoch: Number(epochData?.epoch.id),
onlyActive: false,
scopeToTeams: true,
});
const { data: markets } = useMarketsMapProvider();
@@ -107,7 +112,7 @@ const TeamPageContainer = ({ teamId }: { teamId: string | undefined }) => {
games={areTeamGames(games) ? games : undefined}
gamesLoading={gamesLoading}
transfers={transfersData}
transfersLoading={transfersLoading}
transfersLoading={epochLoading || transfersLoading}
allMarkets={markets || undefined}
refetch={refetch}
/>
@@ -132,7 +137,7 @@ const TeamPage = ({
members?: Member[];
games?: TeamGame[];
gamesLoading?: boolean;
transfers?: EnrichedRewardTransfer[];
transfers?: EnrichedTransfer[];
transfersLoading?: boolean;
allMarkets?: MarketMap;
refetch: () => void;
@@ -206,7 +211,7 @@ const Games = ({
}: {
games?: TeamGame[];
gamesLoading?: boolean;
transfers?: EnrichedRewardTransfer[];
transfers?: EnrichedTransfer[];
transfersLoading?: boolean;
allMarkets?: MarketMap;
}) => {
@@ -446,7 +451,7 @@ const GameTypeCell = ({
transfer,
allMarkets,
}: {
transfer?: EnrichedRewardTransfer;
transfer?: EnrichedTransfer;
allMarkets?: MarketMap;
}) => {
const [open, setOpen] = useState(false);
@@ -469,7 +474,7 @@ const GameTypeCell = ({
ref={ref}
className="border-b border-dashed border-vega-clight-200 dark:border-vega-cdark-200 text-left md:truncate md:max-w-[25vw]"
>
<DispatchMetricInfo reward={transfer} />
<DispatchMetricInfo transferNode={transfer} allMarkets={allMarkets} />
</button>
</>
);
@@ -485,7 +490,7 @@ const ActiveRewardCardDialog = ({
open: boolean;
onChange: (isOpen: boolean) => void;
trigger?: HTMLElement | null;
transfer: EnrichedRewardTransfer;
transfer: EnrichedTransfer;
allMarkets?: MarketMap;
}) => {
const t = useT();
@@ -511,6 +516,8 @@ const ActiveRewardCardDialog = ({
<ActiveRewardCard
transferNode={transfer}
currentEpoch={Number(data?.epoch.id)}
kind={transfer.transfer.kind as RecurringTransfer}
allMarkets={allMarkets}
/>
</div>
<div className="w-1/4">
@@ -1,4 +1,5 @@
import { Link } from 'react-router-dom';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { formatNumber } from '@vegaprotocol/utils';
import { type useTeams } from '../../lib/hooks/use-teams';
import { useT } from '../../lib/use-t';
@@ -17,11 +18,7 @@ export const CompetitionsLeaderboard = ({
const num = (n?: number | string) => (!n ? '-' : formatNumber(n, 0));
if (!data || data.length === 0) {
return (
<p className="text-sm">
{t('Currently no active teams on the network.')}
</p>
);
return <Splash>{t('Could not find any teams')}</Splash>;
}
return (
@@ -1,26 +1,28 @@
import { ActiveRewardCard } from '../rewards-container/active-rewards';
import { useT } from '../../lib/use-t';
import { type EnrichedRewardTransfer } from '../../lib/hooks/use-rewards';
import { type EnrichedTransfer } from '../../lib/hooks/use-game-cards';
import { useMarketsMapProvider } from '@vegaprotocol/markets';
export const GamesContainer = ({
data,
currentEpoch,
}: {
data: EnrichedRewardTransfer[];
data: EnrichedTransfer[];
currentEpoch: number;
}) => {
const t = useT();
const { data: markets } = useMarketsMapProvider();
if (!data || data.length === 0) {
return (
<p className="text-sm">
{t('Currently no active games on the network.')}
<p className="mb-6 text-muted">
{t('There are currently no games available.')}
</p>
);
}
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div className="mb-12 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{data.map((game, i) => {
// TODO: Remove `kind` prop from ActiveRewardCard
const { transfer } = game;
@@ -35,6 +37,8 @@ export const GamesContainer = ({
key={i}
transferNode={game}
currentEpoch={currentEpoch}
kind={transfer.kind}
allMarkets={markets || undefined}
/>
);
})}
@@ -1,5 +1,9 @@
import { render, screen } from '@testing-library/react';
import { ActiveRewardCard, applyFilter } from './active-rewards';
import {
ActiveRewardCard,
applyFilter,
isActiveReward,
} from './active-rewards';
import {
AccountType,
AssetStatus,
@@ -7,13 +11,54 @@ import {
DistributionStrategy,
EntityScope,
IndividualScope,
type RecurringTransfer,
type TransferNode,
TransferStatus,
type Transfer,
} from '@vegaprotocol/types';
import { type EnrichedRewardTransfer } from '../../lib/hooks/use-rewards';
jest.mock('./__generated__/Rewards', () => ({
useMarketForRewardsQuery: () => ({
data: undefined,
}),
}));
jest.mock('@vegaprotocol/assets', () => ({
useAssetDataProvider: () => {
return {
data: {
assetId: 'asset-1',
},
};
},
}));
describe('ActiveRewards', () => {
const reward: EnrichedRewardTransfer = {
const mockRecurringTransfer: RecurringTransfer = {
__typename: 'RecurringTransfer',
startEpoch: 115332,
endEpoch: 115432,
factor: '1',
dispatchStrategy: {
__typename: 'DispatchStrategy',
dispatchMetric: DispatchMetric.DISPATCH_METRIC_LP_FEES_RECEIVED,
dispatchMetricAssetId:
'c9fe6fc24fce121b2cc72680543a886055abb560043fda394ba5376203b7527d',
marketIdsInScope: null,
entityScope: EntityScope.ENTITY_SCOPE_INDIVIDUALS,
individualScope: IndividualScope.INDIVIDUAL_SCOPE_ALL,
teamScope: null,
nTopPerformers: '',
stakingRequirement: '',
notionalTimeWeightedAveragePositionRequirement: '',
windowLength: 1,
lockPeriod: 0,
distributionStrategy: DistributionStrategy.DISTRIBUTION_STRATEGY_PRO_RATA,
rankTable: null,
},
};
const mockTransferNode: TransferNode = {
__typename: 'TransferNode',
transfer: {
__typename: 'Transfer',
@@ -41,37 +86,21 @@ describe('ActiveRewards', () => {
reference: 'reward',
status: TransferStatus.STATUS_PENDING,
timestamp: '2023-12-18T13:05:35.948706Z',
kind: {
__typename: 'RecurringTransfer',
startEpoch: 115332,
endEpoch: 115432,
factor: '1',
dispatchStrategy: {
__typename: 'DispatchStrategy',
dispatchMetric: DispatchMetric.DISPATCH_METRIC_LP_FEES_RECEIVED,
dispatchMetricAssetId:
'c9fe6fc24fce121b2cc72680543a886055abb560043fda394ba5376203b7527d',
marketIdsInScope: null,
entityScope: EntityScope.ENTITY_SCOPE_INDIVIDUALS,
individualScope: IndividualScope.INDIVIDUAL_SCOPE_ALL,
teamScope: null,
nTopPerformers: '',
stakingRequirement: '',
notionalTimeWeightedAveragePositionRequirement: '',
windowLength: 1,
lockPeriod: 0,
distributionStrategy:
DistributionStrategy.DISTRIBUTION_STRATEGY_PRO_RATA,
rankTable: null,
},
},
kind: mockRecurringTransfer,
reason: null,
},
fees: [],
};
it('renders with valid props', () => {
render(<ActiveRewardCard transferNode={reward} currentEpoch={115432} />);
render(
<ActiveRewardCard
transferNode={mockTransferNode}
currentEpoch={1}
kind={mockRecurringTransfer}
allMarkets={{}}
/>
);
expect(
screen.getByText(/Liquidity provision fees received/i)
@@ -79,11 +108,41 @@ describe('ActiveRewards', () => {
expect(screen.getByText('Individual scope')).toBeInTheDocument();
expect(screen.getByText('Average position')).toBeInTheDocument();
expect(screen.getByText('Ends in')).toBeInTheDocument();
expect(screen.getByText('1 epoch')).toBeInTheDocument();
expect(screen.getByText('115431 epochs')).toBeInTheDocument();
expect(screen.getByText('Assessed over')).toBeInTheDocument();
expect(screen.getByText('1 epoch')).toBeInTheDocument();
});
describe('isActiveReward', () => {
it('returns true for valid active reward', () => {
const node = {
transfer: {
kind: {
__typename: 'RecurringTransfer',
dispatchStrategy: {},
endEpoch: 10,
},
status: TransferStatus.STATUS_PENDING,
},
} as TransferNode;
expect(isActiveReward(node, 5)).toBeTruthy();
});
it('returns false for invalid active reward', () => {
const node = {
transfer: {
kind: {
__typename: 'RecurringTransfer',
dispatchStrategy: {},
endEpoch: 10,
},
status: TransferStatus.STATUS_PENDING,
},
} as TransferNode;
expect(isActiveReward(node, 15)).toBeFalsy();
});
});
describe('applyFilter', () => {
it('returns true when filter matches dispatch metric label', () => {
const transfer = {
@@ -1,8 +1,12 @@
import { useActiveRewardsQuery } from './__generated__/Rewards';
import { useT } from '../../lib/use-t';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import classNames from 'classnames';
import {
type IconName,
type VegaIconSize,
Icon,
Intent,
Tooltip,
VegaIcon,
VegaIconNames,
@@ -10,12 +14,18 @@ import {
TinyScroll,
truncateMiddle,
} from '@vegaprotocol/ui-toolkit';
import { IconNames } from '@blueprintjs/icons';
import {
type Maybe,
type Transfer,
type TransferNode,
type RecurringTransfer,
DistributionStrategyDescriptionMapping,
DistributionStrategyMapping,
EntityScope,
EntityScopeMapping,
TransferStatus,
TransferStatusMapping,
DispatchMetric,
DispatchMetricDescription,
DispatchMetricLabels,
@@ -26,33 +36,43 @@ import {
IndividualScopeDescriptionMapping,
} from '@vegaprotocol/types';
import { Card } from '../card/card';
import { type ReactNode, useState } from 'react';
import { useMemo, useState } from 'react';
import {
type AssetFieldsFragment,
type BasicAssetDetails,
useAssetsMapProvider,
} from '@vegaprotocol/assets';
import { type MarketFieldsFragment } from '@vegaprotocol/markets';
import {
type EnrichedRewardTransfer,
useRewards,
} from '../../lib/hooks/use-rewards';
import compact from 'lodash/compact';
enum CardColour {
BLUE = 'BLUE',
GREEN = 'GREEN',
GREY = 'GREY',
ORANGE = 'ORANGE',
PINK = 'PINK',
PURPLE = 'PURPLE',
WHITE = 'WHITE',
YELLOW = 'YELLOW',
}
type MarketFieldsFragment,
useMarketsMapProvider,
getAsset,
} from '@vegaprotocol/markets';
export type Filter = {
searchTerm: string;
};
export const isActiveReward = (node: TransferNode, currentEpoch: number) => {
const { transfer } = node;
if (transfer.kind.__typename !== 'RecurringTransfer') {
return false;
}
const { dispatchStrategy } = transfer.kind;
if (!dispatchStrategy) {
return false;
}
if (transfer.kind.endEpoch && transfer.kind.endEpoch < currentEpoch) {
return false;
}
if (transfer.status !== TransferStatus.STATUS_PENDING) {
return false;
}
return true;
};
export const applyFilter = (
node: TransferNode & {
asset?: AssetFieldsFragment | null;
@@ -75,10 +95,7 @@ export const applyFilter = (
transfer.asset?.symbol
.toLowerCase()
.includes(filter.searchTerm.toLowerCase()) ||
(
EntityScopeLabelMapping[transfer.kind.dispatchStrategy.entityScope] ||
'Unspecified'
)
EntityScopeLabelMapping[transfer.kind.dispatchStrategy.entityScope]
.toLowerCase()
.includes(filter.searchTerm.toLowerCase()) ||
node.asset?.name
@@ -97,15 +114,42 @@ export const applyFilter = (
export const ActiveRewards = ({ currentEpoch }: { currentEpoch: number }) => {
const t = useT();
const { data } = useRewards({
onlyActive: true,
const { data: activeRewardsData } = useActiveRewardsQuery({
variables: {
isReward: true,
},
});
const [filter, setFilter] = useState<Filter>({
searchTerm: '',
});
if (!data || !data.length) return null;
const { data: assets } = useAssetsMapProvider();
const { data: markets } = useMarketsMapProvider();
const enrichedTransfers = activeRewardsData?.transfersConnection?.edges
?.map((e) => e?.node as TransferNode)
.filter((node) => isActiveReward(node, currentEpoch))
.map((node) => {
if (node.transfer.kind.__typename !== 'RecurringTransfer') {
return node;
}
const asset =
assets &&
assets[
node.transfer.kind.dispatchStrategy?.dispatchMetricAssetId || ''
];
const marketsInScope =
node.transfer.kind.dispatchStrategy?.marketIdsInScope?.map(
(id) => markets && markets[id]
);
return { ...node, asset, markets: marketsInScope };
});
if (!enrichedTransfers || !enrichedTransfers.length) return null;
return (
<Card
@@ -113,8 +157,7 @@ export const ActiveRewards = ({ currentEpoch }: { currentEpoch: number }) => {
className="lg:col-span-full"
data-testid="active-rewards-card"
>
{/** CARDS FILTER */}
{data.length > 1 && (
{enrichedTransfers.length > 1 && (
<TradingInput
onChange={(e) =>
setFilter((curr) => ({ ...curr, searchTerm: e.target.value }))
@@ -129,32 +172,142 @@ export const ActiveRewards = ({ currentEpoch }: { currentEpoch: number }) => {
prependElement={<VegaIcon name={VegaIconNames.SEARCH} />}
/>
)}
{/** CARDS */}
<TinyScroll className="grid gap-x-8 gap-y-10 h-fit grid-cols-[repeat(auto-fill,_minmax(230px,_1fr))] md:grid-cols-[repeat(auto-fill,_minmax(230px,_1fr))] lg:grid-cols-[repeat(auto-fill,_minmax(320px,_1fr))] xl:grid-cols-[repeat(auto-fill,_minmax(335px,_1fr))] max-h-[40rem] overflow-auto pr-2">
{data
{enrichedTransfers
.filter((n) => applyFilter(n, filter))
.map((node, i) => (
<ActiveRewardCard
key={i}
transferNode={node}
currentEpoch={currentEpoch}
/>
))}
.map((node, i) => {
const { transfer } = node;
if (
transfer.kind.__typename !== 'RecurringTransfer' ||
!transfer.kind.dispatchStrategy?.dispatchMetric
) {
return null;
}
return (
node && (
<ActiveRewardCard
key={i}
transferNode={node}
kind={transfer.kind}
currentEpoch={currentEpoch}
allMarkets={markets || {}}
/>
)
);
})}
</TinyScroll>
</Card>
);
};
// This was built to be a status indicator for the rewards based on the transfer status
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const StatusIndicator = ({
status,
reason,
}: {
status: TransferStatus;
reason?: Maybe<string> | undefined;
}) => {
const t = useT();
const getIconIntent = (status: string) => {
switch (status) {
case TransferStatus.STATUS_DONE:
return { icon: IconNames.TICK_CIRCLE, intent: Intent.Success };
case TransferStatus.STATUS_REJECTED:
return { icon: IconNames.ERROR, intent: Intent.Danger };
default:
return { icon: IconNames.HELP, intent: Intent.Primary };
}
};
const { icon, intent } = getIconIntent(status);
return (
<Tooltip
description={
<span>
{t('Transfer status: {{status}} {{reason}}', {
status: TransferStatusMapping[status],
reason: reason ? `(${reason})` : '',
})}
</span>
}
>
<span
className={classNames(
{
'text-gray-700 dark:text-gray-300': intent === Intent.None,
'text-vega-blue': intent === Intent.Primary,
'text-vega-green dark:text-vega-green': intent === Intent.Success,
'dark:text-yellow text-yellow-600': intent === Intent.Warning,
'text-vega-red': intent === Intent.Danger,
},
'flex items-start p-1 align-text-bottom'
)}
>
<Icon size={3} name={icon as IconName} />
</span>
</Tooltip>
);
};
type ActiveRewardCardProps = {
transferNode: EnrichedRewardTransfer;
transferNode: TransferNode & {
asset?: AssetFieldsFragment | null;
markets?: (MarketFieldsFragment | null)[];
};
currentEpoch: number;
kind: RecurringTransfer;
allMarkets?: Record<string, MarketFieldsFragment | null>;
};
export const ActiveRewardCard = ({
transferNode,
currentEpoch,
kind,
allMarkets,
}: ActiveRewardCardProps) => {
// don't display the cards that are scoped to not trading markets
const marketSettled = transferNode.markets?.filter(
const t = useT();
const { transfer } = transferNode;
const { dispatchStrategy } = kind;
const marketIdsInScope = dispatchStrategy?.marketIdsInScope;
const firstMarketData = transferNode.markets?.[0];
const specificMarkets = useMemo(() => {
if (
!firstMarketData ||
!marketIdsInScope ||
marketIdsInScope.length === 0
) {
return null;
}
if (marketIdsInScope.length > 1) {
const marketNames =
allMarkets &&
marketIdsInScope
.map((id) => allMarkets[id]?.tradableInstrument?.instrument?.name)
.join(', ');
return (
<Tooltip description={marketNames}>
<span>Specific markets</span>
</Tooltip>
);
}
return (
<span>{firstMarketData?.tradableInstrument?.instrument?.name || ''}</span>
);
}, [firstMarketData, marketIdsInScope, allMarkets]);
const dispatchAsset = transferNode.asset;
if (!dispatchStrategy) {
return null;
}
// Gray out/hide the cards that are related to not trading markets
const marketSettled = transferNode.markets?.some(
(m) =>
m?.state &&
[
@@ -165,133 +318,97 @@ export const ActiveRewardCard = ({
].includes(m.state)
);
// hide the card if all of the markets are being marked as e.g. settled
if (
marketSettled?.length === transferNode.markets?.length &&
Boolean(transferNode.markets && transferNode.markets.length > 0)
) {
if (marketSettled) {
return null;
}
let colour =
DispatchMetricColourMap[
transferNode.transfer.kind.dispatchStrategy.dispatchMetric
];
// grey out of any of the markets is suspended or
// if the asset is not currently traded on any of the active markets
const marketSuspended =
transferNode.markets?.filter(
(m) =>
m?.state === MarketState.STATE_SUSPENDED ||
m?.state === MarketState.STATE_SUSPENDED_VIA_GOVERNANCE
).length === transferNode.markets?.length &&
Boolean(transferNode.markets && transferNode.markets.length > 0);
if (marketSuspended || !transferNode.isAssetTraded) {
colour = CardColour.GREY;
}
return (
<RewardCard
colour={colour}
rewardAmount={addDecimalsFormatNumber(
transferNode.transfer.amount,
transferNode.transfer.asset?.decimals || 0,
6
)}
rewardAsset={transferNode.asset}
endsIn={
transferNode.transfer.kind.endEpoch != null
? transferNode.transfer.kind.endEpoch - currentEpoch
: undefined
const assetInActiveMarket =
allMarkets &&
Object.values(allMarkets).some((m: MarketFieldsFragment | null) => {
if (m && getAsset(m).id === dispatchStrategy.dispatchMetricAssetId) {
return m?.state && MarketState.STATE_ACTIVE === m.state;
}
dispatchStrategy={transferNode.transfer.kind.dispatchStrategy}
dispatchMetricInfo={<DispatchMetricInfo reward={transferNode} />}
/>
return false;
});
const marketSuspended = transferNode.markets?.some(
(m) =>
m?.state === MarketState.STATE_SUSPENDED ||
m?.state === MarketState.STATE_SUSPENDED_VIA_GOVERNANCE
);
};
// Gray out the cards that are related to suspended markets
// Or settlement assets in markets that are not active and eligible for rewards
const { gradientClassName, mainClassName } =
marketSuspended || !assetInActiveMarket
? {
gradientClassName: 'from-vega-cdark-500 to-vega-clight-400',
mainClassName: 'from-vega-cdark-400 dark:from-vega-cdark-600 to-20%',
}
: getGradientClasses(dispatchStrategy.dispatchMetric);
const entityScope = dispatchStrategy.entityScope;
const RewardCard = ({
colour,
rewardAmount,
rewardAsset,
dispatchStrategy,
endsIn,
dispatchMetricInfo,
}: {
colour: CardColour;
rewardAmount: string;
/** The asset linked to the dispatch strategy via `dispatchMetricAssetId` property. */
rewardAsset?: BasicAssetDetails;
/** The transfer's dispatch strategy. */
dispatchStrategy: DispatchStrategy;
/** The number of epochs until the transfer stops. */
endsIn?: number;
/** The VEGA asset details, required to format the min staking amount. */
vegaAsset?: BasicAssetDetails;
dispatchMetricInfo?: ReactNode;
}) => {
const t = useT();
return (
<div>
<div
className={classNames(
'bg-gradient-to-r col-span-full p-0.5 lg:col-auto h-full',
'rounded-lg',
CardColourStyles[colour].gradientClassName
gradientClassName
)}
data-testid="active-rewards-card"
>
<div
className={classNames(
CardColourStyles[colour].mainClassName,
'bg-gradient-to-b bg-vega-clight-800 dark:bg-vega-cdark-800 h-full w-full rounded-md p-4 flex flex-col gap-4'
mainClassName,
'bg-gradient-to-b bg-vega-clight-800 dark:bg-vega-cdark-800 h-full w-full rounded p-4 flex flex-col gap-4'
)}
>
<div className="flex justify-between gap-4">
{/** ENTITY SCOPE */}
<div className="flex flex-col gap-2 items-center text-center">
<EntityIcon entityScope={dispatchStrategy.entityScope} />
{dispatchStrategy.entityScope && (
<EntityIcon transfer={transfer} />
{entityScope && (
<span className="text-muted text-xs" data-testid="entity-scope">
{EntityScopeLabelMapping[dispatchStrategy.entityScope] ||
t('Unspecified')}
{EntityScopeLabelMapping[entityScope] || t('Unspecified')}
</span>
)}
</div>
{/** AMOUNT AND DISTRIBUTION STRATEGY */}
<div className="flex flex-col gap-2 items-center text-center">
{/** AMOUNT */}
<h3 className="flex flex-col gap-1 text-2xl shrink-1 text-center">
<span className="font-glitch" data-testid="reward-value">
{rewardAmount}
{addDecimalsFormatNumber(
transferNode.transfer.amount,
transferNode.transfer.asset?.decimals || 0,
6
)}
</span>
<span className="font-alpha">{rewardAsset?.symbol || ''}</span>
<span className="font-alpha">
{transferNode.transfer.asset?.symbol}
</span>
</h3>
{/** DISTRIBUTION STRATEGY */}
<Tooltip
description={t(
DistributionStrategyDescriptionMapping[
dispatchStrategy.distributionStrategy
]
)}
underline={true}
>
<span className="text-xs" data-testid="distribution-strategy">
{
DistributionStrategyMapping[
{
<Tooltip
description={t(
DistributionStrategyDescriptionMapping[
dispatchStrategy.distributionStrategy
]
}
</span>
</Tooltip>
)}
underline={true}
>
<span className="text-xs" data-testid="distribution-strategy">
{
DistributionStrategyMapping[
dispatchStrategy.distributionStrategy
]
}
</span>
</Tooltip>
}
</div>
{/** DISTRIBUTION DELAY */}
<div className="flex flex-col gap-2 items-center text-center">
<CardIcon
iconName={VegaIconNames.LOCK}
@@ -304,59 +421,63 @@ const RewardCard = ({
data-testid="locked-for"
>
{t('numberEpochs', '{{count}} epochs', {
count: dispatchStrategy.lockPeriod,
count: kind.dispatchStrategy?.lockPeriod,
})}
</span>
</div>
</div>
<span className="border-[0.5px] border-gray-700" />
{/** DISPATCH METRIC */}
{dispatchMetricInfo ? (
dispatchMetricInfo
) : (
<span data-testid="dispatch-metric-info">
{DispatchMetricLabels[dispatchStrategy.dispatchMetric]}
</span>
)}
<span data-testid="dispatch-metric-info">
{DispatchMetricLabels[dispatchStrategy.dispatchMetric]} {' '}
<Tooltip
underline={marketSuspended}
description={
(marketSuspended || !assetInActiveMarket) &&
(specificMarkets
? t('Eligible market(s) currently suspended')
: !assetInActiveMarket
? t('Currently no markets eligible for reward')
: '')
}
>
<span>{specificMarkets || dispatchAsset?.name}</span>
</Tooltip>
</span>
<div className="flex items-center gap-8 flex-wrap">
{/** ENDS IN */}
{endsIn != null && (
{kind.endEpoch && (
<span className="flex flex-col">
<span className="text-muted text-xs">{t('Ends in')} </span>
<span data-testid="ends-in" data-endsin={endsIn}>
{endsIn >= 0
? t('numberEpochs', '{{count}} epochs', {
count: endsIn,
})
: t('Ended')}
<span data-testid="ends-in">
{t('numberEpochs', '{{count}} epochs', {
count: kind.endEpoch - currentEpoch,
})}
</span>
</span>
)}
{/** WINDOW LENGTH */}
<span className="flex flex-col">
<span className="text-muted text-xs">{t('Assessed over')}</span>
<span data-testid="assessed-over">
{t('numberEpochs', '{{count}} epochs', {
count: dispatchStrategy.windowLength,
})}
{
<span className="flex flex-col">
<span className="text-muted text-xs">{t('Assessed over')}</span>
<span data-testid="assessed-over">
{t('numberEpochs', '{{count}} epochs', {
count: dispatchStrategy.windowLength,
})}
</span>
</span>
</span>
}
</div>
{/** DISPATCH METRIC DESCRIPTION */}
{dispatchStrategy?.dispatchMetric && (
<span className="text-muted text-sm h-[3rem]">
{t(DispatchMetricDescription[dispatchStrategy?.dispatchMetric])}
</span>
)}
<span className="border-[0.5px] border-gray-700" />
{/** REQUIREMENTS */}
{dispatchStrategy && (
{kind.dispatchStrategy && (
<RewardRequirements
dispatchStrategy={dispatchStrategy}
rewardAsset={rewardAsset}
dispatchStrategy={kind.dispatchStrategy}
assetDecimalPlaces={transfer.asset?.decimals}
/>
)}
</div>
@@ -366,67 +487,77 @@ const RewardCard = ({
};
export const DispatchMetricInfo = ({
reward,
transferNode,
allMarkets,
}: {
reward: EnrichedRewardTransfer;
transferNode: ActiveRewardCardProps['transferNode'];
allMarkets?: ActiveRewardCardProps['allMarkets'];
}) => {
const t = useT();
const dispatchStrategy = reward.transfer.kind.dispatchStrategy;
const marketNames = compact(
reward.markets?.map((m) => m.tradableInstrument.instrument.name)
);
const dispatchStrategy =
transferNode.transfer.kind.__typename === 'RecurringTransfer'
? transferNode.transfer.kind.dispatchStrategy
: null;
let additionalDispatchMetricInfo = null;
const dispatchAsset = transferNode.transfer.asset;
// if asset found then display asset symbol
if (reward.asset) {
additionalDispatchMetricInfo = <span>{reward.asset.symbol}</span>;
}
// but if scoped to only one market then display market name
if (marketNames.length === 1) {
additionalDispatchMetricInfo = <span>{marketNames[0]}</span>;
}
// or if scoped to many markets then indicate it's scoped to "specific markets"
if (marketNames.length > 1) {
additionalDispatchMetricInfo = (
<Tooltip description={marketNames}>
<span>{t('Specific markets')}</span>
</Tooltip>
);
}
const marketIdsInScope = dispatchStrategy?.marketIdsInScope;
const firstMarketData = transferNode.markets?.[0];
const specificMarkets = useMemo(() => {
if (
!firstMarketData ||
!marketIdsInScope ||
marketIdsInScope.length === 0
) {
return null;
}
if (marketIdsInScope.length > 1) {
const marketNames =
allMarkets &&
marketIdsInScope
.map((id) => allMarkets[id]?.tradableInstrument?.instrument?.name)
.join(', ');
return (
<Tooltip description={marketNames}>
<span>Specific markets</span>
</Tooltip>
);
}
const name = firstMarketData?.tradableInstrument?.instrument?.name;
if (name) {
return <span>{name}</span>;
}
return null;
}, [firstMarketData, marketIdsInScope, allMarkets]);
if (!dispatchStrategy) return null;
return (
<span data-testid="dispatch-metric-info">
{DispatchMetricLabels[dispatchStrategy.dispatchMetric]}
{additionalDispatchMetricInfo != null && (
<> {additionalDispatchMetricInfo}</>
)}
{DispatchMetricLabels[dispatchStrategy.dispatchMetric]} {' '}
<span>{specificMarkets || dispatchAsset?.name}</span>
</span>
);
};
const RewardRequirements = ({
dispatchStrategy,
rewardAsset,
vegaAsset,
assetDecimalPlaces = 0,
}: {
dispatchStrategy: DispatchStrategy;
rewardAsset?: BasicAssetDetails;
vegaAsset?: BasicAssetDetails;
assetDecimalPlaces: number | undefined;
}) => {
const t = useT();
const entityLabel = EntityScopeLabelMapping[dispatchStrategy.entityScope];
return (
<dl className="flex justify-between flex-wrap items-center gap-3 text-xs">
<div className="flex flex-col gap-1">
<dt className="flex items-center gap-1 text-muted">
{entityLabel
? t('{{entity}} scope', {
entity: entityLabel,
})
: t('Scope')}
{t('{{entity}} scope', {
entity: EntityScopeLabelMapping[dispatchStrategy.entityScope],
})}
</dt>
<dd className="flex items-center gap-1" data-testid="scope">
<RewardEntityScope dispatchStrategy={dispatchStrategy} />
@@ -443,7 +574,7 @@ const RewardRequirements = ({
>
{addDecimalsFormatNumber(
dispatchStrategy?.stakingRequirement || 0,
vegaAsset?.decimals || 18
assetDecimalPlaces
)}
</dd>
</div>
@@ -456,7 +587,7 @@ const RewardRequirements = ({
{addDecimalsFormatNumber(
dispatchStrategy?.notionalTimeWeightedAveragePositionRequirement ||
0,
rewardAsset?.decimals || 0
assetDecimalPlaces
)}
</dd>
</div>
@@ -514,65 +645,44 @@ const RewardEntityScope = ({
);
}
return t('Unspecified');
return null;
};
const CardColourStyles: Record<
CardColour,
{ gradientClassName: string; mainClassName: string }
> = {
[CardColour.BLUE]: {
gradientClassName: 'from-vega-blue-500 to-vega-green-400',
mainClassName: 'from-vega-blue-400 dark:from-vega-blue-600 to-20%',
},
[CardColour.GREEN]: {
gradientClassName: 'from-vega-green-500 to-vega-yellow-500',
mainClassName: 'from-vega-green-400 dark:from-vega-green-600 to-20%',
},
[CardColour.GREY]: {
gradientClassName: 'from-vega-cdark-500 to-vega-clight-200',
mainClassName: 'from-vega-cdark-400 dark:from-vega-cdark-600 to-20%',
},
[CardColour.ORANGE]: {
gradientClassName: 'from-vega-orange-500 to-vega-pink-400',
mainClassName: 'from-vega-orange-400 dark:from-vega-orange-600 to-20%',
},
[CardColour.PINK]: {
gradientClassName: 'from-vega-pink-500 to-vega-purple-400',
mainClassName: 'from-vega-pink-400 dark:from-vega-pink-600 to-20%',
},
[CardColour.PURPLE]: {
gradientClassName: 'from-vega-purple-500 to-vega-blue-400',
mainClassName: 'from-vega-purple-400 dark:from-vega-purple-600 to-20%',
},
[CardColour.WHITE]: {
gradientClassName:
'from-vega-clight-600 dark:from-vega-clight-900 to-vega-yellow-500 dark:to-vega-yellow-400',
mainClassName: 'from-white dark:from-vega-clight-100 to-20%',
},
[CardColour.YELLOW]: {
gradientClassName: 'from-vega-yellow-500 to-vega-orange-400',
mainClassName: 'from-vega-yellow-400 dark:from-vega-yellow-600 to-20%',
},
};
const DispatchMetricColourMap: Record<DispatchMetric, CardColour> = {
// Liquidity provision fees received
[DispatchMetric.DISPATCH_METRIC_LP_FEES_RECEIVED]: CardColour.BLUE,
// Price maker fees paid
[DispatchMetric.DISPATCH_METRIC_MAKER_FEES_PAID]: CardColour.PINK,
// Price maker fees earned
[DispatchMetric.DISPATCH_METRIC_MAKER_FEES_RECEIVED]: CardColour.GREEN,
// Total market value
[DispatchMetric.DISPATCH_METRIC_MARKET_VALUE]: CardColour.WHITE,
// Average position
[DispatchMetric.DISPATCH_METRIC_AVERAGE_POSITION]: CardColour.ORANGE,
// Relative return
[DispatchMetric.DISPATCH_METRIC_RELATIVE_RETURN]: CardColour.PURPLE,
// Return volatility
[DispatchMetric.DISPATCH_METRIC_RETURN_VOLATILITY]: CardColour.YELLOW,
// Validator ranking
[DispatchMetric.DISPATCH_METRIC_VALIDATOR_RANKING]: CardColour.WHITE,
const getGradientClasses = (d: DispatchMetric | undefined) => {
switch (d) {
case DispatchMetric.DISPATCH_METRIC_AVERAGE_POSITION:
return {
gradientClassName: 'from-vega-pink-500 to-vega-purple-400',
mainClassName: 'from-vega-pink-400 dark:from-vega-pink-600 to-20%',
};
case DispatchMetric.DISPATCH_METRIC_LP_FEES_RECEIVED:
return {
gradientClassName: 'from-vega-green-500 to-vega-yellow-500',
mainClassName: 'from-vega-green-400 dark:from-vega-green-600 to-20%',
};
case DispatchMetric.DISPATCH_METRIC_MAKER_FEES_PAID:
return {
gradientClassName: 'from-vega-orange-500 to-vega-pink-400',
mainClassName: 'from-vega-orange-400 dark:from-vega-orange-600 to-20%',
};
case DispatchMetric.DISPATCH_METRIC_MARKET_VALUE:
case DispatchMetric.DISPATCH_METRIC_RELATIVE_RETURN:
return {
gradientClassName: 'from-vega-purple-500 to-vega-blue-400',
mainClassName: 'from-vega-purple-400 dark:from-vega-purple-600 to-20%',
};
case DispatchMetric.DISPATCH_METRIC_RETURN_VOLATILITY:
return {
gradientClassName: 'from-vega-blue-500 to-vega-green-400',
mainClassName: 'from-vega-blue-400 dark:from-vega-blue-600 to-20%',
};
case DispatchMetric.DISPATCH_METRIC_VALIDATOR_RANKING:
default:
return {
gradientClassName: 'from-vega-pink-500 to-vega-purple-400',
mainClassName: 'from-vega-pink-400 dark:from-vega-pink-600 to-20%',
};
}
};
const CardIcon = ({
@@ -593,29 +703,36 @@ const CardIcon = ({
);
};
const EntityScopeIconMap: Record<EntityScope, VegaIconNames> = {
[EntityScope.ENTITY_SCOPE_TEAMS]: VegaIconNames.TEAM,
[EntityScope.ENTITY_SCOPE_INDIVIDUALS]: VegaIconNames.MAN,
};
const EntityIcon = ({
entityScope,
transfer,
size = 18,
}: {
entityScope: EntityScope;
transfer: Transfer;
size?: VegaIconSize;
}) => {
if (transfer.kind.__typename !== 'RecurringTransfer') {
return null;
}
const entityScope = transfer.kind.dispatchStrategy?.entityScope;
const getIconName = () => {
switch (entityScope) {
case EntityScope.ENTITY_SCOPE_TEAMS:
return VegaIconNames.TEAM;
case EntityScope.ENTITY_SCOPE_INDIVIDUALS:
return VegaIconNames.MAN;
default:
return VegaIconNames.QUESTION_MARK;
}
};
const iconName = getIconName();
return (
<Tooltip
description={
entityScope ? <span>{EntityScopeMapping[entityScope]}</span> : undefined
<span>{entityScope ? EntityScopeMapping[entityScope] : ''}</span>
}
>
<span className="flex items-center p-2 rounded-full border border-gray-600">
<VegaIcon
name={EntityScopeIconMap[entityScope] || VegaIconNames.QUESTION_MARK}
size={size}
/>
{iconName && <VegaIcon name={iconName} size={size} />}
</span>
</Tooltip>
);
@@ -20,7 +20,7 @@ import {
type RewardsPageQuery,
useRewardsPageQuery,
useRewardsEpochQuery,
} from '../../lib/hooks/__generated__/Rewards';
} from './__generated__/Rewards';
import {
TradingButton,
VegaIcon,
@@ -16,7 +16,7 @@ import {
import {
useRewardsHistoryQuery,
type RewardsHistoryQuery,
} from '../../lib/hooks/__generated__/Rewards';
} from './__generated__/Rewards';
import { useRewardsRowData } from './use-reward-row-data';
import { useT } from '../../lib/use-t';
@@ -4,7 +4,7 @@ import BigNumber from 'bignumber.js';
import { removePaginationWrapper } from '@vegaprotocol/utils';
import { type Asset } from '@vegaprotocol/assets';
import { type PartyRewardsConnection } from './rewards-history';
import { type RewardsHistoryQuery } from '../../lib/hooks/__generated__/Rewards';
import { type RewardsHistoryQuery } from './__generated__/Rewards';
const REWARD_ACCOUNT_TYPES = [
AccountType.ACCOUNT_TYPE_GLOBAL_REWARD,
+92
View File
@@ -0,0 +1,92 @@
import compact from 'lodash/compact';
import { useActiveRewardsQuery } from '../../components/rewards-container/__generated__/Rewards';
import { isActiveReward } from '../../components/rewards-container/active-rewards';
import {
type RecurringTransfer,
type TransferNode,
EntityScope,
IndividualScope,
} from '@vegaprotocol/types';
import {
type AssetFieldsFragment,
useAssetsMapProvider,
} from '@vegaprotocol/assets';
import {
type MarketFieldsFragment,
useMarketsMapProvider,
} from '@vegaprotocol/markets';
import { type ApolloError } from '@apollo/client';
export type EnrichedTransfer = TransferNode & {
asset?: AssetFieldsFragment | null;
markets?: (MarketFieldsFragment | null)[];
};
type RecurringTransferKind = EnrichedTransfer & {
transfer: {
kind: RecurringTransfer;
};
};
export const isScopedToTeams = (
node: TransferNode
): node is RecurringTransferKind =>
node.transfer.kind.__typename === 'RecurringTransfer' &&
// scoped to teams
(node.transfer.kind.dispatchStrategy?.entityScope ===
EntityScope.ENTITY_SCOPE_TEAMS ||
// or to individuals
(node.transfer.kind.dispatchStrategy?.entityScope ===
EntityScope.ENTITY_SCOPE_INDIVIDUALS &&
// but they have to be in a team
node.transfer.kind.dispatchStrategy.individualScope ===
IndividualScope.INDIVIDUAL_SCOPE_IN_TEAM));
export const useGameCards = ({
currentEpoch,
onlyActive,
}: {
currentEpoch: number;
onlyActive: boolean;
}): { data: EnrichedTransfer[]; loading: boolean; error?: ApolloError } => {
const { data, loading, error } = useActiveRewardsQuery({
variables: {
isReward: true,
},
fetchPolicy: 'cache-and-network',
});
const { data: assets, loading: assetsLoading } = useAssetsMapProvider();
const { data: markets, loading: marketsLoading } = useMarketsMapProvider();
const games = compact(data?.transfersConnection?.edges?.map((n) => n?.node))
.map((n) => n as TransferNode)
.filter((node) => {
const active = onlyActive ? isActiveReward(node, currentEpoch) : true;
return active && isScopedToTeams(node);
})
.map((node) => {
if (node.transfer.kind.__typename !== 'RecurringTransfer') {
return node;
}
const asset =
assets &&
assets[
node.transfer.kind.dispatchStrategy?.dispatchMetricAssetId || ''
];
const marketsInScope =
node.transfer.kind.dispatchStrategy?.marketIdsInScope?.map(
(id) => markets && markets[id]
);
return { ...node, asset, markets: marketsInScope };
});
return {
data: games,
loading: loading || assetsLoading || marketsLoading,
error,
};
};
-242
View File
@@ -1,242 +0,0 @@
import {
type DispatchStrategy,
type TransferNode,
EntityScope,
type TransferKind,
TransferStatus,
IndividualScope,
} from '@vegaprotocol/types';
import {
type RewardTransfer,
isActiveReward,
isReward,
isScopedToTeams,
} from './use-rewards';
const makeDispatchStrategy = (
entityScope: EntityScope,
individualScope?: IndividualScope
): DispatchStrategy =>
({
entityScope,
individualScope,
} as DispatchStrategy);
const makeReward = (
status: TransferStatus,
startEpoch: number,
endEpoch?: number,
dispatchStrategy?: DispatchStrategy,
kind: TransferKind['__typename'] = 'OneOffTransfer'
): RewardTransfer =>
({
transfer: {
status,
kind: {
__typename: kind,
dispatchStrategy,
startEpoch,
endEpoch,
},
},
} as RewardTransfer);
describe('isReward', () => {
it.each([
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
true,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_INDIVIDUALS),
'RecurringTransfer'
),
true,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
undefined,
'RecurringTransfer'
),
false,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'OneOffTransfer'
),
false,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_INDIVIDUALS),
'OneOffTransfer'
),
false,
],
])('checks if given transfer is a reward or not', (input, output) => {
expect(isReward(input as TransferNode)).toEqual(output);
});
});
describe('isActiveReward', () => {
it.each([
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
true,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
2,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
true,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
3,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
true,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
4, // start in 1 epoch
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
false,
],
[
makeReward(
TransferStatus.STATUS_DONE, // done, not active any more
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
false,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
2, // ended 1 epoch ago
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
false,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
3, // ends now, but active until end of epoch
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS),
'RecurringTransfer'
),
true,
],
])('checks if given reward is active or not', (input, output) => {
expect(isActiveReward(input, 3)).toEqual(output);
});
});
describe('isScopedToTeams', () => {
it.each([
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_TEAMS), // only teams
'RecurringTransfer'
),
true,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(
EntityScope.ENTITY_SCOPE_INDIVIDUALS,
IndividualScope.INDIVIDUAL_SCOPE_IN_TEAM // individual in teams
),
'RecurringTransfer'
),
true,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(EntityScope.ENTITY_SCOPE_INDIVIDUALS), // not in team
'RecurringTransfer'
),
false,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(
EntityScope.ENTITY_SCOPE_INDIVIDUALS,
IndividualScope.INDIVIDUAL_SCOPE_ALL // not only in team
),
'RecurringTransfer'
),
false,
],
[
makeReward(
TransferStatus.STATUS_PENDING,
1,
undefined,
makeDispatchStrategy(
EntityScope.ENTITY_SCOPE_INDIVIDUALS,
IndividualScope.INDIVIDUAL_SCOPE_NOT_IN_TEAM // not in team
),
'RecurringTransfer'
),
false,
],
])('checks if given reward is scoped to teams or not', (input, output) => {
expect(isScopedToTeams(input)).toEqual(output);
});
});
-181
View File
@@ -1,181 +0,0 @@
import {
type AssetFieldsFragment,
useAssetsMapProvider,
} from '@vegaprotocol/assets';
import { useActiveRewardsQuery } from './__generated__/Rewards';
import {
type MarketFieldsFragment,
useMarketsMapProvider,
getAsset,
} from '@vegaprotocol/markets';
import {
type RecurringTransfer,
type TransferNode,
TransferStatus,
type DispatchStrategy,
EntityScope,
IndividualScope,
MarketState,
} from '@vegaprotocol/types';
import { type ApolloError } from '@apollo/client';
import compact from 'lodash/compact';
import { useEpochInfoQuery } from './__generated__/Epoch';
export type RewardTransfer = TransferNode & {
transfer: {
kind: RecurringTransfer & {
dispatchStrategy: DispatchStrategy;
};
};
};
export type EnrichedRewardTransfer = RewardTransfer & {
/** Dispatch metric asset (reward asset) */
asset?: AssetFieldsFragment;
/** A flag determining whether a reward asset is being traded on any of the active markets */
isAssetTraded?: boolean;
/** A list of markets in scope */
markets?: MarketFieldsFragment[];
};
/**
* Checks if given transfer is a reward.
*
* A reward has to be a recurring transfer and has to have a
* dispatch strategy.
*/
export const isReward = (node: TransferNode): node is RewardTransfer => {
if (
node.transfer.kind.__typename === 'RecurringTransfer' &&
node.transfer.kind.dispatchStrategy != null
) {
return true;
}
return false;
};
/**
* Checks if given reward (transfer) is active.
*/
export const isActiveReward = (node: RewardTransfer, currentEpoch: number) => {
const { transfer } = node;
const pending = transfer.status === TransferStatus.STATUS_PENDING;
const withinEpochs =
transfer.kind.startEpoch <= currentEpoch &&
(transfer.kind.endEpoch != null
? transfer.kind.endEpoch >= currentEpoch
: true);
if (pending && withinEpochs) return true;
return false;
};
/**
* Checks if given reward (transfer) is scoped to teams.
*
* A reward is scoped to teams if it's entity scope is set to teams or
* if the scope is set to individuals but the individuals are in a team.
*/
export const isScopedToTeams = (node: EnrichedRewardTransfer) =>
// scoped to teams
node.transfer.kind.dispatchStrategy.entityScope ===
EntityScope.ENTITY_SCOPE_TEAMS ||
// or to individuals
(node.transfer.kind.dispatchStrategy.entityScope ===
EntityScope.ENTITY_SCOPE_INDIVIDUALS &&
// but they have to be in a team
node.transfer.kind.dispatchStrategy.individualScope ===
IndividualScope.INDIVIDUAL_SCOPE_IN_TEAM);
/** Retrieves rewards (transfers) */
export const useRewards = ({
// get active by default
onlyActive = true,
scopeToTeams = false,
}: {
onlyActive: boolean;
scopeToTeams?: boolean;
}): {
data: EnrichedRewardTransfer[];
loading: boolean;
error?: ApolloError | Error;
} => {
const {
data: epochData,
loading: epochLoading,
error: epochError,
} = useEpochInfoQuery({
fetchPolicy: 'network-only',
});
const currentEpoch = Number(epochData?.epoch.id);
const { data, loading, error } = useActiveRewardsQuery({
variables: {
isReward: true,
},
skip: onlyActive && isNaN(currentEpoch),
fetchPolicy: 'cache-and-network',
});
const {
data: assets,
loading: assetsLoading,
error: assetsError,
} = useAssetsMapProvider();
const {
data: markets,
loading: marketsLoading,
error: marketsError,
} = useMarketsMapProvider();
const enriched = compact(
data?.transfersConnection?.edges?.map((n) => n?.node)
)
.map((n) => n as TransferNode)
// make sure we have only rewards here
.filter(isReward)
// take only active rewards if required, otherwise take all
.filter((node) => (onlyActive ? isActiveReward(node, currentEpoch) : true))
// take only those rewards that are scoped to teams if required, otherwise take all
.filter((node) => (scopeToTeams ? isScopedToTeams(node) : true))
// enrich with dispatch asset and markets in scope details
.map((node) => {
const asset =
assets &&
assets[node.transfer.kind.dispatchStrategy.dispatchMetricAssetId];
const marketsInScope = compact(
node.transfer.kind.dispatchStrategy.marketIdsInScope?.map(
(id) => markets && markets[id]
)
);
const isAssetTraded =
markets &&
Object.values(markets).some((m) => {
try {
const mAsset = getAsset(m);
return (
mAsset.id ===
node.transfer.kind.dispatchStrategy.dispatchMetricAssetId &&
m.state === MarketState.STATE_ACTIVE
);
} catch {
// NOOP
}
return false;
});
return {
...node,
asset: asset ? asset : undefined,
isAssetTraded: isAssetTraded != null ? isAssetTraded : undefined,
markets: marketsInScope.length > 0 ? marketsInScope : undefined,
};
});
return {
data: enriched,
loading: loading || assetsLoading || marketsLoading || epochLoading,
error: error || assetsError || marketsError || epochError,
};
};
+4 -25
View File
@@ -93,23 +93,16 @@ export const useEnabledAssets = () => {
/** Wrapped ETH symbol */
const WETH = 'WETH';
/** VEGA */
const VEGA = 'VEGA';
export type BasicAssetDetails = Pick<
AssetFieldsFragment,
'symbol' | 'decimals' | 'quantum'
>;
type WETHDetails = Pick<AssetFieldsFragment, 'symbol' | 'decimals' | 'quantum'>;
/**
* Tries to find WETH asset configuration on Vega in order to provide its
* details, otherwise it returns hardcoded values.
*/
export const useWETH = (): BasicAssetDetails => {
export const useWETH = (): WETHDetails => {
const { data } = useAssetsDataProvider();
if (data) {
const details = data.find((a) => a.symbol.toUpperCase() === WETH);
if (details) return details;
const weth = data.find((a) => a.symbol.toUpperCase() === WETH);
if (weth) return weth;
}
return {
@@ -118,17 +111,3 @@ export const useWETH = (): BasicAssetDetails => {
quantum: '500000000000000', // 1 WETH ~= 2000 qUSD
};
};
export const useVEGA = (): BasicAssetDetails => {
const { data } = useAssetsDataProvider();
if (data) {
const details = data.find((a) => a.symbol.toUpperCase() === VEGA);
if (details) return details;
}
return {
symbol: VEGA,
decimals: 18,
quantum: '1000000000000000000', // 1 VEGA ~= 1 qUSD
};
};
-1
View File
@@ -87,7 +87,6 @@ export const DocsLinks = VEGA_DOCS_URL
QUANTUM: `${VEGA_DOCS_URL}/concepts/assets/asset-framework#quantum`,
REFERRALS: `${VEGA_DOCS_URL}/tutorials/proposals/referral-program-proposal`,
LIQUIDITY_FEE_PERCENTAGE: `${VEGA_DOCS_URL}/concepts/liquidity/rewards-penalties#determining-the-liquidity-fee-percentage`,
ASSET_TRANSFER_PROPOSAL: `${VEGA_DOCS_URL}/tutorials/proposals/asset-transfer-proposal`,
}
: undefined;
+1 -2
View File
@@ -159,7 +159,6 @@
"ContinueSharingData": "Continue sharing data",
"copied!": "Copied!",
"copyToClipboard": "Copy to clipboard",
"copyId": "Copy ID to clipboard",
"CouldNotInstantiateMarket": "Could not instantiate market",
"created": "Created",
"CreateProposalAndDownloadJSONToShare": "Create proposal and download JSON to share",
@@ -808,7 +807,7 @@
"unsupportedVersion": "Looks like you're running an outdated version of GoWallet. You're running {{version}} but {{requiredVersion}} is required.",
"UpdateAsset": "Update asset",
"UpdateAssetProposal": "Update asset proposal",
"UpdateToMarket": "Update to market",
"UpdateToMarket": "Update to market ID",
"OpenInConsole": "Open in Console",
"UpdateMarket": "Update market",
"UpdateMarketProposal": "Update market proposal",
+2 -10
View File
@@ -445,6 +445,7 @@
"Leaderboard": "Leaderboard",
"View all teams": "View all teams",
"Competitions": "Competitions",
"Be a team player! Participate in games and work together to rake in as much profit to win.": "Be a team player! Participate in games and work together to rake in as much profit to win.",
"Create a public team": "Create a public team",
"Create a private team": "Create a private team",
"Choose a team": "Choose a team",
@@ -461,14 +462,5 @@
"Daily reward amount": "Daily reward amount",
"Amount earned this epoch": "Amount earned this epoch",
"Cumulative amount earned": "Cumulative amount earned",
"Game details": "Game details",
"Check the cards below to see what community-created, on-chain games are active and how to compete. Joining a team also lets you take part in the on-chain <0>referral program</0>.": "Check the cards below to see what community-created, on-chain games are active and how to compete. Joining a team also lets you take part in the on-chain <0>referral program</0>.",
"Got an idea for a competition? Anyone can define and fund one -- <0>propose an on-chain game</0> yourself.": "Got an idea for a competition? Anyone can define and fund one -- <0>propose an on-chain game</0> yourself.",
"Create a new team, share your code with potential members, or set a whitelist for an exclusive group.": "Create a new team, share your code with potential members, or set a whitelist for an exclusive group.",
"Want to compete but think the best team size is one? This is the option for you.": "Want to compete but think the best team size is one? This is the option for you.",
"Browse existing public teams to find your perfect match.": "Browse existing public teams to find your perfect match.",
"See all the live games on the cards below. Every on-chain game is community funded and designed. <0>Find out how to create one</0>.": "See all the live games on the cards below. Every on-chain game is community funded and designed. <0>Find out how to create one</0>.",
"Teams can earn rewards if they meet the goals set in the on-chain trading competitions. Track your earned rewards here, and see which teams are top of the leaderboard this month.": "Teams can earn rewards if they meet the goals set in the on-chain trading competitions. Track your earned rewards here, and see which teams are top of the leaderboard this month.",
"Currently no active games on the network.": "Currently no active games on the network.",
"Currently no active teams on the network.": "Currently no active teams on the network."
"Game details": "Game details"
}
-8
View File
@@ -8,7 +8,6 @@ import {
type PeggedReference,
type ProposalChange,
type TransferStatus,
MarketUpdateType,
} from './__generated__/types';
import type { AccountType } from './__generated__/types';
import type {
@@ -756,10 +755,3 @@ export const LiquidityFeeMethodMappingDescription: {
METHOD_UNSPECIFIED: 'Unspecified',
METHOD_WEIGHTED_AVERAGE: `This liquidity fee is the weighted average of all liquidity providers' nominated fees, weighted by their commitment.`,
};
export const MarketUpdateTypeMapping = {
[MarketUpdateType.MARKET_STATE_UPDATE_TYPE_RESUME]: 'Resume',
[MarketUpdateType.MARKET_STATE_UPDATE_TYPE_SUSPEND]: 'Suspend',
[MarketUpdateType.MARKET_STATE_UPDATE_TYPE_TERMINATE]: 'Terminate',
[MarketUpdateType.MARKET_STATE_UPDATE_TYPE_UNSPECIFIED]: 'Unspecified',
};