diff --git a/packages/page-accounts/src/modals/IdentityMain.tsx b/packages/page-accounts/src/modals/IdentityMain.tsx index 0d7155c1ab..e15168aba3 100644 --- a/packages/page-accounts/src/modals/IdentityMain.tsx +++ b/packages/page-accounts/src/modals/IdentityMain.tsx @@ -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'; diff --git a/packages/page-broker/src/Overview/Summary.tsx b/packages/page-broker/src/Overview/Summary.tsx index 28e53cc909..d9f32ef06c 100644 --- a/packages/page-broker/src/Overview/Summary.tsx +++ b/packages/page-broker/src/Overview/Summary.tsx @@ -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')} >
-
{estimateTime(currentRegionStart, status?.lastTimeslice * 80)}
-
{estimateTime(currentRegionEnd, status?.lastTimeslice * 80)}
+
{estimateTime(currentRegionStart, status?.lastTimeslice * 80, coretimeConstants?.relay)}
+
{estimateTime(currentRegionEnd, status?.lastTimeslice * 80, coretimeConstants?.relay)}
= { [CoreTimeTypes.Reservation]: 'orange', diff --git a/packages/page-broker/src/Overview/Workload.tsx b/packages/page-broker/src/Overview/Workload.tsx index ce9a897340..b9f6b6cf71 100644 --- a/packages/page-broker/src/Overview/Workload.tsx +++ b/packages/page-broker/src/Overview/Workload.tsx @@ -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 { const { isApiReady } = useApi(); const salesInfo = useBrokerSalesInfo(api, isApiReady); + const coretimeConstants = useCoretimeConsts(); const status = useCall>(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; diff --git a/packages/page-broker/src/types.ts b/packages/page-broker/src/types.ts index 28547c792e..1adc9581aa 100644 --- a/packages/page-broker/src/types.ts +++ b/packages/page-broker/src/types.ts @@ -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 diff --git a/packages/page-broker/src/utils.ts b/packages/page-broker/src/utils.ts index bf1f36fe8c..bdd4ed33bf 100644 --- a/packages/page-broker/src/utils.ts +++ b/packages/page-broker/src/utils.ts @@ -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; diff --git a/packages/page-coretime/src/CoretimeContext.tsx b/packages/page-coretime/src/CoretimeContext.tsx new file mode 100644 index 0000000000..a92469c71a --- /dev/null +++ b/packages/page-coretime/src/CoretimeContext.tsx @@ -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 | null; +} + +const CoretimeContext = createContext({ + 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 ( + + {children} + + ); +}; + +export const useCoretimeContext = () => useContext(CoretimeContext); diff --git a/packages/page-coretime/src/CoretimePage.tsx b/packages/page-coretime/src/CoretimePage.tsx new file mode 100644 index 0000000000..5e761f207d --- /dev/null +++ b/packages/page-coretime/src/CoretimePage.tsx @@ -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): TabItem[] { + return [ + { + isRoot: true, + name: 'overview', + text: t('Overview') + }, + { + name: 'sale', + text: t('Sale') + } + ]; +} + +function CoretimePage ({ api, basePath, className, isApiReady }: Props): React.ReactElement { + const { t } = useTranslation(); + const itemsRef = useRef(createItemsRef(t)); + const chainName = useCall(isApiReady && api?.rpc.system.chain)?.toString().toLowerCase() as ChainName; + + return ( +
+ + + + } + index + /> + } + path='sale' + /> + + +
+ ); +} + +export default React.memo(CoretimePage); diff --git a/packages/page-coretime/src/Overview/Summary.tsx b/packages/page-coretime/src/Overview/Summary.tsx index fa57045494..48db3b29d6 100644 --- a/packages/page-coretime/src/Overview/Summary.tsx +++ b/packages/page-coretime/src/Overview/Summary.tsx @@ -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 { +function Summary ({ chainName, config, constants, parachainCount, saleInfo, status }: Props): React.ReactElement { const { t } = useTranslation(); const currentRegionEnd = saleInfo.regionEnd - config.regionLength; const currentRegionStart = saleInfo.regionEnd - config.regionLength * 2; - const chainName = useCall(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 (
- - {status?.lastTimeslice} - - - {`${saleInfo?.coresSold} / ${saleInfo?.coresOffered}`} - - - {parachainCount && parachainCount} - {status && - +
{cycleNumber}
} + + {status?.lastTimeslice} + + + {parachainCount && parachainCount} + {config && status &&
-
{estimateTime(currentRegionStart, status?.lastTimeslice * 80)}
-
{estimateTime(currentRegionEnd, status?.lastTimeslice * 80)}
+
{get && estimateTime(currentRegionStart, get.blocks.relay(status?.lastTimeslice), constants.relay)}
+
{get && estimateTime(currentRegionEnd, get.blocks.relay(status?.lastTimeslice), constants.relay)}
) } diff --git a/packages/page-coretime/src/Overview/index.tsx b/packages/page-coretime/src/Overview/index.tsx new file mode 100644 index 0000000000..8f4b890569 --- /dev/null +++ b/packages/page-coretime/src/Overview/index.tsx @@ -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 { + const { coretimeInfo } = useCoretimeContext(); + + return ( +
+ {coretimeInfo && ( + + )} + {!!coretimeInfo && + + } +
+ ); +} + +export default React.memo(Overview); diff --git a/packages/page-coretime/src/ParachainTableRow.tsx b/packages/page-coretime/src/ParachainTableRow.tsx index efad721b55..3db146424e 100644 --- a/packages/page-coretime/src/ParachainTableRow.tsx +++ b/packages/page-coretime/src/ParachainTableRow.tsx @@ -42,10 +42,10 @@ function ParachainTableRow ({ chain, lastCommittedTimeslice, regionBegin, region {idx === 0 && {!!multiple && - + } } ; diff --git a/packages/page-coretime/src/ParachainsTable.tsx b/packages/page-coretime/src/ParachainsTable.tsx index 56f7811a68..82188cd1cb 100644 --- a/packages/page-coretime/src/ParachainsTable.tsx +++ b/packages/page-coretime/src/ParachainsTable.tsx @@ -33,6 +33,7 @@ function ParachainsTable ({ coretimeInfo }: Props): React.ReactElement { header={headerRef.current} isSplit={false} > + {coretimeInfo?.taskIds?.map((taskId: number) => { const chain = coretimeInfo.chainInfo[taskId]; diff --git a/packages/page-coretime/src/Row.tsx b/packages/page-coretime/src/Row.tsx index b032ecb508..42c1f3646b 100644 --- a/packages/page-coretime/src/Row.tsx +++ b/packages/page-coretime/src/Row.tsx @@ -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 ( {id} @@ -57,11 +59,11 @@ function Row ({ chainRecord, highlight = false, id, lastCommittedTimeslice, leas {showEstimates && formatNumber(targetTimeslice * 80).toString()} + >{showEstimates && get && formatNumber(get.blocks.relay(targetTimeslice)).toString()} {showEstimates && estimateTime(targetTimeslice, lastCommittedTimeslice * 80)} + >{showEstimates && get && coretimeInfo && estimateTime(targetTimeslice, get.blocks.relay(lastCommittedTimeslice), coretimeInfo?.constants?.relay)} { + 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 ( + + + + + + + + + + + + + + + + +
Start{saleDetails.date.start}{saleDetails.relay.start.block}{saleDetails.coretime.start.block}{saleDetails.relay.start.ts}
End{saleDetails.date.end}{saleDetails.relay.end.block}{saleDetails.coretime.end.block}{saleDetails.relay.end.ts}
+ ); +} + +export default React.memo(SaleTable); diff --git a/packages/page-coretime/src/Sale/Summary.tsx b/packages/page-coretime/src/Sale/Summary.tsx new file mode 100644 index 0000000000..5b89836b17 --- /dev/null +++ b/packages/page-coretime/src/Sale/Summary.tsx @@ -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 { + 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 ( + +
+ {status && + +
+ {cycleNumber > -1 ? cycleNumber : '-'} +
+
+ } + + {`${saleInfo?.coresSold} / ${saleInfo?.coresOffered}`} + + +
{cycleEnd}
+
+ +
{get && formatNumber(get.blocks.relay(currentRegionEnd))}
+
+ +
{formatNumber(currentRegionEnd)}
+
+ {config && status && + + } +
+
+ {status && + ( +
+
{cycleStart}
+
{cycleEnd}
+
+
) + } + {status && + +
+
{currentRegionStart}
+
{currentRegionEnd}
+
+
+ } +
+
+ ); +} + +export default React.memo(Summary); diff --git a/packages/page-coretime/src/Sale/index.tsx b/packages/page-coretime/src/Sale/index.tsx new file mode 100644 index 0000000000..5b1012006c --- /dev/null +++ b/packages/page-coretime/src/Sale/index.tsx @@ -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 { + 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(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(-1); + const [saleDetails, setSaleDetails] = useState(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 ( +
+ {coretimeInfo && saleParams && + } +
+ +
+ + {phaseName === PhaseName.Renewals + ? ( + Cores cannot be purchased now + ) + : ( + {coretimePrice && formatBalance(coretimePrice)} + )} + + + {/* TODO: Add core purchase functionality */} + {/* {
+
} */} +
+
+ +
+ {phaseName && <> + {phaseName} + {get && coretimeInfo && saleParams?.phaseConfig && estimateTime(saleParams.phaseConfig.config[phaseName].lastTimeslice, get.blocks.relay(coretimeInfo?.status.lastTimeslice), coretimeInfo.constants.relay)} + {formatNumber(saleParams?.phaseConfig?.config[phaseName].lastBlock)} + } + {formatBalance(coretimeInfo?.salesInfo.endPrice)} +
+
+ +
+
+ +
+
+

Interlude + sale data

+
+
+ + +
+ {chosenSaleNumber > -1 && !!saleDetails &&
+ + +
} + {chosenSaleNumber > -1 && !!saleDetails &&
+

Query sale transactions

+

We do not index transactions ourselves but you can query historical transactions on Subscan.
+ The button below will open a new tab with the correct query parameters for the chosen sale.

+
+ + } +
+
+
+
+ ); +} + +export default Sale; diff --git a/packages/page-coretime/src/constants.ts b/packages/page-coretime/src/constants.ts new file mode 100644 index 0000000000..0e96ddd2b6 --- /dev/null +++ b/packages/page-coretime/src/constants.ts @@ -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; diff --git a/packages/page-coretime/src/index.tsx b/packages/page-coretime/src/index.tsx index 3125e2b327..f71e78ecaf 100644 --- a/packages/page-coretime/src/index.tsx +++ b/packages/page-coretime/src/index.tsx @@ -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): TabItem[] { - return [ - { - isRoot: true, - name: 'overview', - text: t('Overview') - } - ]; -} - function CoretimeApp ({ basePath, className }: Props): React.ReactElement { - const { t } = useTranslation(); const { api, isApiReady } = useApi(); - const itemsRef = useRef(createItemsRef(t)); - const coretimeInfo = useCoretimeInformation(api, isApiReady); return ( -
- + - {coretimeInfo && ( - - )} - {!!coretimeInfo && - - } - -
+ ); } diff --git a/packages/page-coretime/src/types.ts b/packages/page-coretime/src/types.ts index b5afab7d6a..c765abf645 100644 --- a/packages/page-coretime/src/types.ts +++ b/packages/page-coretime/src/types.ts @@ -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; +} + +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' diff --git a/packages/page-coretime/src/utils.ts b/packages/page-coretime/src/utils.ts deleted file mode 100644 index 432f4cc56a..0000000000 --- a/packages/page-coretime/src/utils.ts +++ /dev/null @@ -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 = { - 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']; -}; diff --git a/packages/page-coretime/src/utils/index.ts b/packages/page-coretime/src/utils/index.ts new file mode 100644 index 0000000000..9582d6cdfb --- /dev/null +++ b/packages/page-coretime/src/utils/index.ts @@ -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 +> +>; + +// 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}`; +}; diff --git a/packages/page-coretime/src/utils/sale.ts b/packages/page-coretime/src/utils/sale.ts new file mode 100644 index 0000000000..fe730311e2 --- /dev/null +++ b/packages/page-coretime/src/utils/sale.ts @@ -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 +): 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, + 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; +} diff --git a/packages/react-components/src/AccountSidebar/Identity.tsx b/packages/react-components/src/AccountSidebar/Identity.tsx index 0bf29b9afa..fe83a88504 100644 --- a/packages/react-components/src/AccountSidebar/Identity.tsx +++ b/packages/react-components/src/AccountSidebar/Identity.tsx @@ -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'; diff --git a/packages/react-components/src/ProgressBar.tsx b/packages/react-components/src/ProgressBar.tsx new file mode 100644 index 0000000000..a102066349 --- /dev/null +++ b/packages/react-components/src/ProgressBar.tsx @@ -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 | null { + const overallTotal = sections?.reduce((sum, section) => sum + section.total, 0); + + return ( + +
+ {sections?.map((section, index) => { + const sectionWidth = (section.total / overallTotal) * 100; + const sectionProgress = (section.value / section.total) * 100; + + return ( +
+
+
+
+ ); + })} +
+
+ {sections.map((section, index) => ( +
+ {section.label} +
+ ))} +
+ + ); +} + +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); diff --git a/packages/react-components/src/index.ts b/packages/react-components/src/index.ts index 4699f6057f..6007c013f6 100644 --- a/packages/react-components/src/index.ts +++ b/packages/react-components/src/index.ts @@ -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'; diff --git a/packages/react-components/src/types.ts b/packages/react-components/src/types.ts index c5766184d1..1d1af1b1bd 100644 --- a/packages/react-components/src/types.ts +++ b/packages/react-components/src/types.ts @@ -95,3 +95,9 @@ export interface TabItem { name: string; text: React.ReactNode; } + +export interface ProgressBarSection { + value: number; + total: number; + label: string; +} diff --git a/packages/react-hooks/src/constants.ts b/packages/react-hooks/src/constants.ts new file mode 100644 index 0000000000..61fd992f29 --- /dev/null +++ b/packages/react-hooks/src/constants.ts @@ -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; diff --git a/packages/react-hooks/src/types.ts b/packages/react-hooks/src/types.ts index dd4317627b..e6cb66ac4f 100644 --- a/packages/react-hooks/src/types.ts +++ b/packages/react-hooks/src/types.ts @@ -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, 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 -}; diff --git a/packages/react-hooks/src/useCoretimeConsts.ts b/packages/react-hooks/src/useCoretimeConsts.ts new file mode 100644 index 0000000000..1f45a89442 --- /dev/null +++ b/packages/react-hooks/src/useCoretimeConsts.ts @@ -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(); + + 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); diff --git a/packages/react-hooks/src/useCoretimeInformation.ts b/packages/react-hooks/src/useCoretimeInformation.ts index dcd3456686..1d373dd204 100644 --- a/packages/react-hooks/src/useCoretimeInformation.ts +++ b/packages/react-hooks/src/useCoretimeInformation.ts @@ -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([]); const [taskIds, setTaskIds] = useState([]); + const [blocksPerTimesliceCoretimeChain, setBlocksPerTimesliceCoretimeChain] = useState(); /** 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(); 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; }