Relay Chain - Coretime Sale UI (#11091)
* added sales tab * draft for the progress bar * draft for calculating values for the coretime progress timeline * lint * added historical data on sales, button to see transactions on subscan * breaking down utils file logically * improving calculations of phase configuration, sale details, etc * lint * correctly calculated sale start/end blocks, dates and ts * added core price calculation * chainName type, adjustments for westend and paseo * ts fixes * used helper funcitons for getting relay blocks * moved functionality to a new helper * moved constants from types file in react-hooks, page-broker, page-coretime * added dynamic coretime constants, wrapped page coretime in a context for dynamic functions * moved coretime constants to a separate hook for reusability * removed coretime consts and added useCoretimeConsts in page-broker * passing a correct block number for coretime price calculation
This commit is contained in:
parent
81ec67a428
commit
5e80322362
@ -12,7 +12,7 @@ import React, { useEffect, useState } from 'react';
|
||||
import { Input, InputBalance, Modal, Toggle, TxButton } from '@polkadot/react-components';
|
||||
import { getAddressMeta } from '@polkadot/react-components/util';
|
||||
import { useApi, useCall } from '@polkadot/react-hooks';
|
||||
import { AddressIdentityOtherDiscordKey } from '@polkadot/react-hooks/types';
|
||||
import { AddressIdentityOtherDiscordKey } from '@polkadot/react-hooks/constants';
|
||||
import { u8aToString } from '@polkadot/util';
|
||||
|
||||
import { useTranslation } from '../translate.js';
|
||||
|
||||
@ -10,6 +10,7 @@ import { CardSummary, styled, SummaryBox, UsageBar } from '@polkadot/react-compo
|
||||
import { defaultHighlight } from '@polkadot/react-components/styles';
|
||||
import { useApi, useBrokerConfig, useBrokerSalesInfo, useBrokerStatus } from '@polkadot/react-hooks';
|
||||
import { type CoreWorkload } from '@polkadot/react-hooks/types';
|
||||
import { useCoretimeConsts } from '@polkadot/react-hooks/useCoretimeConsts';
|
||||
import { BN, BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { useTranslation } from '../translate.js';
|
||||
@ -42,6 +43,7 @@ interface Props {
|
||||
function Summary ({ coreCount, workloadInfos }: Props): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { api, apiEndpoint, isApiReady } = useApi();
|
||||
const coretimeConstants = useCoretimeConsts();
|
||||
const uiHighlight = apiEndpoint?.ui.color || defaultHighlight;
|
||||
const { idles, pools, tasks }: statsType = React.useMemo(() => getStats(coreCount, workloadInfos), [coreCount, workloadInfos]);
|
||||
|
||||
@ -110,8 +112,8 @@ function Summary ({ coreCount, workloadInfos }: Props): React.ReactElement {
|
||||
label={t('cycle dates')}
|
||||
>
|
||||
<div>
|
||||
<div style={{ fontSize: '14px' }}>{estimateTime(currentRegionStart, status?.lastTimeslice * 80)}</div>
|
||||
<div style={{ fontSize: '14px' }}>{estimateTime(currentRegionEnd, status?.lastTimeslice * 80)}</div>
|
||||
<div style={{ fontSize: '14px' }}>{estimateTime(currentRegionStart, status?.lastTimeslice * 80, coretimeConstants?.relay)}</div>
|
||||
<div style={{ fontSize: '14px' }}>{estimateTime(currentRegionEnd, status?.lastTimeslice * 80, coretimeConstants?.relay)}</div>
|
||||
</div>
|
||||
</CardSummary>
|
||||
<CardSummary
|
||||
|
||||
@ -6,8 +6,9 @@ import type { FlagColor } from '@polkadot/react-components/types';
|
||||
import React from 'react';
|
||||
|
||||
import { AddressMini, styled, Tag } from '@polkadot/react-components';
|
||||
import { CoreTimeTypes } from '@polkadot/react-hooks/constants';
|
||||
|
||||
import { CoreTimeTypes, type InfoRow } from '../types.js';
|
||||
import { type InfoRow } from '../types.js';
|
||||
|
||||
const colours: Record<string, string> = {
|
||||
[CoreTimeTypes.Reservation]: 'orange',
|
||||
|
||||
@ -11,6 +11,7 @@ import React, { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { ExpandButton } from '@polkadot/react-components';
|
||||
import { useApi, useBrokerSalesInfo, useCall, useRegions, useToggle } from '@polkadot/react-hooks';
|
||||
import { useCoretimeConsts } from '@polkadot/react-hooks/useCoretimeConsts';
|
||||
|
||||
import { formatRowInfo } from '../utils.js';
|
||||
import WorkInfoRow from './WorkInfoRow.js';
|
||||
@ -27,6 +28,7 @@ interface Props {
|
||||
function Workload ({ api, config, core, workload, workplan }: Props): React.ReactElement<Props> {
|
||||
const { isApiReady } = useApi();
|
||||
const salesInfo = useBrokerSalesInfo(api, isApiReady);
|
||||
const coretimeConstants = useCoretimeConsts();
|
||||
|
||||
const status = useCall<Option<PalletBrokerStatusRecord>>(isApiReady && api.query.broker?.status);
|
||||
const [isExpanded, toggleIsExpanded] = useToggle(false);
|
||||
@ -47,18 +49,34 @@ function Workload ({ api, config, core, workload, workplan }: Props): React.Reac
|
||||
useEffect(() => {
|
||||
if (!!workload?.length && !!salesInfo) {
|
||||
// saleInfo points to a regionEnd and regionBeing in the next cycle, but we want the start and end of the current cycle
|
||||
setWorkloadData(formatRowInfo(workload, core, region, currentTimeSlice, { regionBegin: salesInfo.regionBegin - config.regionLength, regionEnd: salesInfo.regionEnd - config.regionLength }, config.regionLength));
|
||||
setWorkloadData(formatRowInfo(
|
||||
workload,
|
||||
core,
|
||||
region,
|
||||
currentTimeSlice,
|
||||
{ regionBegin: salesInfo.regionBegin - config.regionLength, regionEnd: salesInfo.regionEnd - config.regionLength },
|
||||
config.regionLength,
|
||||
coretimeConstants?.relay
|
||||
));
|
||||
} else {
|
||||
return setWorkloadData([{ core }]);
|
||||
}
|
||||
}, [workload, region, currentTimeSlice, core, salesInfo, config]);
|
||||
}, [workload, region, currentTimeSlice, core, salesInfo, config, coretimeConstants]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!!workplan?.length && !!salesInfo) {
|
||||
setWorkplanData(formatRowInfo(workplan, core, region, currentTimeSlice, salesInfo, config.regionLength));
|
||||
setWorkplanData(formatRowInfo(
|
||||
workplan,
|
||||
core,
|
||||
region,
|
||||
currentTimeSlice,
|
||||
{ regionBegin: salesInfo.regionBegin - config.regionLength, regionEnd: salesInfo.regionEnd - config.regionLength },
|
||||
config.regionLength,
|
||||
coretimeConstants?.relay
|
||||
));
|
||||
}
|
||||
}
|
||||
, [workplan, region, currentTimeSlice, core, salesInfo, config]);
|
||||
, [workplan, region, currentTimeSlice, core, salesInfo, config, coretimeConstants]);
|
||||
|
||||
const hasWorkplan = workplan?.length;
|
||||
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2024 @polkadot/app-broker authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CoreTimeTypes } from '@polkadot/react-hooks/constants';
|
||||
import type { CoreWorkload, CoreWorkplan } from '@polkadot/react-hooks/types';
|
||||
|
||||
export interface InfoRow {
|
||||
@ -28,13 +29,6 @@ export interface statsType {
|
||||
tasks: number
|
||||
}
|
||||
|
||||
export enum CoreTimeTypes {
|
||||
'Reservation',
|
||||
'Lease',
|
||||
'Bulk Coretime',
|
||||
'On Demand'
|
||||
}
|
||||
|
||||
export interface CoreWorkplanType extends CoreWorkplan {
|
||||
lastBlock: number,
|
||||
type: CoreTimeTypes
|
||||
|
||||
@ -1,13 +1,12 @@
|
||||
// Copyright 2017-2024 @polkadot/app-broker authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ChainBlockConstants, CoreWorkload, LegacyLease, RegionInfo, Reservation } from '@polkadot/react-hooks/types';
|
||||
import type { CoreWorkloadType, CoreWorkplanType, InfoRow } from './types.js';
|
||||
|
||||
import { CoreTimeConsts, type CoreWorkload, type LegacyLease, type RegionInfo, type Reservation } from '@polkadot/react-hooks/types';
|
||||
import { CoreTimeTypes } from '@polkadot/react-hooks/constants';
|
||||
import { BN } from '@polkadot/util';
|
||||
|
||||
import { CoreTimeTypes } from './types.js';
|
||||
|
||||
function formatDate (date: Date) {
|
||||
const day = date.getDate();
|
||||
const month = date.toLocaleString('default', { month: 'short' });
|
||||
@ -29,7 +28,11 @@ function formatDate (date: Date) {
|
||||
* else
|
||||
* now plus block time difference
|
||||
*/
|
||||
export const estimateTime = (targetTimeslice: string | number, latestBlock: number): string | null => {
|
||||
export const estimateTime = (
|
||||
targetTimeslice: string | number,
|
||||
latestBlock: number,
|
||||
{ blocksPerTimeslice: blocksPerTs, blocktimeMs }: ChainBlockConstants = { blocksPerTimeslice: 0, blocktimeMs: 0 }
|
||||
): string | null => {
|
||||
if (!latestBlock || !targetTimeslice) {
|
||||
console.error('Invalid input: one or more inputs are missing');
|
||||
|
||||
@ -39,8 +42,8 @@ export const estimateTime = (targetTimeslice: string | number, latestBlock: numb
|
||||
const now = new Date().getTime();
|
||||
|
||||
try {
|
||||
const blockTime = new BN(CoreTimeConsts.BlockTime); // Average block time in milliseconds (6 seconds)
|
||||
const timeSlice = new BN(CoreTimeConsts.BlocksPerTimeslice);
|
||||
const blockTime = new BN(blocktimeMs); // Average block time in milliseconds (6 seconds)
|
||||
const timeSlice = new BN(blocksPerTs);
|
||||
const latestBlockBN = new BN(latestBlock);
|
||||
const timestampBN = new BN(now);
|
||||
const targetBlockBN = new BN(targetTimeslice).mul(timeSlice);
|
||||
@ -64,7 +67,15 @@ export const estimateTime = (targetTimeslice: string | number, latestBlock: numb
|
||||
* @param param4
|
||||
* @param regionLength
|
||||
*/
|
||||
export function formatRowInfo (data: CoreWorkloadType[] | CoreWorkplanType[], core: number, currentRegion: RegionInfo | undefined, currentTimeSlice: number, { regionBegin, regionEnd }: { regionBegin: number, regionEnd: number }, regionLength: number): InfoRow[] {
|
||||
export function formatRowInfo (
|
||||
data: CoreWorkloadType[] | CoreWorkplanType[],
|
||||
core: number,
|
||||
currentRegion: RegionInfo | undefined,
|
||||
currentTimeSlice: number,
|
||||
{ regionBegin, regionEnd }: { regionBegin: number, regionEnd: number },
|
||||
regionLength: number,
|
||||
coretimeRelayConstants: ChainBlockConstants = { blocksPerTimeslice: 0, blocktimeMs: 0 }
|
||||
): InfoRow[] {
|
||||
return data.map((one: CoreWorkloadType | CoreWorkplanType) => {
|
||||
const item: InfoRow = { core, maskBits: one?.info?.maskBits, task: one?.info?.task, type: one?.type };
|
||||
const blockNumberNow = currentTimeSlice * 80;
|
||||
@ -82,12 +93,12 @@ export function formatRowInfo (data: CoreWorkloadType[] | CoreWorkplanType[], co
|
||||
}
|
||||
|
||||
item.owner = currentRegion?.owner.toString();
|
||||
item.start = start ? estimateTime(start, blockNumberNow) : null;
|
||||
item.end = end ? estimateTime(end, blockNumberNow) : null;
|
||||
item.start = start ? estimateTime(start, blockNumberNow, coretimeRelayConstants) : null;
|
||||
item.end = end ? estimateTime(end, blockNumberNow, coretimeRelayConstants) : null;
|
||||
item.endBlock = end ? Number(end) * 80 : 0;
|
||||
|
||||
if ('timeslice' in one && !start) {
|
||||
start = estimateTime(one.timeslice, blockNumberNow) ?? null;
|
||||
start = estimateTime(one.timeslice, blockNumberNow, coretimeRelayConstants) ?? null;
|
||||
}
|
||||
|
||||
return item;
|
||||
|
||||
49
packages/page-coretime/src/CoretimeContext.tsx
Normal file
49
packages/page-coretime/src/CoretimeContext.tsx
Normal file
@ -0,0 +1,49 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import type { ApiPromise } from '@polkadot/api';
|
||||
import type { CoretimeInformation } from '@polkadot/react-hooks/types';
|
||||
|
||||
import React, { createContext, useContext, useMemo } from 'react';
|
||||
|
||||
import { useCoretimeInformation } from '@polkadot/react-hooks';
|
||||
|
||||
import { createGet } from './utils/index.js';
|
||||
|
||||
interface CoretimeContextProps {
|
||||
coretimeInfo: CoretimeInformation | null;
|
||||
get: ReturnType<typeof createGet> | null;
|
||||
}
|
||||
|
||||
const CoretimeContext = createContext<CoretimeContextProps>({
|
||||
coretimeInfo: null,
|
||||
get: null
|
||||
});
|
||||
|
||||
export const CoretimeProvider = ({ api,
|
||||
children,
|
||||
isApiReady }: {
|
||||
children: ReactNode;
|
||||
api: ApiPromise;
|
||||
isApiReady: boolean;
|
||||
}) => {
|
||||
const coretimeInfo = useCoretimeInformation(api, isApiReady);
|
||||
const get = useMemo(() => {
|
||||
if (coretimeInfo?.constants) {
|
||||
return createGet(coretimeInfo.constants);
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [coretimeInfo?.constants]);
|
||||
|
||||
const value = useMemo(() => ({ coretimeInfo: coretimeInfo ?? null, get }), [coretimeInfo, get]);
|
||||
|
||||
return (
|
||||
<CoretimeContext.Provider value={value}>
|
||||
{children}
|
||||
</CoretimeContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useCoretimeContext = () => useContext(CoretimeContext);
|
||||
66
packages/page-coretime/src/CoretimePage.tsx
Normal file
66
packages/page-coretime/src/CoretimePage.tsx
Normal file
@ -0,0 +1,66 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiPromise } from '@polkadot/api';
|
||||
import type { TabItem } from '@polkadot/react-components/types';
|
||||
import type { ChainName } from './types.js';
|
||||
|
||||
import React, { useRef } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
|
||||
import { Tabs } from '@polkadot/react-components';
|
||||
import { useCall } from '@polkadot/react-hooks';
|
||||
|
||||
import Overview from './Overview/index.js';
|
||||
import Sale from './Sale/index.js';
|
||||
import { useTranslation } from './translate.js';
|
||||
|
||||
interface Props {
|
||||
basePath: string;
|
||||
className?: string;
|
||||
api: ApiPromise;
|
||||
isApiReady: boolean;
|
||||
}
|
||||
|
||||
function createItemsRef (t: (key: string, options?: { replace: Record<string, unknown> }) => string): TabItem[] {
|
||||
return [
|
||||
{
|
||||
isRoot: true,
|
||||
name: 'overview',
|
||||
text: t('Overview')
|
||||
},
|
||||
{
|
||||
name: 'sale',
|
||||
text: t('Sale')
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
function CoretimePage ({ api, basePath, className, isApiReady }: Props): React.ReactElement<Props> {
|
||||
const { t } = useTranslation();
|
||||
const itemsRef = useRef(createItemsRef(t));
|
||||
const chainName = useCall<string>(isApiReady && api?.rpc.system.chain)?.toString().toLowerCase() as ChainName;
|
||||
|
||||
return (
|
||||
<main className={className}>
|
||||
<Tabs
|
||||
basePath={basePath}
|
||||
items={itemsRef.current}
|
||||
/>
|
||||
<Routes>
|
||||
<Route path={basePath}>
|
||||
<Route
|
||||
element={<Overview chainName={chainName} />}
|
||||
index
|
||||
/>
|
||||
<Route
|
||||
element={<Sale chainName={chainName} />}
|
||||
path='sale'
|
||||
/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(CoretimePage);
|
||||
@ -1,57 +1,61 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiPromise } from '@polkadot/api';
|
||||
import type { BrokerStatus, CoreDescription, PalletBrokerConfigRecord, PalletBrokerSaleInfoRecord, RegionInfo } from '@polkadot/react-hooks/types';
|
||||
import type { BrokerStatus, ChainConstants, CoreDescription, PalletBrokerConfigRecord, PalletBrokerSaleInfoRecord, RegionInfo } from '@polkadot/react-hooks/types';
|
||||
import type { ChainName } from '../types.js';
|
||||
|
||||
import React, { useMemo } from 'react';
|
||||
|
||||
import { CardSummary, SummaryBox } from '@polkadot/react-components';
|
||||
import { useCall } from '@polkadot/react-hooks';
|
||||
import { BN } from '@polkadot/util';
|
||||
|
||||
import { useCoretimeContext } from '../CoretimeContext.js';
|
||||
import { useTranslation } from '../translate.js';
|
||||
import { estimateTime, FirstCycleStart } from '../utils.js';
|
||||
import { estimateTime, FirstCycleStart } from '../utils/index.js';
|
||||
|
||||
interface Props {
|
||||
api: ApiPromise | null,
|
||||
coreDscriptors?: CoreDescription[];
|
||||
saleInfo: PalletBrokerSaleInfoRecord
|
||||
config: PalletBrokerConfigRecord,
|
||||
region: RegionInfo[],
|
||||
status: BrokerStatus,
|
||||
parachainCount: number
|
||||
chainName: ChainName,
|
||||
constants: ChainConstants
|
||||
}
|
||||
|
||||
function Summary ({ api, config, parachainCount, saleInfo, status }: Props): React.ReactElement<Props> {
|
||||
function Summary ({ chainName, config, constants, parachainCount, saleInfo, status }: Props): React.ReactElement<Props> {
|
||||
const { t } = useTranslation();
|
||||
const currentRegionEnd = saleInfo.regionEnd - config.regionLength;
|
||||
const currentRegionStart = saleInfo.regionEnd - config.regionLength * 2;
|
||||
const chainName = useCall<string>(api?.rpc.system.chain)?.toString().toLowerCase();
|
||||
const { get } = useCoretimeContext();
|
||||
|
||||
const cycleNumber = useMemo(() =>
|
||||
chainName && currentRegionEnd && Math.floor((currentRegionEnd - FirstCycleStart[chainName]) / config.regionLength)
|
||||
, [currentRegionEnd, chainName, config]);
|
||||
const cycleNumber = useMemo(() => {
|
||||
if (chainName && currentRegionEnd) {
|
||||
return Math.floor(
|
||||
(currentRegionEnd - FirstCycleStart.timeslice.coretime[chainName]) / config.regionLength
|
||||
);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [currentRegionEnd, chainName, config]);
|
||||
|
||||
return (
|
||||
<SummaryBox>
|
||||
<section>
|
||||
<CardSummary label={t('timeslice')}>
|
||||
{status?.lastTimeslice}
|
||||
</CardSummary>
|
||||
<CardSummary label={t('cores sold')}>
|
||||
{`${saleInfo?.coresSold} / ${saleInfo?.coresOffered}`}
|
||||
</CardSummary>
|
||||
<CardSummary label={t('parachains')}>
|
||||
{parachainCount && parachainCount}
|
||||
</CardSummary>
|
||||
{status &&
|
||||
<CardSummary label={t('cycle number')}>
|
||||
<CardSummary label={t('sale number')}>
|
||||
<div>
|
||||
{cycleNumber}
|
||||
</div>
|
||||
</CardSummary>
|
||||
}
|
||||
<CardSummary label={t('timeslice')}>
|
||||
{status?.lastTimeslice}
|
||||
</CardSummary>
|
||||
<CardSummary label={t('parachains')}>
|
||||
{parachainCount && parachainCount}
|
||||
</CardSummary>
|
||||
{config && status &&
|
||||
<CardSummary
|
||||
className='media--800'
|
||||
@ -69,8 +73,8 @@ function Summary ({ api, config, parachainCount, saleInfo, status }: Props): Rea
|
||||
{status &&
|
||||
(<CardSummary label={t('cycle dates')}>
|
||||
<div>
|
||||
<div style={{ fontSize: '14px' }}>{estimateTime(currentRegionStart, status?.lastTimeslice * 80)}</div>
|
||||
<div style={{ fontSize: '14px' }}>{estimateTime(currentRegionEnd, status?.lastTimeslice * 80)}</div>
|
||||
<div style={{ fontSize: '14px' }}>{get && estimateTime(currentRegionStart, get.blocks.relay(status?.lastTimeslice), constants.relay)}</div>
|
||||
<div style={{ fontSize: '14px' }}>{get && estimateTime(currentRegionEnd, get.blocks.relay(status?.lastTimeslice), constants.relay)}</div>
|
||||
</div>
|
||||
</CardSummary>)
|
||||
}
|
||||
|
||||
42
packages/page-coretime/src/Overview/index.tsx
Normal file
42
packages/page-coretime/src/Overview/index.tsx
Normal file
@ -0,0 +1,42 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ChainName } from '../types.js';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { useCoretimeContext } from '../CoretimeContext.js';
|
||||
import ParachainsTable from '../ParachainsTable.js';
|
||||
import Summary from './Summary.js';
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
chainName: ChainName
|
||||
}
|
||||
|
||||
function Overview ({ chainName, className }: Props): React.ReactElement<Props> {
|
||||
const { coretimeInfo } = useCoretimeContext();
|
||||
|
||||
return (
|
||||
<main className={className}>
|
||||
{coretimeInfo && (
|
||||
<Summary
|
||||
chainName={chainName}
|
||||
config={coretimeInfo?.config}
|
||||
constants={coretimeInfo?.constants}
|
||||
parachainCount={coretimeInfo.taskIds?.length || 0}
|
||||
region={coretimeInfo?.region}
|
||||
saleInfo={coretimeInfo?.salesInfo}
|
||||
status={coretimeInfo?.status}
|
||||
/>
|
||||
)}
|
||||
{!!coretimeInfo &&
|
||||
<ParachainsTable
|
||||
coretimeInfo={coretimeInfo}
|
||||
/>
|
||||
}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(Overview);
|
||||
@ -42,10 +42,10 @@ function ParachainTableRow ({ chain, lastCommittedTimeslice, regionBegin, region
|
||||
{idx === 0 && <td style={{ paddingRight: '2rem', textAlign: 'right', verticalAlign: 'top' }}>
|
||||
|
||||
{!!multiple &&
|
||||
<ExpandButton
|
||||
expanded={isExpanded}
|
||||
onClick={toggleIsExpanded}
|
||||
/>
|
||||
<ExpandButton
|
||||
expanded={isExpanded}
|
||||
onClick={toggleIsExpanded}
|
||||
/>
|
||||
}
|
||||
</td>}
|
||||
</>;
|
||||
|
||||
@ -33,6 +33,7 @@ function ParachainsTable ({ coretimeInfo }: Props): React.ReactElement<Props> {
|
||||
header={headerRef.current}
|
||||
isSplit={false}
|
||||
>
|
||||
|
||||
{coretimeInfo?.taskIds?.map((taskId: number) => {
|
||||
const chain = coretimeInfo.chainInfo[taskId];
|
||||
|
||||
|
||||
@ -7,11 +7,11 @@ import type { ChainWorkTaskInformation, LegacyLease } from '@polkadot/react-hook
|
||||
import React from 'react';
|
||||
|
||||
import { ParaLink, styled, Tag } from '@polkadot/react-components';
|
||||
import { ChainRenewalStatus } from '@polkadot/react-hooks/types';
|
||||
import { ChainRenewalStatus, CoreTimeTypes } from '@polkadot/react-hooks/constants';
|
||||
import { BN, formatBalance, formatNumber } from '@polkadot/util';
|
||||
|
||||
import { CoreTimeTypes } from './types.js';
|
||||
import { estimateTime } from './utils.js';
|
||||
import { estimateTime } from './utils/index.js';
|
||||
import { useCoretimeContext } from './CoretimeContext.js';
|
||||
|
||||
interface Props {
|
||||
id: number
|
||||
@ -40,6 +40,8 @@ function Row ({ chainRecord, highlight = false, id, lastCommittedTimeslice, leas
|
||||
const targetTimeslice = lease?.until || chainRegionEnd;
|
||||
const showEstimates = !!targetTimeslice && Object.values(CoreTimeTypes)[chainRecord.type] !== CoreTimeTypes.Reservation;
|
||||
|
||||
const { coretimeInfo, get } = useCoretimeContext();
|
||||
|
||||
return (
|
||||
<React.Fragment key={`${id}`}>
|
||||
<StyledCell $p={highlight}>{id}</StyledCell>
|
||||
@ -57,11 +59,11 @@ function Row ({ chainRecord, highlight = false, id, lastCommittedTimeslice, leas
|
||||
<StyledCell
|
||||
$p={highlight}
|
||||
className='media--800'
|
||||
>{showEstimates && formatNumber(targetTimeslice * 80).toString()}</StyledCell>
|
||||
>{showEstimates && get && formatNumber(get.blocks.relay(targetTimeslice)).toString()}</StyledCell>
|
||||
<StyledCell
|
||||
$p={highlight}
|
||||
className='media--1000'
|
||||
>{showEstimates && estimateTime(targetTimeslice, lastCommittedTimeslice * 80)}</StyledCell>
|
||||
>{showEstimates && get && coretimeInfo && estimateTime(targetTimeslice, get.blocks.relay(lastCommittedTimeslice), coretimeInfo?.constants?.relay)}</StyledCell>
|
||||
<StyledCell
|
||||
$p={highlight}
|
||||
className='media--1200'
|
||||
|
||||
51
packages/page-coretime/src/Sale/SaleTable.tsx
Normal file
51
packages/page-coretime/src/Sale/SaleTable.tsx
Normal file
@ -0,0 +1,51 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { SaleDetails } from '../types.js';
|
||||
|
||||
import React, { useRef } from 'react';
|
||||
|
||||
import { Table } from '@polkadot/react-components';
|
||||
|
||||
import { useTranslation } from '../translate.js';
|
||||
|
||||
interface Props {
|
||||
saleDetails: SaleDetails
|
||||
}
|
||||
|
||||
function SaleTable ({ saleDetails }: Props): React.ReactElement<Props> {
|
||||
const { t } = useTranslation();
|
||||
const headerRef = useRef<([React.ReactNode?, string?, number?] | false)[]>([
|
||||
[],
|
||||
[t('Dates'), 'start media--800'],
|
||||
[t('Blocks (relay)'), 'start'],
|
||||
[t('Blocks(coretime)'), 'start'],
|
||||
[t('Timeslices'), 'start']
|
||||
]);
|
||||
|
||||
return (
|
||||
<Table
|
||||
emptySpinner={false}
|
||||
header={headerRef.current}
|
||||
isSplit={false}
|
||||
>
|
||||
<tr>
|
||||
<td>Start</td>
|
||||
<td>{saleDetails.date.start}</td>
|
||||
<td>{saleDetails.relay.start.block}</td>
|
||||
<td>{saleDetails.coretime.start.block}</td>
|
||||
<td>{saleDetails.relay.start.ts}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>End</td>
|
||||
<td>{saleDetails.date.end}</td>
|
||||
<td>{saleDetails.relay.end.block}</td>
|
||||
<td>{saleDetails.coretime.end.block}</td>
|
||||
<td>{saleDetails.relay.end.ts}</td>
|
||||
</tr>
|
||||
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(SaleTable);
|
||||
91
packages/page-coretime/src/Sale/Summary.tsx
Normal file
91
packages/page-coretime/src/Sale/Summary.tsx
Normal file
@ -0,0 +1,91 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiPromise } from '@polkadot/api';
|
||||
import type { BrokerStatus, ChainConstants, CoreDescription, PalletBrokerConfigRecord, PalletBrokerSaleInfoRecord, RegionInfo } from '@polkadot/react-hooks/types';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { CardSummary, SummaryBox } from '@polkadot/react-components';
|
||||
import { BN, formatNumber } from '@polkadot/util';
|
||||
|
||||
import { useCoretimeContext } from '../CoretimeContext.js';
|
||||
import { useTranslation } from '../translate.js';
|
||||
import { estimateTime, getCurrentRegionStartEndTs } from '../utils/index.js';
|
||||
|
||||
interface Props {
|
||||
api: ApiPromise | null,
|
||||
coreDscriptors?: CoreDescription[];
|
||||
saleInfo: PalletBrokerSaleInfoRecord
|
||||
config: PalletBrokerConfigRecord,
|
||||
region: RegionInfo[],
|
||||
status: BrokerStatus,
|
||||
cycleNumber: number,
|
||||
constants: ChainConstants
|
||||
}
|
||||
|
||||
function Summary ({ config, constants, cycleNumber, saleInfo, status }: Props): React.ReactElement<Props> {
|
||||
const { t } = useTranslation();
|
||||
const { currentRegionEnd, currentRegionStart } = getCurrentRegionStartEndTs(saleInfo, config.regionLength);
|
||||
const { get } = useCoretimeContext();
|
||||
const cycleEnd = get && estimateTime(currentRegionEnd, get.blocks.relay(status?.lastTimeslice), constants.relay);
|
||||
const cycleStart = get && estimateTime(currentRegionStart, get.blocks.relay(status?.lastTimeslice), constants.relay);
|
||||
|
||||
return (
|
||||
<SummaryBox>
|
||||
<section>
|
||||
{status &&
|
||||
<CardSummary label={t('sale number')}>
|
||||
<div>
|
||||
{cycleNumber > -1 ? cycleNumber : '-'}
|
||||
</div>
|
||||
</CardSummary>
|
||||
}
|
||||
<CardSummary label={t('sold/offered')}>
|
||||
{`${saleInfo?.coresSold} / ${saleInfo?.coresOffered}`}
|
||||
</CardSummary>
|
||||
<CardSummary label={t('sale end')}>
|
||||
<div>{cycleEnd}</div>
|
||||
</CardSummary>
|
||||
<CardSummary label={t('last block')}>
|
||||
<div>{get && formatNumber(get.blocks.relay(currentRegionEnd))}</div>
|
||||
</CardSummary>
|
||||
<CardSummary label={t('last timeslice')}>
|
||||
<div>{formatNumber(currentRegionEnd)}</div>
|
||||
</CardSummary>
|
||||
{config && status &&
|
||||
<CardSummary
|
||||
className='media--800'
|
||||
label={t('sale progress')}
|
||||
progress={{
|
||||
isBlurred: false,
|
||||
total: new BN(config?.regionLength),
|
||||
value: new BN(config?.regionLength - (currentRegionEnd - status.lastTimeslice)),
|
||||
withTime: false
|
||||
}}
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
<section className='media--1200'>
|
||||
{status &&
|
||||
(<CardSummary label={t('cycle dates')}>
|
||||
<div>
|
||||
<div style={{ fontSize: '14px' }}>{cycleStart}</div>
|
||||
<div style={{ fontSize: '14px' }}>{cycleEnd}</div>
|
||||
</div>
|
||||
</CardSummary>)
|
||||
}
|
||||
{status &&
|
||||
<CardSummary label={t('cycle ts')}>
|
||||
<div>
|
||||
<div style={{ fontSize: '14px' }}>{currentRegionStart}</div>
|
||||
<div style={{ fontSize: '14px' }}>{currentRegionEnd}</div>
|
||||
</div>
|
||||
</CardSummary>
|
||||
}
|
||||
</section>
|
||||
</SummaryBox>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(Summary);
|
||||
172
packages/page-coretime/src/Sale/index.tsx
Normal file
172
packages/page-coretime/src/Sale/index.tsx
Normal file
@ -0,0 +1,172 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ProgressBarSection } from '@polkadot/react-components/types';
|
||||
import type { BlockNumber } from '@polkadot/types/interfaces';
|
||||
import type { ChainName, SaleDetails } from '../types.js';
|
||||
|
||||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
|
||||
import { Button, CardSummary, Dropdown, SummaryBox } from '@polkadot/react-components';
|
||||
import ProgressBar from '@polkadot/react-components/ProgressBar';
|
||||
import { useApi, useCall } from '@polkadot/react-hooks';
|
||||
import { formatBalance, formatNumber } from '@polkadot/util';
|
||||
|
||||
import { PhaseName } from '../constants.js';
|
||||
import { useCoretimeContext } from '../CoretimeContext.js';
|
||||
import { useTranslation } from '../translate.js';
|
||||
import { constructSubscanQuery, estimateTime } from '../utils/index.js';
|
||||
import { calculateSaleDetails, getCorePriceAt, getSaleParameters, getSaleProgress } from '../utils/sale.js';
|
||||
import SaleTable from './SaleTable.js';
|
||||
import Summary from './Summary.js';
|
||||
|
||||
interface Props {
|
||||
chainName: ChainName
|
||||
}
|
||||
|
||||
function Sale ({ chainName }: Props): React.ReactElement<Props> {
|
||||
const { coretimeInfo, get } = useCoretimeContext();
|
||||
const { api, apiCoretime, isApiReady } = useApi();
|
||||
const { t } = useTranslation();
|
||||
const regionBegin = coretimeInfo?.salesInfo?.regionBegin;
|
||||
const lastCommittedTimeslice = coretimeInfo?.status?.lastTimeslice;
|
||||
const bestNumberFinalized = useCall<BlockNumber>(apiCoretime.derive.chain.bestNumberFinalized);
|
||||
|
||||
const coretimePrice = useMemo(() => get && bestNumberFinalized && getCorePriceAt(bestNumberFinalized.toNumber(), coretimeInfo?.salesInfo), [coretimeInfo?.salesInfo, get, bestNumberFinalized]);
|
||||
const saleParams = coretimeInfo && getSaleParameters(coretimeInfo.salesInfo, coretimeInfo.config, chainName, lastCommittedTimeslice ?? 0, coretimeInfo.constants);
|
||||
const phaseName = useMemo(() => saleParams?.phaseConfig?.currentPhaseName, [saleParams]);
|
||||
const [chosenSaleNumber, setChosenSaleNumber] = useState<number>(-1);
|
||||
const [saleDetails, setSaleDetails] = useState<SaleDetails | null>(null);
|
||||
const saleNumberOptions = useMemo(() =>
|
||||
[
|
||||
{
|
||||
text: t('Pick a sale number'),
|
||||
value: -1
|
||||
},
|
||||
...Array.from({ length: saleParams?.cycleNumber ?? 0 }, (_, i) => ({
|
||||
text: `sale #${i + 1}`,
|
||||
value: i
|
||||
})).reverse()
|
||||
|
||||
]
|
||||
, [saleParams, t]);
|
||||
|
||||
const progressValues = useMemo(() => saleParams && regionBegin && getSaleProgress(lastCommittedTimeslice, saleParams.currentRegion.start.ts, saleParams.interlude.ts, saleParams.leadin.ts, regionBegin),
|
||||
[saleParams, lastCommittedTimeslice, regionBegin]);
|
||||
|
||||
// TODO: uncomment when introducing core purchase functionality
|
||||
// const available = getAvailableNumberOfCores(coretimeInfo);
|
||||
|
||||
const onDropDownChange = useCallback((value: number) => {
|
||||
setChosenSaleNumber(value);
|
||||
|
||||
if (value === -1) {
|
||||
setSaleDetails(null);
|
||||
} else {
|
||||
get && saleParams && setSaleDetails(calculateSaleDetails(
|
||||
value,
|
||||
saleParams?.cycleNumber,
|
||||
get.blocks.relay(coretimeInfo.status.lastTimeslice),
|
||||
chainName,
|
||||
coretimeInfo.config.regionLength,
|
||||
saleParams,
|
||||
coretimeInfo.constants
|
||||
));
|
||||
}
|
||||
}, [get, saleParams, coretimeInfo, chainName]);
|
||||
|
||||
const onQuerySaleClick = useCallback(() => {
|
||||
if (saleDetails) {
|
||||
window.open(constructSubscanQuery(saleDetails.coretime.start.block, saleDetails.coretime.end.block, chainName));
|
||||
}
|
||||
}, [saleDetails, chainName]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{coretimeInfo && saleParams &&
|
||||
<Summary
|
||||
api={isApiReady ? api : null}
|
||||
config={coretimeInfo?.config}
|
||||
constants={coretimeInfo?.constants}
|
||||
cycleNumber={saleParams?.cycleNumber}
|
||||
region={coretimeInfo?.region}
|
||||
saleInfo={coretimeInfo?.salesInfo}
|
||||
status={coretimeInfo?.status}
|
||||
/>}
|
||||
<div style={{ alignItems: 'stretch', display: 'grid', flexFlow: '1', gap: '2rem', gridTemplateColumns: '1fr 3fr', gridTemplateRows: 'auto auto', marginTop: '4rem' }}>
|
||||
|
||||
<div style={{ backgroundColor: 'white', borderRadius: '4px', display: 'flex', flexDirection: 'column', justifyItems: 'center', justifySelf: 'right', padding: '24px', width: 'fit-content' }}>
|
||||
<SummaryBox className='isSmall'>
|
||||
{phaseName === PhaseName.Renewals
|
||||
? (
|
||||
<b>Cores cannot be purchased now</b>
|
||||
)
|
||||
: (
|
||||
<CardSummary label='current price'>{coretimePrice && formatBalance(coretimePrice)}</CardSummary>
|
||||
)}
|
||||
|
||||
</SummaryBox>
|
||||
{/* TODO: Add core purchase functionality */}
|
||||
{/* {<div style={{ marginTop: '8px' }}>
|
||||
<Button
|
||||
isBasic
|
||||
isDisabled={!available || phaseName === PhaseName.Renewals}
|
||||
label={t('Purchase a core')}
|
||||
onClick={() => window.alert('yo')}
|
||||
/>
|
||||
</div>} */}
|
||||
</div>
|
||||
<div style={{ backgroundColor: 'white', borderRadius: '4px', justifySelf: 'left', padding: '24px', width: 'fit-content' }}>
|
||||
<SummaryBox>
|
||||
<section>
|
||||
{phaseName && <>
|
||||
<CardSummary label='current phase'>{phaseName}</CardSummary>
|
||||
<CardSummary label='current phase end'>{get && coretimeInfo && saleParams?.phaseConfig && estimateTime(saleParams.phaseConfig.config[phaseName].lastTimeslice, get.blocks.relay(coretimeInfo?.status.lastTimeslice), coretimeInfo.constants.relay)}</CardSummary>
|
||||
<CardSummary label='last block'>{formatNumber(saleParams?.phaseConfig?.config[phaseName].lastBlock)}</CardSummary>
|
||||
</>}
|
||||
<CardSummary label='fixed price'>{formatBalance(coretimeInfo?.salesInfo.endPrice)}</CardSummary>
|
||||
</section>
|
||||
<section>
|
||||
|
||||
</section>
|
||||
</SummaryBox>
|
||||
<ProgressBar sections={progressValues as ProgressBarSection[] ?? []} />
|
||||
</div>
|
||||
<div style={{ backgroundColor: 'white', borderRadius: '4px', gridColumn: '1 / -1', justifySelf: 'center', padding: '24px', width: '100%' }}>
|
||||
<h2>Interlude + sale data</h2>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem', marginBottom: '1.5rem', maxWidth: '300px' }}>
|
||||
<Dropdown
|
||||
className='isSmall'
|
||||
onChange={onDropDownChange}
|
||||
options={saleNumberOptions}
|
||||
value={chosenSaleNumber}
|
||||
/>
|
||||
|
||||
</div>
|
||||
{chosenSaleNumber > -1 && !!saleDetails && <div style={{ minWidth: '200px' }}>
|
||||
<SaleTable
|
||||
saleDetails={saleDetails}
|
||||
/>
|
||||
|
||||
</div>}
|
||||
{chosenSaleNumber > -1 && !!saleDetails && <div style={{ minWidth: '200px' }}>
|
||||
<h2>Query sale transactions</h2>
|
||||
<p style={{ marginTop: '1rem' }}>We do not index transactions ourselves but you can query historical transactions on Subscan. <br />
|
||||
The button below will open a new tab with the correct query parameters for the chosen sale.</p>
|
||||
<Button
|
||||
isBasic
|
||||
label={t(`Query Subscan for sale #${chosenSaleNumber + 1}`)}
|
||||
onClick={onQuerySaleClick}
|
||||
/>
|
||||
</div>
|
||||
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Sale;
|
||||
8
packages/page-coretime/src/constants.ts
Normal file
8
packages/page-coretime/src/constants.ts
Normal file
@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export const PhaseName = {
|
||||
FixedPrice: 'Fixed Price',
|
||||
PriceDiscovery: 'Price Discovery',
|
||||
Renewals: 'Renewals'
|
||||
} as const;
|
||||
@ -1,61 +1,33 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { TabItem } from '@polkadot/react-components/types';
|
||||
import React from 'react';
|
||||
|
||||
import React, { useRef } from 'react';
|
||||
import { useApi } from '@polkadot/react-hooks';
|
||||
|
||||
import { Tabs } from '@polkadot/react-components';
|
||||
import { useApi, useCoretimeInformation } from '@polkadot/react-hooks';
|
||||
|
||||
import Summary from './Overview/Summary.js';
|
||||
import ParachainsTable from './ParachainsTable.js';
|
||||
import { useTranslation } from './translate.js';
|
||||
import { CoretimeProvider } from './CoretimeContext.js';
|
||||
import CoretimePage from './CoretimePage.js';
|
||||
|
||||
interface Props {
|
||||
basePath: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function createItemsRef (t: (key: string, options?: { replace: Record<string, unknown> }) => string): TabItem[] {
|
||||
return [
|
||||
{
|
||||
isRoot: true,
|
||||
name: 'overview',
|
||||
text: t('Overview')
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
function CoretimeApp ({ basePath, className }: Props): React.ReactElement<Props> {
|
||||
const { t } = useTranslation();
|
||||
const { api, isApiReady } = useApi();
|
||||
const itemsRef = useRef(createItemsRef(t));
|
||||
const coretimeInfo = useCoretimeInformation(api, isApiReady);
|
||||
|
||||
return (
|
||||
<main className={className}>
|
||||
<Tabs
|
||||
<CoretimeProvider
|
||||
api={api}
|
||||
isApiReady={isApiReady}
|
||||
>
|
||||
<CoretimePage
|
||||
api={api}
|
||||
basePath={basePath}
|
||||
items={itemsRef.current}
|
||||
className={className}
|
||||
isApiReady={isApiReady}
|
||||
/>
|
||||
{coretimeInfo && (
|
||||
<Summary
|
||||
api={isApiReady ? api : null}
|
||||
config={coretimeInfo?.config}
|
||||
parachainCount={coretimeInfo.taskIds?.length || 0}
|
||||
region={coretimeInfo?.region}
|
||||
saleInfo={coretimeInfo?.salesInfo}
|
||||
status={coretimeInfo?.status}
|
||||
/>
|
||||
)}
|
||||
{!!coretimeInfo &&
|
||||
<ParachainsTable
|
||||
coretimeInfo={coretimeInfo}
|
||||
/>
|
||||
}
|
||||
|
||||
</main>
|
||||
</CoretimeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -1,9 +1,68 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export enum CoreTimeTypes {
|
||||
'Reservation',
|
||||
'Lease',
|
||||
'Bulk Coretime',
|
||||
'On Demand'
|
||||
import type { PhaseName } from './constants.js';
|
||||
|
||||
export interface PhaseInfo {
|
||||
name: string;
|
||||
lastBlock: number;
|
||||
lastTimeslice: number
|
||||
}
|
||||
|
||||
type PhaseNameType = typeof PhaseName[keyof typeof PhaseName];
|
||||
|
||||
export interface PhaseConfig {
|
||||
currentPhaseName: PhaseNameType;
|
||||
config: Record<PhaseNameType, { lastTimeslice: number; lastBlock: number }>;
|
||||
}
|
||||
|
||||
export interface PhaseProgress {
|
||||
value: number;
|
||||
total: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface SaleParameters {
|
||||
currentRegion: {
|
||||
start: { ts: number; blocks: number };
|
||||
end: { ts: number; blocks: number };
|
||||
};
|
||||
cycleNumber: number;
|
||||
interlude: { ts: number; blocks: number };
|
||||
leadin: { ts: number; blocks: number };
|
||||
phaseConfig: PhaseConfig;
|
||||
regionNumber: number;
|
||||
}
|
||||
|
||||
export interface SaleDetails {
|
||||
saleNumber: number;
|
||||
relay: {
|
||||
start: {
|
||||
block: number;
|
||||
ts: number;
|
||||
},
|
||||
end: {
|
||||
block: number;
|
||||
ts: number;
|
||||
},
|
||||
},
|
||||
coretime: {
|
||||
start: {
|
||||
block: number;
|
||||
},
|
||||
end: {
|
||||
block: number;
|
||||
}
|
||||
}
|
||||
date: {
|
||||
start: string | null;
|
||||
end: string | null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RegionInfo {
|
||||
regionBegin: number;
|
||||
regionEnd: number;
|
||||
}
|
||||
|
||||
export type ChainName = 'kusama' | 'polkadot' | 'paseo testnet' | 'westend'
|
||||
|
||||
@ -1,67 +0,0 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { CoreTimeConsts, type LegacyLease, type Reservation } from '@polkadot/react-hooks/types';
|
||||
import { BN } from '@polkadot/util';
|
||||
|
||||
import { CoreTimeTypes } from './types.js';
|
||||
|
||||
export const FirstCycleStart: Record<string, number> = {
|
||||
kusama: 285768,
|
||||
polkadot: 282525
|
||||
};
|
||||
|
||||
function formatDate (date: Date) {
|
||||
const day = date.getDate();
|
||||
const month = date.toLocaleString('default', { month: 'short' });
|
||||
const year = date.getFullYear();
|
||||
|
||||
return `${day} ${month} ${year}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* blockTime = 6000 ms
|
||||
* BlocksPerTimeslice = 80
|
||||
* Default Regoin = 5040 timeslices
|
||||
* TargetBlock = TargetTimeslice * BlocksPerTimeslice
|
||||
* Block Time Difference = |TargetBlock - latest Block| * blockTime
|
||||
*
|
||||
* Estimate timestamp =
|
||||
* if targetBlock is before the latestBlock
|
||||
* now minus block time difference
|
||||
* else
|
||||
* now plus block time difference
|
||||
*/
|
||||
export const estimateTime = (targetTimeslice: string | number, latestBlock: number): string | null => {
|
||||
if (!latestBlock || !targetTimeslice) {
|
||||
console.error('Invalid input: one or more inputs are missing');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const now = new Date().getTime();
|
||||
|
||||
try {
|
||||
const blockTime = new BN(CoreTimeConsts.BlockTime); // Average block time in milliseconds (6 seconds)
|
||||
const timeSlice = new BN(CoreTimeConsts.BlocksPerTimeslice);
|
||||
const latestBlockBN = new BN(latestBlock);
|
||||
const timestampBN = new BN(now);
|
||||
const targetBlockBN = new BN(targetTimeslice).mul(timeSlice);
|
||||
const blockTimeDifference = targetBlockBN.sub(latestBlockBN).mul(blockTime);
|
||||
const estTimestamp = timestampBN.add(blockTimeDifference);
|
||||
|
||||
return formatDate(new Date(estTimestamp.toNumber()));
|
||||
} catch (error) {
|
||||
console.error('Error in calculation:', error);
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const getOccupancyType = (lease: LegacyLease | undefined, reservation: Reservation | undefined, isPool: boolean): CoreTimeTypes => {
|
||||
if (isPool) {
|
||||
return CoreTimeTypes['On Demand'];
|
||||
}
|
||||
|
||||
return reservation ? CoreTimeTypes.Reservation : lease ? CoreTimeTypes.Lease : CoreTimeTypes['Bulk Coretime'];
|
||||
};
|
||||
168
packages/page-coretime/src/utils/index.ts
Normal file
168
packages/page-coretime/src/utils/index.ts
Normal file
@ -0,0 +1,168 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ChainBlockConstants, ChainConstants, CoretimeInformation } from '@polkadot/react-hooks/types';
|
||||
import type { ChainName, RegionInfo } from '../types.js';
|
||||
|
||||
import { BN } from '@polkadot/util';
|
||||
|
||||
type FirstCycleStartType = Record<
|
||||
'block' | 'timeslice',
|
||||
Record<
|
||||
'coretime',
|
||||
Record<ChainName, number>
|
||||
>
|
||||
>;
|
||||
|
||||
// Blocks on the Coretime Chain
|
||||
export const FirstCycleStart: FirstCycleStartType = {
|
||||
block: {
|
||||
coretime: {
|
||||
kusama: 86947,
|
||||
'paseo testnet': 22316,
|
||||
polkadot: 100988,
|
||||
westend: 7363
|
||||
}
|
||||
},
|
||||
timeslice: {
|
||||
coretime: {
|
||||
kusama: 285768,
|
||||
'paseo testnet': 38469,
|
||||
polkadot: 282525,
|
||||
westend: 245402
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export function formatDate (date: Date) {
|
||||
const day = date.getDate();
|
||||
const month = date.toLocaleString('default', { month: 'short' });
|
||||
const year = date.getFullYear();
|
||||
|
||||
return `${day} ${month} ${year}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives you a date for the traget timeslice
|
||||
*
|
||||
* Relay chain info:
|
||||
* blockTime = 6000 ms
|
||||
* BlocksPerTimeslice = 80
|
||||
* Default Regoin = 5040 timeslices
|
||||
*
|
||||
* Calculation:
|
||||
* TargetBlock = TargetTimeslice * BlocksPerTimeslice
|
||||
* Block Time Difference = |TargetBlock - latest Block| * blockTime
|
||||
*
|
||||
* Estimate timestamp =
|
||||
* if targetBlock is before the latestBlock
|
||||
* now minus block time difference
|
||||
* else
|
||||
* now plus block time difference
|
||||
*/
|
||||
export const estimateTime = (
|
||||
targetTimeslice: string | number,
|
||||
latestBlock: number,
|
||||
{ blocksPerTimeslice: blocksPerTs, blocktimeMs }: ChainBlockConstants
|
||||
): string | null => {
|
||||
if (!latestBlock || !targetTimeslice) {
|
||||
console.error('Invalid input: one or more inputs are missing');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const now = new BN(Date.now());
|
||||
const blockTime = new BN(blocktimeMs); // Average block time in milliseconds (6 seconds)
|
||||
const blocksPerTimeslice = new BN(blocksPerTs);
|
||||
const targetBlock = new BN(Number(targetTimeslice)).mul(blocksPerTimeslice);
|
||||
const latestBlockBN = new BN(latestBlock);
|
||||
const blockDifference = targetBlock.sub(latestBlockBN);
|
||||
const timeDifference = blockDifference.mul(blockTime);
|
||||
const estTimestamp = now.add(timeDifference);
|
||||
|
||||
return formatDate(new Date(estTimestamp.toNumber()));
|
||||
} catch (error) {
|
||||
console.error('Error in calculation:', error);
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Factory function to create helper functions for converting timeslices to blocks and vice versa.
|
||||
*
|
||||
* @returns An object containing blocks and timeslices conversion functions.
|
||||
*/
|
||||
export const createGet = (constants: ChainConstants) => ({
|
||||
blocks: {
|
||||
/**
|
||||
* Convert timeslices to Coretime blocks.
|
||||
*
|
||||
* @param ts - Number of timeslices.
|
||||
* @returns Number of Coretime blocks.
|
||||
*/
|
||||
coretime: (ts: number) => {
|
||||
return ts * constants.coretime.blocksPerTimeslice;
|
||||
},
|
||||
/**
|
||||
* Convert timeslices to Relay blocks.
|
||||
*
|
||||
* @param ts - Number of timeslices.
|
||||
* @returns Number of Relay blocks.
|
||||
*/
|
||||
relay: (ts: number) => {
|
||||
return ts * constants.relay.blocksPerTimeslice;
|
||||
}
|
||||
},
|
||||
timeslices: {
|
||||
/**
|
||||
* Convert Coretime blocks to timeslices.
|
||||
*
|
||||
* @param blocks - Number of Coretime blocks.
|
||||
* @returns Number of timeslices.
|
||||
*/
|
||||
coretime: (blocks: number) => {
|
||||
return blocks / constants.coretime.blocksPerTimeslice;
|
||||
},
|
||||
/**
|
||||
* Convert Relay blocks to timeslices.
|
||||
*
|
||||
* @param blocks - Number of Relay blocks.
|
||||
* @returns Number of timeslices.
|
||||
*/
|
||||
relay: (blocks: number) => {
|
||||
return blocks / constants.relay.blocksPerTimeslice;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the start and end of the current region
|
||||
* broker.saleInfo call returns the start/end of the next region always
|
||||
*
|
||||
* The end of the current region is the start of the next region, which is returned by broker.saleInfo call
|
||||
*
|
||||
* @param saleInfo - The sale information
|
||||
* @param config - The broker configuration
|
||||
*
|
||||
* @returns The start and end of the current region
|
||||
*/
|
||||
export const getCurrentRegionStartEndTs = (saleInfo: RegionInfo, regionLength: number) => {
|
||||
return {
|
||||
currentRegionEnd: saleInfo.regionBegin,
|
||||
currentRegionStart: saleInfo.regionBegin - regionLength
|
||||
};
|
||||
};
|
||||
|
||||
export const getAvailableNumberOfCores = (coretimeInfo: CoretimeInformation) =>
|
||||
Number(coretimeInfo?.salesInfo?.coresOffered) - Number(coretimeInfo?.salesInfo.coresSold);
|
||||
|
||||
export const constructSubscanQuery = (blockStart: number, blockEnd: number, chainName: string, module = 'broker', call = 'purchase') => {
|
||||
const page = 1;
|
||||
const pageSize = 25;
|
||||
const signed = 'all';
|
||||
const baseURL = `https://coretime-${chainName}.subscan.io/extrinsic`;
|
||||
|
||||
return `${baseURL}?page=${page}&time_dimension=block&page_size=${pageSize}&module=${module}&signed=${signed}&call=${call}&block_start=${blockStart}&block_end=${blockEnd}`;
|
||||
};
|
||||
261
packages/page-coretime/src/utils/sale.ts
Normal file
261
packages/page-coretime/src/utils/sale.ts
Normal file
@ -0,0 +1,261 @@
|
||||
// Copyright 2017-2024 @polkadot/app-coretime authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ChainConstants, PalletBrokerConfigRecord, PalletBrokerSaleInfoRecord } from '@polkadot/react-hooks/types';
|
||||
import type { ChainName, PhaseConfig, RegionInfo, SaleDetails, SaleParameters } from '../types.js';
|
||||
|
||||
import { type ProgressBarSection } from '@polkadot/react-components/types';
|
||||
import { BN } from '@polkadot/util';
|
||||
|
||||
import { PhaseName } from '../constants.js';
|
||||
import { createGet, estimateTime, FirstCycleStart, getCurrentRegionStartEndTs } from './index.js';
|
||||
|
||||
// We are scaling everything to avoid floating point precision issues.
|
||||
const SCALE = new BN(10000);
|
||||
|
||||
export const leadinFactorAt = (scaledWhen: BN): BN => {
|
||||
const scaledHalf = SCALE.div(new BN(2)); // 0.5 scaled to 10000
|
||||
|
||||
if (scaledWhen.lte(scaledHalf)) {
|
||||
// First half of the graph, steeper slope
|
||||
return SCALE.mul(new BN(100)).sub(scaledWhen.mul(new BN(180)));
|
||||
} else {
|
||||
// Second half of the graph, flatter slope
|
||||
return SCALE.mul(new BN(19)).sub(scaledWhen.mul(new BN(18)));
|
||||
}
|
||||
};
|
||||
|
||||
export const getCorePriceAt = (blockNow: number | null, saleInfo: PalletBrokerSaleInfoRecord | undefined): BN => {
|
||||
if (!saleInfo || !blockNow) {
|
||||
return new BN(0);
|
||||
}
|
||||
|
||||
const { endPrice, leadinLength, saleStart } = saleInfo;
|
||||
|
||||
// Explicit conversion to BN
|
||||
const blockNowBn = new BN(blockNow);
|
||||
const saleStartBn = new BN(saleStart);
|
||||
const leadinLengthBn = new BN(leadinLength);
|
||||
|
||||
// Elapsed time since the start of the sale, constrained to not exceed the total lead-in period
|
||||
const elapsedTimeSinceSaleStart = blockNowBn.sub(saleStartBn);
|
||||
const cappedElapsedTime = elapsedTimeSinceSaleStart.lt(leadinLengthBn)
|
||||
? elapsedTimeSinceSaleStart
|
||||
: leadinLengthBn;
|
||||
|
||||
const scaledProgress = cappedElapsedTime.mul(new BN(10000)).div(leadinLengthBn);
|
||||
/**
|
||||
* Progress is a normalized value between 0 and 1, where:
|
||||
*
|
||||
* 0 means the sale just started.
|
||||
* 1 means the sale is at the end of the lead-in period.
|
||||
*
|
||||
* We are scaling it to avoid floating point precision issues.
|
||||
*/
|
||||
const leadinFactor = leadinFactorAt(scaledProgress);
|
||||
const scaledPrice = leadinFactor.mul(endPrice).div(SCALE);
|
||||
|
||||
return scaledPrice;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the current sale number
|
||||
*
|
||||
* @param currentRegionEnd - The end of the current region
|
||||
* @param chainName - The name of the chain
|
||||
* @param config - broker.configuration call response
|
||||
*
|
||||
* @returns The current sale number
|
||||
*/
|
||||
export const getCurrentSaleNumber = (
|
||||
currentRegionEnd: number,
|
||||
chainName: ChainName,
|
||||
config: Pick<PalletBrokerConfigRecord, 'interludeLength' | 'leadinLength' | 'regionLength'>
|
||||
): number => {
|
||||
if (!chainName || !currentRegionEnd) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return Math.ceil((currentRegionEnd - FirstCycleStart.timeslice.coretime[chainName]) / config.regionLength);
|
||||
};
|
||||
|
||||
export const determinePhaseName = (
|
||||
lastCommittedTimeslice: number,
|
||||
currentRegionStart: number,
|
||||
interludeLengthTs: number,
|
||||
leadInLengthTs: number): typeof PhaseName[keyof typeof PhaseName] => {
|
||||
const progress = lastCommittedTimeslice - currentRegionStart;
|
||||
|
||||
if (progress < interludeLengthTs) {
|
||||
return PhaseName.Renewals;
|
||||
}
|
||||
|
||||
if (progress < interludeLengthTs + leadInLengthTs) {
|
||||
return PhaseName.PriceDiscovery;
|
||||
}
|
||||
|
||||
return PhaseName.FixedPrice;
|
||||
};
|
||||
|
||||
export const getSaleProgress = (
|
||||
lastCommittedTimeslice: number | undefined,
|
||||
currentRegionStart: number,
|
||||
interludeLengthTs: number,
|
||||
leadInLengthTs: number,
|
||||
regionBegin: number): ProgressBarSection[] => {
|
||||
if (!lastCommittedTimeslice || !currentRegionStart || !interludeLengthTs || !leadInLengthTs || !regionBegin) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const progress = lastCommittedTimeslice - currentRegionStart;
|
||||
|
||||
return [
|
||||
{
|
||||
label: PhaseName.Renewals,
|
||||
total: interludeLengthTs,
|
||||
value: Math.min(progress, interludeLengthTs)
|
||||
},
|
||||
{
|
||||
label: PhaseName.PriceDiscovery,
|
||||
total: leadInLengthTs,
|
||||
value: Math.min(Math.max(progress - interludeLengthTs, 0), leadInLengthTs)
|
||||
},
|
||||
{
|
||||
label: PhaseName.FixedPrice,
|
||||
total: regionBegin - currentRegionStart - interludeLengthTs - leadInLengthTs,
|
||||
value: Math.max(progress - interludeLengthTs - leadInLengthTs, 0)
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
const getPhaseConfiguration = (
|
||||
currentRegionStart: number,
|
||||
regionLength: number,
|
||||
interludeLengthTs: number,
|
||||
leadInLengthTs: number,
|
||||
lastCommittedTimeslice: number,
|
||||
constants: ChainConstants
|
||||
): PhaseConfig => {
|
||||
const renewalsEndTs = currentRegionStart + interludeLengthTs;
|
||||
const priceDiscoveryEndTs = renewalsEndTs + leadInLengthTs;
|
||||
const fixedPriceLenght = regionLength - interludeLengthTs - leadInLengthTs;
|
||||
const fixedPriceEndTs = priceDiscoveryEndTs + fixedPriceLenght;
|
||||
const get = createGet(constants);
|
||||
|
||||
return {
|
||||
config: {
|
||||
[PhaseName.Renewals]: {
|
||||
lastBlock: get.blocks.relay(renewalsEndTs),
|
||||
lastTimeslice: renewalsEndTs
|
||||
},
|
||||
[PhaseName.PriceDiscovery]: {
|
||||
lastBlock: get.blocks.relay(priceDiscoveryEndTs),
|
||||
lastTimeslice: priceDiscoveryEndTs
|
||||
},
|
||||
[PhaseName.FixedPrice]: {
|
||||
lastBlock: get.blocks.relay(fixedPriceEndTs),
|
||||
lastTimeslice: fixedPriceEndTs
|
||||
}
|
||||
},
|
||||
currentPhaseName: determinePhaseName(lastCommittedTimeslice, currentRegionStart, interludeLengthTs, leadInLengthTs)
|
||||
};
|
||||
};
|
||||
|
||||
export const getSaleParameters = (
|
||||
salesInfo: RegionInfo,
|
||||
config: Pick<PalletBrokerConfigRecord, 'interludeLength' | 'leadinLength' | 'regionLength'>,
|
||||
chainName: ChainName,
|
||||
lastCommittedTimeslice: number,
|
||||
constants: ChainConstants
|
||||
): SaleParameters => {
|
||||
// The sale is happening on the coretime chain, so we need to convert the timeslices to blocks (40 blocks per timeslice)
|
||||
const get = createGet(constants);
|
||||
const interludeLengthTs = get.timeslices.coretime(config.interludeLength);
|
||||
const leadInLengthTs = get.timeslices.coretime(config.leadinLength);
|
||||
|
||||
const { currentRegionEnd, currentRegionStart } = getCurrentRegionStartEndTs(salesInfo, config.regionLength);
|
||||
const phaseConfig = getPhaseConfiguration(
|
||||
currentRegionStart,
|
||||
config.regionLength,
|
||||
interludeLengthTs,
|
||||
leadInLengthTs,
|
||||
lastCommittedTimeslice,
|
||||
constants
|
||||
);
|
||||
|
||||
const saleNumber = getCurrentSaleNumber(currentRegionEnd, chainName, config);
|
||||
|
||||
return {
|
||||
currentRegion: {
|
||||
end: {
|
||||
blocks: get.blocks.relay(currentRegionEnd),
|
||||
ts: currentRegionEnd
|
||||
},
|
||||
start: {
|
||||
blocks: get.blocks.relay(currentRegionStart),
|
||||
ts: currentRegionStart
|
||||
}
|
||||
},
|
||||
cycleNumber: getCurrentSaleNumber(currentRegionEnd, chainName, config),
|
||||
interlude: {
|
||||
blocks: config.interludeLength,
|
||||
ts: interludeLengthTs
|
||||
},
|
||||
leadin: {
|
||||
blocks: config.leadinLength,
|
||||
ts: leadInLengthTs
|
||||
},
|
||||
phaseConfig,
|
||||
regionNumber: saleNumber - 1
|
||||
};
|
||||
};
|
||||
|
||||
export function calculateSaleDetails (
|
||||
saleNumber: number,
|
||||
currentSaleNumber: number,
|
||||
latestBlock: number,
|
||||
chainName: ChainName,
|
||||
regionLength: number,
|
||||
saleParams: SaleParameters,
|
||||
constants: ChainConstants
|
||||
): SaleDetails | null {
|
||||
if (saleNumber === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const get = createGet(constants);
|
||||
|
||||
const blocksPerSaleRelay = get.blocks.relay(regionLength);
|
||||
const saleStartBlock = saleParams.currentRegion.start.blocks - blocksPerSaleRelay * (currentSaleNumber - saleNumber - 1);
|
||||
const saleEndBlock = saleStartBlock + blocksPerSaleRelay;
|
||||
|
||||
const saleStartTs = get.timeslices.relay(saleStartBlock);
|
||||
const saleEndTs = get.timeslices.relay(saleEndBlock);
|
||||
|
||||
const saleStartBlockCoretime = FirstCycleStart.block.coretime[chainName] + get.blocks.coretime((saleNumber) * regionLength);
|
||||
const saleEndBlockCoretime = saleStartBlockCoretime + get.blocks.coretime(regionLength);
|
||||
|
||||
const data = {
|
||||
coretime: {
|
||||
end: { block: saleEndBlockCoretime },
|
||||
start: { block: saleStartBlockCoretime }
|
||||
},
|
||||
date: {
|
||||
end: estimateTime(saleEndTs, latestBlock, constants.relay),
|
||||
start: estimateTime(saleStartTs, latestBlock, constants.relay)
|
||||
},
|
||||
relay: {
|
||||
end: {
|
||||
block: saleEndBlock,
|
||||
ts: saleEndTs
|
||||
},
|
||||
start: {
|
||||
block: saleStartBlock,
|
||||
ts: saleStartTs
|
||||
}
|
||||
},
|
||||
saleNumber
|
||||
};
|
||||
|
||||
return data;
|
||||
}
|
||||
@ -4,7 +4,8 @@
|
||||
import React, { useMemo } from 'react';
|
||||
|
||||
import { useApi, useRegistrars, useSubidentities, useToggle } from '@polkadot/react-hooks';
|
||||
import { type AddressIdentity, AddressIdentityOtherDiscordKey } from '@polkadot/react-hooks/types';
|
||||
import { AddressIdentityOtherDiscordKey } from '@polkadot/react-hooks/constants';
|
||||
import { type AddressIdentity } from '@polkadot/react-hooks/types';
|
||||
import { isHex } from '@polkadot/util';
|
||||
|
||||
import AddressMini from '../AddressMini.js';
|
||||
|
||||
100
packages/react-components/src/ProgressBar.tsx
Normal file
100
packages/react-components/src/ProgressBar.tsx
Normal file
@ -0,0 +1,100 @@
|
||||
// Copyright 2017-2024 @polkadot/react-components authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ProgressBarSection } from './types.js';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { styled } from './styled.js';
|
||||
|
||||
interface Props {
|
||||
sections: ProgressBarSection[];
|
||||
}
|
||||
|
||||
function ProgressBar ({ sections }: Props): React.ReactElement<Props> | null {
|
||||
const overallTotal = sections?.reduce((sum, section) => sum + section.total, 0);
|
||||
|
||||
return (
|
||||
<StyledDiv>
|
||||
<div className='progress-container'>
|
||||
{sections?.map((section, index) => {
|
||||
const sectionWidth = (section.total / overallTotal) * 100;
|
||||
const sectionProgress = (section.value / section.total) * 100;
|
||||
|
||||
return (
|
||||
<div
|
||||
className='progress-segment'
|
||||
key={index}
|
||||
style={{ width: `${sectionWidth}%` }}
|
||||
>
|
||||
<div
|
||||
className='progress-bar'
|
||||
style={{ width: `${sectionProgress}%` }}
|
||||
/>
|
||||
<div className='marker' />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className='labels'>
|
||||
{sections.map((section, index) => (
|
||||
<div
|
||||
className='label'
|
||||
key={index}
|
||||
style={{ width: `${100 / sections.length}%` }}
|
||||
>
|
||||
{section.label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</StyledDiv>
|
||||
);
|
||||
}
|
||||
|
||||
const StyledDiv = styled.div`
|
||||
width: 100%;
|
||||
.progress-container {
|
||||
display: flex;
|
||||
height: 1rem;
|
||||
background-color: #e0e0e0;
|
||||
border-radius: 0.5rem;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.progress-segment {
|
||||
position: relative;
|
||||
background-color: transparent;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
background-color: #007bff;
|
||||
height: 100%;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.marker {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: -0.5rem;
|
||||
width: 2px;
|
||||
height: 1.5rem;
|
||||
background-color: #000000;
|
||||
}
|
||||
|
||||
.labels {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.label {
|
||||
text-align: center;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
`;
|
||||
|
||||
export default React.memo(ProgressBar);
|
||||
@ -76,6 +76,7 @@ export { default as Password } from './Password.js';
|
||||
export { default as PasswordStrength } from './PasswordStrength.js';
|
||||
export { default as Popup } from './Popup/index.js';
|
||||
export { default as Progress } from './Progress.js';
|
||||
export { default as ProgressBar } from './ProgressBar.js';
|
||||
export { default as Row } from './Row.js';
|
||||
export { default as Sidebar } from './Sidebar.js';
|
||||
export { default as SortDropdown } from './SortDropdown.js';
|
||||
@ -99,7 +100,6 @@ export { default as TxButton } from './TxButton.js';
|
||||
export { default as UsageBar } from './UsageBar.js';
|
||||
export { default as VoteAccount } from './VoteAccount.js';
|
||||
export { default as VoteValue } from './VoteValue.js';
|
||||
|
||||
// star exports
|
||||
export * from './modals/index.js';
|
||||
export * from './themes.js';
|
||||
|
||||
@ -95,3 +95,9 @@ export interface TabItem {
|
||||
name: string;
|
||||
text: React.ReactNode;
|
||||
}
|
||||
|
||||
export interface ProgressBarSection {
|
||||
value: number;
|
||||
total: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
20
packages/react-hooks/src/constants.ts
Normal file
20
packages/react-hooks/src/constants.ts
Normal file
@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2024 @polkadot/react-hooks authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export const AddressIdentityOtherDiscordKey = 'Discord';
|
||||
|
||||
export enum CoreTimeTypes {
|
||||
'Reservation',
|
||||
'Lease',
|
||||
'Bulk Coretime',
|
||||
'On Demand'
|
||||
}
|
||||
|
||||
export const ChainRenewalStatus = {
|
||||
Eligible: 'eligible',
|
||||
None: '-',
|
||||
Renewed: 'renewed'
|
||||
};
|
||||
|
||||
// block time on coretime chain is 2 x slower than on relay chain
|
||||
export const BlockTimeCoretimeToRelayConstant = 2;
|
||||
@ -13,6 +13,7 @@ import type { ICompact, IExtrinsic, INumber } from '@polkadot/types/types';
|
||||
import type { KeyringJson$Meta } from '@polkadot/ui-keyring/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CoreTimeTypes } from './constants.js';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export type CallParam = any;
|
||||
@ -109,8 +110,6 @@ export interface AddressFlags extends DeriveAccountFlags {
|
||||
isNominator: boolean;
|
||||
}
|
||||
|
||||
export const AddressIdentityOtherDiscordKey = 'Discord';
|
||||
|
||||
export interface AddressIdentity extends DeriveAccountRegistration {
|
||||
isExistent: boolean;
|
||||
isKnownGood: boolean;
|
||||
@ -336,8 +335,18 @@ export interface ChainInformation {
|
||||
reservation: Reservation| undefined
|
||||
workTaskInfo: ChainWorkTaskInformation[]
|
||||
}
|
||||
export interface ChainBlockConstants {
|
||||
blocksPerTimeslice: number,
|
||||
blocktimeMs: number
|
||||
}
|
||||
|
||||
export interface ChainConstants {
|
||||
coretime: ChainBlockConstants,
|
||||
relay: ChainBlockConstants
|
||||
}
|
||||
|
||||
export interface CoretimeInformation {
|
||||
constants: ChainConstants,
|
||||
chainInfo: Record<number, ChainInformation>,
|
||||
salesInfo: PalletBrokerSaleInfoRecord,
|
||||
status: BrokerStatus,
|
||||
@ -363,26 +372,3 @@ export interface PotentialRenewal {
|
||||
maskBits: number,
|
||||
task: string
|
||||
}
|
||||
|
||||
export enum CoreTimeTypes {
|
||||
'Reservation',
|
||||
'Lease',
|
||||
'Bulk Coretime',
|
||||
'On Demand'
|
||||
}
|
||||
|
||||
export const ChainRenewalStatus = {
|
||||
Eligible: 'eligible',
|
||||
None: '-',
|
||||
Renewed: 'renewed'
|
||||
};
|
||||
|
||||
// RelayChain
|
||||
export const CoreTimeConsts = {
|
||||
BlockTime: 6000,
|
||||
BlocksPerTimeslice: 80
|
||||
};
|
||||
|
||||
export const CoreTimeChainConsts = {
|
||||
BlocksPerTimeslice: 40
|
||||
};
|
||||
|
||||
49
packages/react-hooks/src/useCoretimeConsts.ts
Normal file
49
packages/react-hooks/src/useCoretimeConsts.ts
Normal file
@ -0,0 +1,49 @@
|
||||
// Copyright 2017-2024 @polkadot/react-hooks authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ChainConstants } from './types.js';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { useApi, useBlockTime } from '@polkadot/react-hooks';
|
||||
import { BN, BN_ONE, BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { createNamedHook } from './createNamedHook.js';
|
||||
|
||||
function useCoretimeConstsImpl (): ChainConstants | undefined {
|
||||
const { api, apiCoretime, isApiReady } = useApi();
|
||||
const [coretimeConstants, setCoretimeConstants] = useState<ChainConstants | undefined>();
|
||||
|
||||
const [blockTimeMsRelayChain] = useBlockTime(BN_ONE, api);
|
||||
const blockTimeMsCoretimeChain = apiCoretime?.consts.aura?.slotDuration;
|
||||
const blocksPerTimesliceRelayChain = apiCoretime?.consts.broker?.timeslicePeriod;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isApiReady || !blockTimeMsRelayChain || !blockTimeMsCoretimeChain || !blocksPerTimesliceRelayChain) {
|
||||
return;
|
||||
}
|
||||
|
||||
const blockTimeMsCoretimeChainBN = new BN(blockTimeMsCoretimeChain.toString());
|
||||
const blocksPerTimesliceRelayChainBN = new BN(blocksPerTimesliceRelayChain);
|
||||
const relationConstant = blockTimeMsCoretimeChainBN.div(new BN(blockTimeMsRelayChain));
|
||||
|
||||
const blocksPerTimesliceCoretimeChain = relationConstant.gtn(0)
|
||||
? blocksPerTimesliceRelayChainBN.div(relationConstant)
|
||||
: BN_ZERO;
|
||||
|
||||
setCoretimeConstants({
|
||||
coretime: {
|
||||
blocksPerTimeslice: blocksPerTimesliceCoretimeChain.toNumber(),
|
||||
blocktimeMs: blockTimeMsCoretimeChainBN.toNumber()
|
||||
},
|
||||
relay: {
|
||||
blocksPerTimeslice: blocksPerTimesliceRelayChainBN.toNumber(),
|
||||
blocktimeMs: blockTimeMsRelayChain
|
||||
}
|
||||
});
|
||||
}, [isApiReady, blockTimeMsRelayChain, blockTimeMsCoretimeChain, blocksPerTimesliceRelayChain]);
|
||||
|
||||
return coretimeConstants;
|
||||
}
|
||||
|
||||
export const useCoretimeConsts = createNamedHook('useCoretimeConsts', useCoretimeConstsImpl);
|
||||
@ -7,10 +7,11 @@ import type { ChainInformation, CoretimeInformation, CoreWorkload, CoreWorkloadI
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { createNamedHook, useApi, useBrokerConfig, useBrokerLeases, useBrokerReservations, useBrokerSalesInfo, useBrokerStatus, useCoreDescriptor, useRegions, useWorkloadInfos, useWorkplanInfos } from '@polkadot/react-hooks';
|
||||
import { BN } from '@polkadot/util';
|
||||
import { BN, BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { ChainRenewalStatus, CoreTimeChainConsts, CoreTimeTypes } from './types.js';
|
||||
import { ChainRenewalStatus, CoreTimeTypes } from './constants.js';
|
||||
import { useBrokerPotentialRenewals } from './useBrokerPotentialRenewals.js';
|
||||
import { useCoretimeConsts } from './useCoretimeConsts.js';
|
||||
|
||||
const getOccupancyType = (lease: LegacyLease | undefined, reservation: Reservation | undefined, isPool: boolean): CoreTimeTypes => {
|
||||
if (isPool) {
|
||||
@ -25,6 +26,7 @@ function useCoretimeInformationImpl (api: ApiPromise, ready: boolean): CoretimeI
|
||||
|
||||
const [workloadData, setWorkloadData] = useState<CoreWorkload[]>([]);
|
||||
const [taskIds, setTaskIds] = useState<number[]>([]);
|
||||
const [blocksPerTimesliceCoretimeChain, setBlocksPerTimesliceCoretimeChain] = useState<BN | undefined>();
|
||||
|
||||
/** coretime API calls */
|
||||
const status = useBrokerStatus(apiCoretime, isApiReady);
|
||||
@ -36,22 +38,32 @@ function useCoretimeInformationImpl (api: ApiPromise, ready: boolean): CoretimeI
|
||||
const config = useBrokerConfig(apiCoretime, isApiReady);
|
||||
const potentialRenewals = useBrokerPotentialRenewals(apiCoretime, isApiReady);
|
||||
const region = useRegions(apiCoretime);
|
||||
const coretimeConstants = useCoretimeConsts();
|
||||
|
||||
/** Coretime constants */
|
||||
useEffect(() => {
|
||||
if (!coretimeConstants?.coretime.blocksPerTimeslice) {
|
||||
return;
|
||||
}
|
||||
|
||||
setBlocksPerTimesliceCoretimeChain(new BN(coretimeConstants.coretime.blocksPerTimeslice));
|
||||
}, [coretimeConstants]);
|
||||
/** *******************/
|
||||
|
||||
/** Other APIs */
|
||||
const coreInfos = useCoreDescriptor(api, ready);
|
||||
const paraIds = useMemo(() => coreInfos && [...new Set(coreInfos?.map((a) => a.info.currentWork.assignments.map((ass) => ass.task)).flat().filter((id) => id !== 'Pool'))], [coreInfos]);
|
||||
|
||||
const isInterludePhase = useMemo(() => {
|
||||
if (!salesInfo || !config || !status) {
|
||||
if (!salesInfo || !config || !status || !blocksPerTimesliceCoretimeChain) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const currentRegionStart = new BN(salesInfo?.regionBegin).sub(new BN(config.regionLength));
|
||||
const interludeLengthTs = new BN(config?.interludeLength).div(new BN(CoreTimeChainConsts.BlocksPerTimeslice));
|
||||
const interludeLengthTs = blocksPerTimesliceCoretimeChain.gt(BN_ZERO) ? new BN(config?.interludeLength).div(blocksPerTimesliceCoretimeChain) : BN_ZERO;
|
||||
const interludeEndTs = currentRegionStart.add(interludeLengthTs);
|
||||
|
||||
return interludeEndTs.gte(new BN(status?.lastCommittedTimeslice));
|
||||
}, [status, salesInfo, config]);
|
||||
}, [status, salesInfo, config, blocksPerTimesliceCoretimeChain]);
|
||||
|
||||
const potentialRenewalsCurrentRegion = useMemo(() => {
|
||||
if (!isInterludePhase || !config || !salesInfo) {
|
||||
@ -65,16 +77,21 @@ function useCoretimeInformationImpl (api: ApiPromise, ready: boolean): CoretimeI
|
||||
const [state, setState] = useState<CoretimeInformation | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
if (paraIds?.length && potentialRenewals?.length && !taskIds.length) {
|
||||
if (paraIds?.length && !taskIds.length) {
|
||||
const simpleIds = paraIds.map((p) => Number(p));
|
||||
const renewalIds = potentialRenewals?.map((r) => Number(r.task));
|
||||
const numbers = [...new Set(simpleIds.concat(renewalIds))];
|
||||
|
||||
if (numbers?.length > simpleIds.length) {
|
||||
setTaskIds(numbers.sort((a, b) => a - b));
|
||||
} else {
|
||||
setTaskIds(simpleIds);
|
||||
if (renewalIds) {
|
||||
const numbers = [...new Set(simpleIds.concat(renewalIds))];
|
||||
|
||||
if (numbers?.length > simpleIds.length) {
|
||||
setTaskIds(numbers.sort((a, b) => a - b));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setTaskIds(simpleIds);
|
||||
}
|
||||
}, [potentialRenewals, paraIds, taskIds]);
|
||||
|
||||
@ -102,7 +119,7 @@ function useCoretimeInformationImpl (api: ApiPromise, ready: boolean): CoretimeI
|
||||
}, [workloads, coreInfos]);
|
||||
|
||||
useEffect((): void => {
|
||||
if (!workloadData?.length || !leases?.length || !reservations?.length) {
|
||||
if (!workloadData?.length || !reservations?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -110,7 +127,7 @@ function useCoretimeInformationImpl (api: ApiPromise, ready: boolean): CoretimeI
|
||||
|
||||
taskIds?.forEach((id) => {
|
||||
const taskId = id.toString();
|
||||
const lease = leases?.find((lease) => lease.task === taskId);
|
||||
const lease = leases?.length ? leases?.find((lease) => lease.task === taskId) : undefined;
|
||||
const reservation = reservations?.find((reservation) => reservation.task === taskId);
|
||||
const workloads = workloadData?.filter((one) => one.info.task === taskId);
|
||||
|
||||
@ -139,17 +156,30 @@ function useCoretimeInformationImpl (api: ApiPromise, ready: boolean): CoretimeI
|
||||
};
|
||||
});
|
||||
|
||||
if (chainInfo && config && region && salesInfo && status) {
|
||||
if (chainInfo && config && region && salesInfo && status && coretimeConstants) {
|
||||
setState({
|
||||
chainInfo,
|
||||
config,
|
||||
constants: coretimeConstants,
|
||||
region,
|
||||
salesInfo,
|
||||
status,
|
||||
taskIds
|
||||
});
|
||||
}
|
||||
}, [taskIds, workloadData, potentialRenewalsCurrentRegion, salesInfo, leases, reservations, region, status, config, workplans]);
|
||||
}, [
|
||||
config,
|
||||
coretimeConstants,
|
||||
taskIds,
|
||||
workloadData,
|
||||
potentialRenewalsCurrentRegion,
|
||||
salesInfo,
|
||||
leases,
|
||||
reservations,
|
||||
region,
|
||||
status,
|
||||
workplans
|
||||
]);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user