diff --git a/.prettierrc b/.prettierrc index e72878b7..0ba1f22b 100644 --- a/.prettierrc +++ b/.prettierrc @@ -6,5 +6,6 @@ "jsxSingleQuote": true, "trailingComma": "es5", "bracketSpacing": true, - "arrowParens": "always" -} + "arrowParens": "always", + "printWidth": 100 +} \ No newline at end of file diff --git a/cypress/common/index.ts b/cypress/common/index.ts index c5be65ba..242c2d29 100644 --- a/cypress/common/index.ts +++ b/cypress/common/index.ts @@ -23,15 +23,13 @@ export const connectWallet = () => { address: ALICE, name: 'Alice', type: 'sr25519', - mnemonic: - 'bottom drive obey lake curtain smoke basket hold race lonely fit walk', + mnemonic: 'bottom drive obey lake curtain smoke basket hold race lonely fit walk', }, { address: BOB, name: 'Bob', type: 'sr25519', - mnemonic: - 'sample split bamboo west visual approve brain fox arch impact relief smile', + mnemonic: 'sample split bamboo west visual approve brain fox arch impact relief smile', }, ], APP_NAME diff --git a/cypress/e2e/purchase.cy.ts b/cypress/e2e/purchase.cy.ts index 30a68d48..b15f83b5 100644 --- a/cypress/e2e/purchase.cy.ts +++ b/cypress/e2e/purchase.cy.ts @@ -9,16 +9,12 @@ describe('E2E tests for the purchase page', () => { connectWallet(); // Wallet connection works: - cy.get('[data-cy="connect-wallet"]', { timeout: 5 * 1000 }).should( - 'not.exist' - ); + cy.get('[data-cy="connect-wallet"]', { timeout: 5 * 1000 }).should('not.exist'); cy.get('[data-cy="address"]').should('exist'); cy.get('[data-cy="address"]').should('contain.text', '5DfhGy...1EqRzV'); // Fetching complete - cy.get('[data-cy="loading-current-price"]', { timeout: 60 * 1000 }).should( - 'not.exist' - ); + cy.get('[data-cy="loading-current-price"]', { timeout: 60 * 1000 }).should('not.exist'); }); it('Successfully loads the purchase page and all UI elements are in place.', () => { diff --git a/next.config.js b/next.config.js index aae4cefa..490bb2bf 100644 --- a/next.config.js +++ b/next.config.js @@ -13,13 +13,11 @@ const nextConfig = { ROCOCO_CORETIME_INDEXER: process.env.ROCOCO_CORETIME_INDEXER || '', KUSAMA_CORETIME_INDEXER: process.env.KUSAMA_CORETIME_INDEXER || '', - SUBSCAN_CORETIME_WESTEND_INDEXER: - process.env.SUBSCAN_CORETIME_WESTEND_INDEXER || '', + SUBSCAN_CORETIME_WESTEND_INDEXER: process.env.SUBSCAN_CORETIME_WESTEND_INDEXER || '', ROCOCO_CORETIME_DICT: process.env.ROCOCO_CORETIME_DICT || '', KUSAMA_CORETIME_DICT: process.env.KUSAMA_CORETIME_DICT || '', - SUBSCAN_CORETIME_WESTEND_DICT: - process.env.SUBSCAN_CORETIME_WESTEND_DICT || '', + SUBSCAN_CORETIME_WESTEND_DICT: process.env.SUBSCAN_CORETIME_WESTEND_DICT || '', WS_REGIONX_COCOS_CHAIN: process.env.WS_REGIONX_COCOS_CHAIN || '', diff --git a/src/apis/orders.ts b/src/apis/orders.ts index dd5ffc8f..be63e007 100644 --- a/src/apis/orders.ts +++ b/src/apis/orders.ts @@ -25,9 +25,7 @@ export const fetchUserContribution = async ( return fetchGraphql(API_COCOS_INDEXER, query); }; -export const fetchOrders = async ( - after: string | null -): Promise => { +export const fetchOrders = async (after: string | null): Promise => { const query = `{ orders(after: ${after}) { nodes { diff --git a/src/apis/sales.ts b/src/apis/sales.ts index f111dec1..592dc71f 100644 --- a/src/apis/sales.ts +++ b/src/apis/sales.ts @@ -3,9 +3,7 @@ import { fetchGraphql } from '@/utils/fetchGraphql'; import { API_CORETIME_INDEXER } from '@/consts'; import { ApiResponse, NetworkType } from '@/models'; -export const fetchBurnInfo = async ( - network: NetworkType -): Promise => { +export const fetchBurnInfo = async (network: NetworkType): Promise => { const query = `{ stats { nodes { diff --git a/src/chaindata/kusama.ts b/src/chaindata/kusama.ts index 129d782f..68028b6f 100644 --- a/src/chaindata/kusama.ts +++ b/src/chaindata/kusama.ts @@ -368,8 +368,7 @@ const prodParasKusama: ChainDetails[] = [ }, text: 'K-Laos', ui: { - color: - 'linear-gradient(158deg, rgba(226,157,0,1) 0%, rgba(234,55,203,1) 100%)', + color: 'linear-gradient(158deg, rgba(226,157,0,1) 0%, rgba(234,55,203,1) 100%)', logo: chainsLaosPNG, }, }, @@ -922,8 +921,7 @@ const prodParasKusama: ChainDetails[] = [ info: 'xode', paraId: 3344, providers: { - XodeCommunity: - 'wss://rpcnodea01.xode.net/n7yoxCmcIrCF6VziCcDmYTwL8R03a/rpc', + XodeCommunity: 'wss://rpcnodea01.xode.net/n7yoxCmcIrCF6VziCcDmYTwL8R03a/rpc', }, text: 'Xode', ui: { diff --git a/src/chaindata/rococo.ts b/src/chaindata/rococo.ts index 9d1e7aca..483303d8 100644 --- a/src/chaindata/rococo.ts +++ b/src/chaindata/rococo.ts @@ -637,8 +637,7 @@ const testParasRococo: ChainDetails[] = [ }, text: 'Stagex', ui: { - color: - 'linear-gradient(158deg, rgba(226,157,0,1) 0%, rgba(234,55,203,1) 100%)', + color: 'linear-gradient(158deg, rgba(226,157,0,1) 0%, rgba(234,55,203,1) 100%)', logo: chainsTotemSVG, }, }, @@ -673,8 +672,7 @@ const testParasRococo: ChainDetails[] = [ }, text: 'Tinkernet', ui: { - color: - 'linear-gradient(90deg, rgba(253,52,166,1) 0%, rgba(22,213,239,1) 100%)', + color: 'linear-gradient(90deg, rgba(253,52,166,1) 0%, rgba(22,213,239,1) 100%)', logo: chainsTinkerPNG, }, }, diff --git a/src/components/Accounts/TxHistory/index.tsx b/src/components/Accounts/TxHistory/index.tsx index a206f7dc..e49cb26f 100644 --- a/src/components/Accounts/TxHistory/index.tsx +++ b/src/components/Accounts/TxHistory/index.tsx @@ -26,11 +26,7 @@ interface TxHistoryModalProps extends DialogProps { account: Address; } -export const TxHistoryModal = ({ - open, - onClose, - account, -}: TxHistoryModalProps) => { +export const TxHistoryModal = ({ open, onClose, account }: TxHistoryModalProps) => { const theme = useTheme(); const { network } = useNetwork(); @@ -40,10 +36,7 @@ export const TxHistoryModal = ({ - + Transaction History diff --git a/src/components/Elements/Address/index.tsx b/src/components/Elements/Address/index.tsx index ec049795..dc1c1b20 100644 --- a/src/components/Elements/Address/index.tsx +++ b/src/components/Elements/Address/index.tsx @@ -13,13 +13,7 @@ interface AddressProps { center?: boolean; } -export const Address = ({ - value, - isShort, - isCopy, - size = 32, - center, -}: AddressProps) => { +export const Address = ({ value, isShort, isCopy, size = 32, center }: AddressProps) => { const { toastInfo } = useToast(); const onCopy = () => { diff --git a/src/components/Elements/Balance/index.tsx b/src/components/Elements/Balance/index.tsx index 152753af..781d1e23 100644 --- a/src/components/Elements/Balance/index.tsx +++ b/src/components/Elements/Balance/index.tsx @@ -85,9 +85,7 @@ export const Balance = ({ {items.map(({ label, value, symbol, decimals }, index) => ( - - {label} - + {label} { + } diff --git a/src/components/Elements/Cards/FeatureCard/index.tsx b/src/components/Elements/Cards/FeatureCard/index.tsx index c9c5d9bb..cfa4fe79 100644 --- a/src/components/Elements/Cards/FeatureCard/index.tsx +++ b/src/components/Elements/Cards/FeatureCard/index.tsx @@ -1,11 +1,4 @@ -import { - Button, - Card, - CardActions, - CardContent, - Typography, - useTheme, -} from '@mui/material'; +import { Button, Card, CardActions, CardContent, Typography, useTheme } from '@mui/material'; import Image, { StaticImageData } from 'next/image'; import { useRouter } from 'next/router'; import React from 'react'; @@ -20,13 +13,7 @@ interface FeatureCardProps { href: string; } -export const FeatureCard = ({ - title, - buttonText, - image, - enabled, - href, -}: FeatureCardProps) => { +export const FeatureCard = ({ title, buttonText, image, enabled, href }: FeatureCardProps) => { const { push, query } = useRouter(); const theme = useTheme(); diff --git a/src/components/Elements/Cards/SalePhaseCard/index.tsx b/src/components/Elements/Cards/SalePhaseCard/index.tsx index 46b14476..9c209883 100644 --- a/src/components/Elements/Cards/SalePhaseCard/index.tsx +++ b/src/components/Elements/Cards/SalePhaseCard/index.tsx @@ -1,10 +1,4 @@ -import { - Box, - CircularProgress, - Tooltip, - Typography, - useTheme, -} from '@mui/material'; +import { Box, CircularProgress, Tooltip, Typography, useTheme } from '@mui/material'; import { SalePhase } from '@/models'; @@ -14,12 +8,7 @@ interface SalePhaseProps { value: SalePhase; cyLabel?: string; } -export const SalePhaseCard = ({ - label, - loading, - value, - cyLabel, -}: SalePhaseProps) => { +export const SalePhaseCard = ({ label, loading, value, cyLabel }: SalePhaseProps) => { const theme = useTheme(); const tooltip = { @@ -27,15 +16,12 @@ export const SalePhaseCard = ({ 'During the interlude phase, renewals take place. Regular purchases cannot be made.', [SalePhase.Leadin]: 'During the leadin phase, the price decreases from the start price to the floor price.', - [SalePhase.Regular]: - 'During the fixed price phase, cores are sold for the floor price.', + [SalePhase.Regular]: 'During the fixed price phase, cores are sold for the floor price.', }; return ( - - {label} - + {label} {loading ? ( diff --git a/src/components/Elements/CountDown/index.tsx b/src/components/Elements/CountDown/index.tsx index e65f4c35..61f9ef9a 100644 --- a/src/components/Elements/CountDown/index.tsx +++ b/src/components/Elements/CountDown/index.tsx @@ -23,10 +23,8 @@ export const CountDown = ({ remainingTime }: CountDownProps) => { const [daysDuration, setDaysDuration] = useState(0); const getTimeSeconds = (time: number) => (minuteSeconds - time) | 0; - const getTimeMinutes = (time: number) => - ((time % hourSeconds) / minuteSeconds) | 0; - const getTimeHours = (time: number) => - ((time % daySeconds) / hourSeconds) | 0; + const getTimeMinutes = (time: number) => ((time % hourSeconds) / minuteSeconds) | 0; + const getTimeHours = (time: number) => ((time % daySeconds) / hourSeconds) | 0; const getTimeDays = (time: number) => (time / daySeconds) | 0; const renderTime = (dimension: string, time: number) => { return ( @@ -119,9 +117,7 @@ export const CountDown = ({ remainingTime }: CountDownProps) => { })} > {({ elapsedTime, color }) => ( - - {renderTime('seconds', getTimeSeconds(elapsedTime))} - + {renderTime('seconds', getTimeSeconds(elapsedTime))} )} diff --git a/src/components/Elements/InfoItem/index.tsx b/src/components/Elements/InfoItem/index.tsx index 1cedd28e..ed2f9eb7 100644 --- a/src/components/Elements/InfoItem/index.tsx +++ b/src/components/Elements/InfoItem/index.tsx @@ -8,9 +8,7 @@ export const InfoItem = ({ label, value }: ItemDetail) => { const theme = useTheme(); return ( - - {label} - + {label} { +export const AddressInput = ({ onChange, address, label }: AddressInputProps) => { const { state: { activeAccount }, } = useAccounts(); diff --git a/src/components/Elements/Inputs/AmountInput/index.tsx b/src/components/Elements/Inputs/AmountInput/index.tsx index 9b12f537..3095e996 100644 --- a/src/components/Elements/Inputs/AmountInput/index.tsx +++ b/src/components/Elements/Inputs/AmountInput/index.tsx @@ -9,12 +9,7 @@ interface AmountInputProps { // TODO: Fetch dot price and show how much is the currency amount worth. -export const AmountInput = ({ - currency, - title, - caption, - setAmount, -}: AmountInputProps) => { +export const AmountInput = ({ currency, title, caption, setAmount }: AmountInputProps) => { return ( <> @@ -28,9 +23,7 @@ export const AmountInput = ({ {currency} - ), + endAdornment: {currency}, style: { borderRadius: '1rem', textAlign: 'center', diff --git a/src/components/Elements/Inputs/FileInput/index.tsx b/src/components/Elements/Inputs/FileInput/index.tsx index 0b25c3dc..efba50b9 100644 --- a/src/components/Elements/Inputs/FileInput/index.tsx +++ b/src/components/Elements/Inputs/FileInput/index.tsx @@ -116,9 +116,7 @@ function InputFile({
{file.name}
-
{`(${file.size.toLocaleString()} bytes)`}
+
{`(${file.size.toLocaleString()} bytes)`}
)} diff --git a/src/components/Elements/Label/index.tsx b/src/components/Elements/Label/index.tsx index af435360..da29d700 100644 --- a/src/components/Elements/Label/index.tsx +++ b/src/components/Elements/Label/index.tsx @@ -12,10 +12,7 @@ export const Label = ({ text, color, width }: LabelProps) => { sx={{ borderRadius: '5px', padding: '0.5rem 1rem', - background: - color === 'success' - ? theme.palette.success.main - : theme.palette.primary.main, + background: color === 'success' ? theme.palette.success.main : theme.palette.primary.main, color: theme.palette.common.white, fontWeight: 400, width, diff --git a/src/components/Elements/Selectors/AssetSelector/index.tsx b/src/components/Elements/Selectors/AssetSelector/index.tsx index 640583c9..d8e165ee 100644 --- a/src/components/Elements/Selectors/AssetSelector/index.tsx +++ b/src/components/Elements/Selectors/AssetSelector/index.tsx @@ -11,11 +11,7 @@ interface AssetSelectorProps { symbol: string; } -export default function AssetSelector({ - asset, - setAsset, - symbol, -}: AssetSelectorProps) { +export default function AssetSelector({ asset, setAsset, symbol }: AssetSelectorProps) { const items = [ { value: AssetType.TOKEN, diff --git a/src/components/Elements/Selectors/FinalitySelector/index.tsx b/src/components/Elements/Selectors/FinalitySelector/index.tsx index 2b974e8e..4b1131f6 100644 --- a/src/components/Elements/Selectors/FinalitySelector/index.tsx +++ b/src/components/Elements/Selectors/FinalitySelector/index.tsx @@ -7,10 +7,7 @@ interface FinalitySelectorProps { setFinality: (_: FinalityType) => void; } -export const FinalitySelector = ({ - finality, - setFinality, -}: FinalitySelectorProps) => { +export const FinalitySelector = ({ finality, setFinality }: FinalitySelectorProps) => { return ( { />
- + Name: { +export const InterlaceModal = ({ open, onClose, regionMetadata }: InterlaceModalProps) => { const theme = useTheme(); const { state: { activeAccount, activeSigner }, @@ -59,47 +55,34 @@ export const InterlaceModal = ({ const [working, setWorking] = useState(false); const [position, setPosition] = useState(oneStart); - const newMask = - oneStart <= position + 1 - ? maskToBin(maskFromChunk(oneStart, position + 1)) - : ''; + const newMask = oneStart <= position + 1 ? maskToBin(maskFromChunk(oneStart, position + 1)) : ''; const onInterlace = async () => { if (!api || !activeAccount || !activeSigner) return; const mask = maskFromBin(newMask); - const txInterlace = api.tx.broker.interlace( - regionMetadata.region.getOnChainRegionId(), - mask - ); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txInterlace, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess('Successfully interlaced the region'); - onClose(); - fetchRegions(); - }, - fail: () => { - toastError('Failed to interlace the region'); - }, - error: (e) => { - toastError(`Failed to interlace the region ${e}`); - setWorking(false); - }, - } - ); + const txInterlace = api.tx.broker.interlace(regionMetadata.region.getOnChainRegionId(), mask); + submitExtrinsicWithFeeInfo(symbol, decimals, txInterlace, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Successfully interlaced the region'); + onClose(); + fetchRegions(); + }, + fail: () => { + toastError('Failed to interlace the region'); + }, + error: (e) => { + toastError(`Failed to interlace the region ${e}`); + setWorking(false); + }, + }); }; useEffect(() => { @@ -110,10 +93,7 @@ export const InterlaceModal = ({ - + Region Interlacing - Interlace your region into two new regions, each of which can be - assigned to a different task while both run on the same core. + Interlace your region into two new regions, each of which can be assigned to a different + task while both run on the same core.

- Select the percentage of core resources that will be allocated to - one of the newly created regions, while the rest will be allocated - to the other. + Select the percentage of core resources that will be allocated to one of the newly + created regions, while the rest will be allocated to the other.
@@ -156,11 +135,7 @@ export const InterlaceModal = ({ {activeBits > 1 && ( <> - + setPosition(Number(v))} valueLabelDisplay='on' valueLabelFormat={(v) => - `${(((v - oneStart + 1) / COREMASK_BIT_LEN) * 100).toFixed( - 2 - )}%` + `${(((v - oneStart + 1) / COREMASK_BIT_LEN) * 100).toFixed(2)}%` } className={styles.slider} /> @@ -216,11 +189,7 @@ const CoremaskCircularProgress = ({ oneStart, oneEnd, }: CoremaskCircularProgressProps) => { - const getCircularProgressValue = ( - value: number, - minValue: number, - maxValue: number - ) => { + const getCircularProgressValue = (value: number, minValue: number, maxValue: number) => { return ((value - minValue) / (maxValue - minValue)) * 100; }; diff --git a/src/components/Regions/Modals/Partition/index.tsx b/src/components/Regions/Modals/Partition/index.tsx index 2b328a0c..b9e027d3 100644 --- a/src/components/Regions/Modals/Partition/index.tsx +++ b/src/components/Regions/Modals/Partition/index.tsx @@ -21,13 +21,7 @@ import { useAccounts } from '@/contexts/account'; import { useCoretimeApi } from '@/contexts/apis'; import { useRegions } from '@/contexts/regions'; import { useToast } from '@/contexts/toast'; -import { - DAY, - HOUR, - MINUTE, - RegionMetadata, - RELAY_CHAIN_BLOCK_TIME, -} from '@/models'; +import { DAY, HOUR, MINUTE, RegionMetadata, RELAY_CHAIN_BLOCK_TIME } from '@/models'; import styles from './index.module.scss'; @@ -36,11 +30,7 @@ interface PartitionModalProps extends DialogProps { regionMetadata: RegionMetadata; } -export const PartitionModal = ({ - open, - onClose, - regionMetadata, -}: PartitionModalProps) => { +export const PartitionModal = ({ open, onClose, regionMetadata }: PartitionModalProps) => { const timeUnits = [ { label: 'Minutes', @@ -84,8 +74,7 @@ export const PartitionModal = ({ const maxSteps = Math.floor(duration / unit) - 1; useEffect(() => { - const diff = - regionMetadata.region.getEnd() - regionMetadata.region.getBegin(); + const diff = regionMetadata.region.getEnd() - regionMetadata.region.getBegin(); setDuration(diff * timeslicePeriod * RELAY_CHAIN_BLOCK_TIME); }, [timeslicePeriod, regionMetadata.region]); @@ -103,43 +92,33 @@ export const PartitionModal = ({ pivotInTimeslice ); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txPartition, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess('Successfully partitioned the region'); - onClose(); - fetchRegions(); - }, - fail: () => { - toastError('Failed to partition the region'); - }, - error: (e) => { - toastError(`Failed to partition the region ${e}`); - setWorking(false); - }, - } - ); + submitExtrinsicWithFeeInfo(symbol, decimals, txPartition, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Successfully partitioned the region'); + onClose(); + fetchRegions(); + }, + fail: () => { + toastError('Failed to partition the region'); + }, + error: (e) => { + toastError(`Failed to partition the region ${e}`); + setWorking(false); + }, + }); }; return ( - + Region Partitioning - Split your region into two new ones with different start and end - points. They will be divided at the selected pivot point. + Split your region into two new ones with different start and end points. They will be + divided at the selected pivot point. @@ -168,11 +147,7 @@ export const PartitionModal = ({ {timeUnits.map(({ label }, index) => ( setUnitIdx(index)} > {label} @@ -189,9 +164,7 @@ export const PartitionModal = ({ onChange={(_e, v) => setPivot(v as number)} marks valueLabelDisplay='on' - valueLabelFormat={(v) => - `${v} ${timeUnits[unitIdx].strUnit}${v > 1 ? 's' : ''}` - } + valueLabelFormat={(v) => `${v} ${timeUnits[unitIdx].strUnit}${v > 1 ? 's' : ''}`} size='medium' className={styles.timeSlider} /> @@ -202,11 +175,7 @@ export const PartitionModal = ({ - + ); diff --git a/src/components/Regions/Modals/Pooling/index.tsx b/src/components/Regions/Modals/Pooling/index.tsx index 018aa160..845c97c4 100644 --- a/src/components/Regions/Modals/Pooling/index.tsx +++ b/src/components/Regions/Modals/Pooling/index.tsx @@ -33,11 +33,7 @@ interface PoolingModalProps extends DialogProps { regionMetadata: RegionMetadata; } -export const PoolingModal = ({ - open, - onClose, - regionMetadata, -}: PoolingModalProps) => { +export const PoolingModal = ({ open, onClose, regionMetadata }: PoolingModalProps) => { const theme = useTheme(); const { state: { activeAccount, activeSigner }, @@ -64,35 +60,26 @@ export const PoolingModal = ({ finality ); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txPooling, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess( - 'Successfully contributed to the instantaneous region pool' - ); - onClose(); - fetchRegions(); - }, - fail: () => { - toastError('Failed to contribute to the instantaneous region pool'); - }, - error: () => { - toastError('Failed to contribute to the instantaneous region pool'); - setWorking(false); - }, - } - ); + submitExtrinsicWithFeeInfo(symbol, decimals, txPooling, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Successfully contributed to the instantaneous region pool'); + onClose(); + fetchRegions(); + }, + fail: () => { + toastError('Failed to contribute to the instantaneous region pool'); + }, + error: () => { + toastError('Failed to contribute to the instantaneous region pool'); + setWorking(false); + }, + }); }; useEffect(() => { @@ -106,10 +93,7 @@ export const PoolingModal = ({ - + Task Pooling - You can contribute your region to the instantaneous coretime pool to - earn rewards. + You can contribute your region to the instantaneous coretime pool to earn rewards. - + Contribution options @@ -155,9 +135,7 @@ export const PoolingModal = ({ diff --git a/src/components/Regions/Modals/Price/index.tsx b/src/components/Regions/Modals/Price/index.tsx index 82289344..50e776c3 100644 --- a/src/components/Regions/Modals/Price/index.tsx +++ b/src/components/Regions/Modals/Price/index.tsx @@ -31,26 +31,16 @@ export const PriceModal = ({ open, onClose }: PriceModalProps) => { - + Price Analysis {currentPhase === SalePhase.Interlude ? ( {"Sale hasn't started yet."} - + Sale starts in: - + ) : ( @@ -62,11 +52,7 @@ export const PriceModal = ({ open, onClose }: PriceModalProps) => { - + diff --git a/src/components/Regions/Modals/Purchase/index.tsx b/src/components/Regions/Modals/Purchase/index.tsx index 81ad64c0..564a792e 100644 --- a/src/components/Regions/Modals/Purchase/index.tsx +++ b/src/components/Regions/Modals/Purchase/index.tsx @@ -1,11 +1,5 @@ import { LoadingButton } from '@mui/lab'; -import { - Button, - Dialog, - DialogActions, - DialogContent, - DialogProps, -} from '@mui/material'; +import { Button, Dialog, DialogActions, DialogContent, DialogProps } from '@mui/material'; import { BN } from '@polkadot/util'; import { useState } from 'react'; @@ -25,11 +19,7 @@ interface PurchaseModalProps extends DialogProps { listing: Listing; } -export const PurchaseModal = ({ - open, - onClose, - listing, -}: PurchaseModalProps) => { +export const PurchaseModal = ({ open, onClose, listing }: PurchaseModalProps) => { const { state: { activeAccount, activeSigner }, } = useAccounts(); @@ -57,9 +47,7 @@ export const PurchaseModal = ({ return; } - const regionDuration = new BN( - listing.region.getEnd() - listing.region.getBegin() - ); + const regionDuration = new BN(listing.region.getEnd() - listing.region.getBegin()); const maxPrice = listing.timeslicePrice.mul(regionDuration); const txPurchase = regionXApi.tx.market.purchaseRegion( @@ -67,40 +55,31 @@ export const PurchaseModal = ({ maxPrice.toString() ); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txPurchase, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess('Successfully purchased the region'); - fetchMarket(); - fetchRegions(); - onClose(); - }, - fail: () => { - toastError('Failed to purchase the region'); - }, - error: (e) => { - toastError( - `Failed to purchase the region. Error: ${ - e.errorMessage === 'Error' - ? 'Please check your balance.' - : e.errorMessage - }` - ); - setWorking(false); - }, - } - ); + submitExtrinsicWithFeeInfo(symbol, decimals, txPurchase, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Successfully purchased the region'); + fetchMarket(); + fetchRegions(); + onClose(); + }, + fail: () => { + toastError('Failed to purchase the region'); + }, + error: (e) => { + toastError( + `Failed to purchase the region. Error: ${ + e.errorMessage === 'Error' ? 'Please check your balance.' : e.errorMessage + }` + ); + setWorking(false); + }, + }); }; return ( @@ -120,11 +99,7 @@ export const PurchaseModal = ({ - purchaseRegion()} - variant='contained' - loading={working} - > + purchaseRegion()} variant='contained' loading={working}> Purchase diff --git a/src/components/Regions/Modals/PurchaseHistory/index.tsx b/src/components/Regions/Modals/PurchaseHistory/index.tsx index 4639805d..7b19b5fa 100644 --- a/src/components/Regions/Modals/PurchaseHistory/index.tsx +++ b/src/components/Regions/Modals/PurchaseHistory/index.tsx @@ -26,10 +26,7 @@ interface PurchaseHistoryModalProps extends DialogProps { onClose: () => void; } -export const PurchaseHistoryModal = ({ - open, - onClose, -}: PurchaseHistoryModalProps) => { +export const PurchaseHistoryModal = ({ open, onClose }: PurchaseHistoryModalProps) => { const theme = useTheme(); const { network } = useNetwork(); const { @@ -38,26 +35,14 @@ export const PurchaseHistoryModal = ({ const { loading, data, isError } = usePurchaseHistory(network, regionBegin); return ( - + - + Purchase History - - Get an insight into all purchases and renewals made during the - current bulk period. + + Get an insight into all purchases and renewals made during the current bulk period. {loading || isError ? ( diff --git a/src/components/Regions/Modals/Sell/index.tsx b/src/components/Regions/Modals/Sell/index.tsx index 584ed3b2..e3b1c3db 100644 --- a/src/components/Regions/Modals/Sell/index.tsx +++ b/src/components/Regions/Modals/Sell/index.tsx @@ -14,11 +14,7 @@ import { useState } from 'react'; import { useSubmitExtrinsic } from '@/hooks/submitExtrinsic'; import theme from '@/utils/muiTheme'; -import { - AddressInput, - AmountInput, - ProgressButton, -} from '@/components/Elements'; +import { AddressInput, AmountInput, ProgressButton } from '@/components/Elements'; import { RegionOverview } from '@/components/Regions'; import { useAccounts } from '@/contexts/account'; @@ -36,11 +32,7 @@ interface SellModalProps extends DialogProps { regionMetadata: RegionMetadata; } -export const SellModal = ({ - open, - onClose, - regionMetadata, -}: SellModalProps) => { +export const SellModal = ({ open, onClose, regionMetadata }: SellModalProps) => { const { state: { activeAccount, activeSigner }, } = useAccounts(); @@ -62,9 +54,7 @@ export const SellModal = ({ const listOnSale = async () => { if (!activeAccount || !activeSigner || !regionXApi || !isRegionXReady) { - toastWarning( - 'Please connect your wallet and check the network connection.' - ); + toastWarning('Please connect your wallet and check the network connection.'); return; } @@ -113,9 +103,7 @@ export const SellModal = ({ error: (e) => { toastError( `Failed to list the region. Error: ${ - e.errorMessage === 'Error' - ? 'Please check your balance' - : e.errorMessage + e.errorMessage === 'Error' ? 'Please check your balance' : e.errorMessage }` ); setWorking(false); @@ -127,10 +115,7 @@ export const SellModal = ({ return ( - + List on Market
- +
@@ -169,11 +150,7 @@ export const SellModal = ({ - +
); diff --git a/src/components/Regions/Modals/TaskAssign/index.tsx b/src/components/Regions/Modals/TaskAssign/index.tsx index e7af226d..a8052d15 100644 --- a/src/components/Regions/Modals/TaskAssign/index.tsx +++ b/src/components/Regions/Modals/TaskAssign/index.tsx @@ -66,12 +66,7 @@ const TaskItem = ({ name, id, editable = false }: TaskItemProps) => { }; return ( - + {editing ? ( { ); }; -export const TaskAssignModal = ({ - open, - onClose, - regionMetadata, -}: TaskAssignModalProps) => { +export const TaskAssignModal = ({ open, onClose, regionMetadata }: TaskAssignModalProps) => { const theme = useTheme(); const { @@ -141,33 +132,26 @@ export const TaskAssignModal = ({ finality ); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txAssign, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess('Successfully assigned a task'); - onClose(); - fetchRegions(); - }, - fail: () => { - toastError('Failed to assign a task'); - }, - error: (e) => { - toastError(`Failed to assign a task. ${e}`); - setWorking(false); - }, - } - ); + submitExtrinsicWithFeeInfo(symbol, decimals, txAssign, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Successfully assigned a task'); + onClose(); + fetchRegions(); + }, + fail: () => { + toastError('Failed to assign a task'); + }, + error: (e) => { + toastError(`Failed to assign a task. ${e}`); + setWorking(false); + }, + }); }; useEffect(() => { @@ -181,36 +165,22 @@ export const TaskAssignModal = ({ return ( <> - {taskModalOpen && ( - openTaskModal(false)} /> - )} + {taskModalOpen && openTaskModal(false)} />} - + Task Assignment - + Here you can assign your region to a specific task - - + + Tasks - {taskModalOpen && ( - openTaskModal(false)} /> - )} + {taskModalOpen && openTaskModal(false)} />} ); }; diff --git a/src/components/Regions/Modals/Transfer/index.tsx b/src/components/Regions/Modals/Transfer/index.tsx index dded524e..c75ff363 100644 --- a/src/components/Regions/Modals/Transfer/index.tsx +++ b/src/components/Regions/Modals/Transfer/index.tsx @@ -34,11 +34,7 @@ interface TransferModalProps extends DialogProps { regionMetadata: RegionMetadata; } -export const TransferModal = ({ - open, - onClose, - regionMetadata, -}: TransferModalProps) => { +export const TransferModal = ({ open, onClose, regionMetadata }: TransferModalProps) => { const theme = useTheme(); const { @@ -141,33 +137,20 @@ export const TransferModal = ({ - + Transfer Region - + Here you can transfer your region to a new owner - + Transfer to - setNewOwner(e)} - /> + setNewOwner(e)} /> @@ -176,11 +159,7 @@ export const TransferModal = ({ Cancel - + ); diff --git a/src/components/Regions/RegionMetaCard/index.tsx b/src/components/Regions/RegionMetaCard/index.tsx index 18f94d79..8d8929b8 100644 --- a/src/components/Regions/RegionMetaCard/index.tsx +++ b/src/components/Regions/RegionMetaCard/index.tsx @@ -81,8 +81,7 @@ const RegionCardInner = ({ const { tasks } = useTasks(); const formatDuration = humanizer({ units: ['w', 'd', 'h'], round: true }); - const { region, taskId, location, currentUsage, consumed, coreOccupancy } = - regionMetadata; + const { region, taskId, location, currentUsage, consumed, coreOccupancy } = regionMetadata; const theme = useTheme(); const [isEdit, setEdit] = useState(false); @@ -105,16 +104,8 @@ const RegionCardInner = ({ } const fetchTimestamps = async () => { - const begin = await timesliceToTimestamp( - api, - region.getBegin(), - timeslicePeriod - ); - const end = await timesliceToTimestamp( - api, - region.getEnd(), - timeslicePeriod - ); + const begin = await timesliceToTimestamp(api, region.getBegin(), timeslicePeriod); + const end = await timesliceToTimestamp(api, region.getEnd(), timeslicePeriod); setBeginTimestamp(begin); setEndTimestamp(end); @@ -198,11 +189,7 @@ const RegionCardInner = ({ }} > {editable && isEdit ? ( - setName(e.target.value)} - size='small' - /> + setName(e.target.value)} size='small' /> ) : ( {regionMetadata.name} )} @@ -234,12 +221,8 @@ const RegionCardInner = ({ }} > {`Core Index: #${region.getCore()}`} - - Begin: {getRelativeTimeString(beginTimestamp)} - - - End: {getRelativeTimeString(endTimestamp)} - + Begin: {getRelativeTimeString(beginTimestamp)} + End: {getRelativeTimeString(endTimestamp)} @@ -276,10 +255,7 @@ const RegionCardInner = ({ }} > {progress.map(({ label, value, color }, index) => ( - + { return; } const fetchTimestamps = async () => { - const begin = await timesliceToTimestamp( - relayApi, - region.getBegin(), - timeslicePeriod - ); - const end = await timesliceToTimestamp( - relayApi, - region.getEnd(), - timeslicePeriod - ); + const begin = await timesliceToTimestamp(relayApi, region.getBegin(), timeslicePeriod); + const end = await timesliceToTimestamp(relayApi, region.getEnd(), timeslicePeriod); setBeginTimestamp(begin); setEndTimestamp(end); @@ -62,10 +54,7 @@ export const RegionOverview = ({ regionMetadata }: RegionOverviewProps) => { > {regionMetadata.name} - + {`Duration: ${formatDuration(endTimestamp - beginTimestamp)}`} diff --git a/src/components/Sales/SaleDetails/index.tsx b/src/components/Sales/SaleDetails/index.tsx index 6a54b894..d7e35d6c 100644 --- a/src/components/Sales/SaleDetails/index.tsx +++ b/src/components/Sales/SaleDetails/index.tsx @@ -32,11 +32,7 @@ interface SaleDetailsModalProps extends DialogProps { info: SalesHistoryItem; } -export const SaleDetailsModal = ({ - open, - onClose, - info, -}: SaleDetailsModalProps) => { +export const SaleDetailsModal = ({ open, onClose, info }: SaleDetailsModalProps) => { const theme = useTheme(); const { network } = useNetwork(); const { @@ -57,18 +53,10 @@ export const SaleDetailsModal = ({ const { loading, data, isError } = useSaleDetails(network, saleCycle); return ( - + - + Coretime Sale#{saleCycle} @@ -86,21 +74,11 @@ export const SaleDetailsModal = ({ ) : ( - - + + {endTimestamp - ? `${getTimeStringShort( - startTimestamp - )} ~ ${getTimeStringShort(endTimestamp)}` + ? `${getTimeStringShort(startTimestamp)} ~ ${getTimeStringShort(endTimestamp)}` : getTimeStringShort(startTimestamp)} { const startPrice = saleInfo.leadinLength === 0 ? 0 - : planckBnToUnit( - getCorePriceAt(saleStart, saleInfo).toString(), - decimals - ); + : planckBnToUnit(getCorePriceAt(saleStart, saleInfo).toString(), decimals); const curPrice = - currentPrice === undefined - ? 0 - : planckBnToUnit(currentPrice.toString(), decimals); + currentPrice === undefined ? 0 : planckBnToUnit(currentPrice.toString(), decimals); const floorPrice = planckBnToUnit(saleInfo.price.toString(), decimals); const data = [ @@ -137,8 +128,7 @@ export const SalePriceChart = () => { intersect: true, shared: false, x: { - formatter: (v: number) => - v === currentTimestamp ? 'Now' : getTimeStringShort(v), + formatter: (v: number) => (v === currentTimestamp ? 'Now' : getTimeStringShort(v)), }, }, grid: { @@ -157,21 +147,15 @@ export const SalePriceChart = () => { const series = [ { name: 'Interlude Period', - data: data.map(({ phase, value }) => - phase === SalePhase.Interlude ? value : null - ), + data: data.map(({ phase, value }) => (phase === SalePhase.Interlude ? value : null)), }, { name: 'Leadin Period', - data: data.map(({ phase, value }) => - phase === SalePhase.Leadin ? value : null - ), + data: data.map(({ phase, value }) => (phase === SalePhase.Leadin ? value : null)), }, { name: 'Fixed Price Period', - data: data.map(({ phase, value }) => - phase === SalePhase.Regular ? value : null - ), + data: data.map(({ phase, value }) => (phase === SalePhase.Regular ? value : null)), }, ]; @@ -180,12 +164,6 @@ export const SalePriceChart = () => { ) : ( - + ); }; diff --git a/src/components/Tables/OrderProcessorTable/index.tsx b/src/components/Tables/OrderProcessorTable/index.tsx index f07d6742..8e3d4e76 100644 --- a/src/components/Tables/OrderProcessorTable/index.tsx +++ b/src/components/Tables/OrderProcessorTable/index.tsx @@ -13,11 +13,7 @@ import { } from '@mui/material'; import { useState } from 'react'; -import { - getBalanceString, - getRelativeTimeString, - getTimeStringLong, -} from '@/utils/functions'; +import { getBalanceString, getRelativeTimeString, getTimeStringLong } from '@/utils/functions'; import { Address, Link } from '@/components/Elements'; import { OrderDetailsModal } from '@/components/Orders'; @@ -75,50 +71,40 @@ export const OrderProcessorTable = ({ data }: OrderProcessorTableProps) => { {(rowsPerPage > 0 - ? data.slice( - page * rowsPerPage, - page * rowsPerPage + rowsPerPage - ) + ? data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : data - ).map( - ( - { orderId, height, extrinsicId, account, reward, timestamp }, - index - ) => ( - - - - - - {height}-{extrinsicId} - - - -
- - - - {getBalanceString(reward.toString(), decimals, symbol)} - - - -

{getRelativeTimeString(timestamp)}

-
-
- - ) - )} + ).map(({ orderId, height, extrinsicId, account, reward, timestamp }, index) => ( + + + + + + {height}-{extrinsicId} + + + +
+ + + + {getBalanceString(reward.toString(), decimals, symbol)} + + + +

{getRelativeTimeString(timestamp)}

+
+
+ + ))} @@ -157,11 +143,7 @@ export const OrderProcessorTable = ({ data }: OrderProcessorTableProps) => { {activeOrderId !== null ? ( - setActiveOrderId(null)} - orderId={activeOrderId} - /> + setActiveOrderId(null)} orderId={activeOrderId} /> ) : ( <> )} diff --git a/src/components/Tables/ParachainTable/index.tsx b/src/components/Tables/ParachainTable/index.tsx index 25cc0f76..0f281768 100644 --- a/src/components/Tables/ParachainTable/index.tsx +++ b/src/components/Tables/ParachainTable/index.tsx @@ -124,9 +124,7 @@ export const ParachainTable = ({ { let newDir: Order = direction === 'asc' ? 'desc' : 'asc'; @@ -151,17 +149,12 @@ export const ParachainTable = ({ {(rowsPerPage > 0 - ? parachains.slice( - page * rowsPerPage, - page * rowsPerPage + rowsPerPage - ) + ? parachains.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : parachains ).map(({ id, name, state, watching, logo, homepage }, index) => ( - - {id} - + {id} @@ -207,29 +200,21 @@ export const ParachainTable = ({ {state === ParaState.RESERVED ? ( - onRegister(id)}> - Register - + onRegister(id)}>Register ) : state === ParaState.ONDEMAND_PARACHAIN ? ( onUpgrade(id)}> Upgrade(Buy Coretime) ) : state === ParaState.IDLE_PARA ? ( - - Buy Coretime - + Buy Coretime ) : state === ParaState.ACTIVE_RENEWABLE_PARA ? ( - onRenew(id)}> - Renew Coretime - + onRenew(id)}>Renew Coretime ) : ( No action required )} - onWatch(id, watching ? false : true)} - > + onWatch(id, watching ? false : true)}> {watching ? ( ) : ( diff --git a/src/components/Tables/PurchaseHistoryTable/index.tsx b/src/components/Tables/PurchaseHistoryTable/index.tsx index 7f069264..0758b2c7 100644 --- a/src/components/Tables/PurchaseHistoryTable/index.tsx +++ b/src/components/Tables/PurchaseHistoryTable/index.tsx @@ -13,11 +13,7 @@ import { } from '@mui/material'; import { useState } from 'react'; -import { - getBalanceString, - getRelativeTimeString, - getTimeStringLong, -} from '@/utils/functions'; +import { getBalanceString, getRelativeTimeString, getTimeStringLong } from '@/utils/functions'; import { Address, Link } from '@/components/Elements'; @@ -77,17 +73,7 @@ export const PurchaseHistoryTable = ({ data }: PurchaseHistoryTableProps) => { ? data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : data ).map( - ( - { - address, - core, - extrinsicId: extrinsic_index, - timestamp, - price, - type, - }, - index - ) => ( + ({ address, core, extrinsicId: extrinsic_index, timestamp, price, type }, index) => ( { color: theme.palette.primary.main, }} onClick={() => - window.open( - `${SUSBCAN_CORETIME_URL[network]}/account/${address}`, - '_blank' - ) + window.open(`${SUSBCAN_CORETIME_URL[network]}/account/${address}`, '_blank') } >
diff --git a/src/components/Tables/SalesHistoryTable/index.tsx b/src/components/Tables/SalesHistoryTable/index.tsx index 446c23b0..c9b01022 100644 --- a/src/components/Tables/SalesHistoryTable/index.tsx +++ b/src/components/Tables/SalesHistoryTable/index.tsx @@ -74,19 +74,13 @@ export const SalesHistoryTable = ({ data }: SalesHistoryTableProps) => { {info.saleCycle} - - {info.regionBegin} - - - {info.regionEnd} - + {info.regionBegin} + {info.regionEnd} {getTimeStringLong(info.startTimestamp)} - {info.endTimestamp - ? getTimeStringLong(info.endTimestamp) - : 'Not yet ended'} + {info.endTimestamp ? getTimeStringLong(info.endTimestamp) : 'Not yet ended'} ))} diff --git a/src/components/Tables/TxHistoryTable/index.tsx b/src/components/Tables/TxHistoryTable/index.tsx index 160727a6..951b6d11 100644 --- a/src/components/Tables/TxHistoryTable/index.tsx +++ b/src/components/Tables/TxHistoryTable/index.tsx @@ -64,32 +64,24 @@ export const TxHistoryTable = ({ data }: TxHistoryTableProps) => { {(rowsPerPage > 0 ? data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : data - ).map( - ({ module, call, extrinsicId, success, timestamp }, index) => ( - - - - {extrinsicId} - - - {module} - {call} - - {success ? ( - - ) : ( - - )} - - - {getRelativeTimeString(timestamp)} - - - ) - )} + ).map(({ module, call, extrinsicId, success, timestamp }, index) => ( + + + + {extrinsicId} + + + {module} + {call} + + {success ? : } + + {getRelativeTimeString(timestamp)} + + ))} diff --git a/src/components/Transfer/common.ts b/src/components/Transfer/common.ts index 6c34a481..78435de1 100644 --- a/src/components/Transfer/common.ts +++ b/src/components/Transfer/common.ts @@ -1,14 +1,9 @@ import { AssetType, ChainType } from '@/models'; -export const assetType = ( - originChain: ChainType, - destinationChain: ChainType -): AssetType => { +export const assetType = (originChain: ChainType, destinationChain: ChainType): AssetType => { if ( - (originChain === ChainType.CORETIME && - destinationChain === ChainType.REGIONX) || - (originChain === ChainType.REGIONX && - destinationChain === ChainType.CORETIME) + (originChain === ChainType.CORETIME && destinationChain === ChainType.REGIONX) || + (originChain === ChainType.REGIONX && destinationChain === ChainType.CORETIME) ) return AssetType.REGION; else return AssetType.TOKEN; diff --git a/src/components/Transfer/contexts/transferState.tsx b/src/components/Transfer/contexts/transferState.tsx index de519022..82b70fdb 100644 --- a/src/components/Transfer/contexts/transferState.tsx +++ b/src/components/Transfer/contexts/transferState.tsx @@ -1,10 +1,4 @@ -import { - createContext, - ReactNode, - useContext, - useEffect, - useState, -} from 'react'; +import { createContext, ReactNode, useContext, useEffect, useState } from 'react'; import { useRegions } from '@/contexts/regions'; import { ChainType, RegionLocation, RegionMetadata } from '@/models'; @@ -37,33 +31,19 @@ const defaultTasksData: TransferState = { const TransferStateContext = createContext(defaultTasksData); -export const TransferStateProvider = ({ - children, -}: { - children: ReactNode; -}) => { +export const TransferStateProvider = ({ children }: { children: ReactNode }) => { const { regions } = useRegions(); const [originChain, setOriginChain] = useState(ChainType.RELAY); - const [destinationChain, setDestinationChain] = useState( - ChainType.CORETIME - ); - const [selectedRegion, setSelectedRegion] = useState( - null - ); - const [filteredRegions, setFilteredRegions] = useState>( - [] - ); + const [destinationChain, setDestinationChain] = useState(ChainType.CORETIME); + const [selectedRegion, setSelectedRegion] = useState(null); + const [filteredRegions, setFilteredRegions] = useState>([]); useEffect(() => { if (originChain === ChainType.CORETIME) { - setFilteredRegions( - regions.filter((r) => r.location === RegionLocation.CORETIME_CHAIN) - ); + setFilteredRegions(regions.filter((r) => r.location === RegionLocation.CORETIME_CHAIN)); } else if (originChain === ChainType.REGIONX) { - setFilteredRegions( - regions.filter((r) => r.location === RegionLocation.REGIONX_CHAIN) - ); + setFilteredRegions(regions.filter((r) => r.location === RegionLocation.REGIONX_CHAIN)); } else { setFilteredRegions([]); } diff --git a/src/components/Transfer/hooks/useTransferHandlers.ts b/src/components/Transfer/hooks/useTransferHandlers.ts index 55bd0aca..94b0060c 100644 --- a/src/components/Transfer/hooks/useTransferHandlers.ts +++ b/src/components/Transfer/hooks/useTransferHandlers.ts @@ -9,10 +9,7 @@ import { transferTokensFromRelayToCoretime, transferTokensFromRelayToRegionX, } from '@/utils/transfers/crossChain'; -import { - transferNativeToken, - transferRegionOnCoretimeChain, -} from '@/utils/transfers/native'; +import { transferNativeToken, transferRegionOnCoretimeChain } from '@/utils/transfers/native'; import { useAccounts } from '@/contexts/account'; import { useCoretimeApi, useRegionXApi, useRelayApi } from '@/contexts/apis'; @@ -34,11 +31,7 @@ export const useTransferHandlers = () => { state: { api: regionXApi, isApiReady: isRegionXReady }, } = useRegionXApi(); const { - state: { - api: relayApi, - isApiReady: isRelayReady, - decimals: relayTokenDecimals, - }, + state: { api: relayApi, isApiReady: isRelayReady, decimals: relayTokenDecimals }, } = useRelayApi(); const { fetchRegions } = useRegions(); @@ -114,25 +107,13 @@ export const useTransferHandlers = () => { ); } else { let transferFunction: any; - if ( - originChain === ChainType.CORETIME && - destinationChain === ChainType.RELAY - ) { + if (originChain === ChainType.CORETIME && destinationChain === ChainType.RELAY) { transferFunction = transferTokensFromCoretimeToRelay; - } else if ( - originChain === ChainType.REGIONX && - destinationChain === ChainType.RELAY - ) { + } else if (originChain === ChainType.REGIONX && destinationChain === ChainType.RELAY) { transferFunction = transferTokensFromRegionXToRelay; - } else if ( - originChain === ChainType.RELAY && - destinationChain === ChainType.CORETIME - ) { + } else if (originChain === ChainType.RELAY && destinationChain === ChainType.CORETIME) { transferFunction = transferTokensFromRelayToCoretime; - } else if ( - originChain === ChainType.RELAY && - destinationChain === ChainType.REGIONX - ) { + } else if (originChain === ChainType.RELAY && destinationChain === ChainType.REGIONX) { transferFunction = transferTokensFromRelayToRegionX; } else { toastWarning('Currently not supported'); @@ -149,19 +130,11 @@ export const useTransferHandlers = () => { defaultHandler() ); - if ( - originChain === ChainType.CORETIME && - coretimeApi && - isCoretimeReady - ) { + if (originChain === ChainType.CORETIME && coretimeApi && isCoretimeReady) { transfer(coretimeApi); } else if (originChain === ChainType.RELAY && relayApi && isRelayReady) { transfer(relayApi); - } else if ( - originChain === ChainType.REGIONX && - regionXApi && - isRegionXReady - ) { + } else if (originChain === ChainType.REGIONX && regionXApi && isRegionXReady) { transfer(regionXApi); } } @@ -191,10 +164,7 @@ export const useTransferHandlers = () => { newOwner ?? activeAccount.address, defaultHandler(true) ); - } else if ( - originChain === ChainType.CORETIME && - destinationChain === ChainType.REGIONX - ) { + } else if (originChain === ChainType.CORETIME && destinationChain === ChainType.REGIONX) { if (!(coretimeApi && isCoretimeReady)) return; await coretimeToRegionXTransfer( coretimeApi, @@ -203,10 +173,7 @@ export const useTransferHandlers = () => { receiverKeypair.pairs[0].publicKey, defaultHandler(true) ); - } else if ( - originChain === ChainType.REGIONX && - destinationChain === ChainType.CORETIME - ) { + } else if (originChain === ChainType.REGIONX && destinationChain === ChainType.CORETIME) { if (!(regionXApi && isRegionXReady)) return; coretimeFromRegionXTransfer( regionXApi, diff --git a/src/components/Transfer/transferActions.tsx b/src/components/Transfer/transferActions.tsx index 255f5f07..9c6cca38 100644 --- a/src/components/Transfer/transferActions.tsx +++ b/src/components/Transfer/transferActions.tsx @@ -19,14 +19,8 @@ import { useTransferState } from './contexts/transferState'; import { useTransferHandlers } from './hooks/useTransferHandlers'; const TransferActions = () => { - const { - transferAmount, - handleTransfer, - working, - newOwner, - setNewOwner, - setTransferAmount, - } = useTransferHandlers(); + const { transferAmount, handleTransfer, working, newOwner, setNewOwner, setTransferAmount } = + useTransferHandlers(); const { state: { ed: coretimeChainED }, @@ -72,8 +66,7 @@ const TransferActions = () => { (originChain === ChainType.REGIONX && // ED is not really relevant since rc asset is not the native asset. balance.rxRcCurrencyBalance < _transferAmount) || - (originChain === ChainType.RELAY && - balance.relay - relayChainED < _transferAmount) + (originChain === ChainType.RELAY && balance.relay - relayChainED < _transferAmount) ) { toastWarning('Insufficient balance'); return; @@ -95,11 +88,7 @@ const TransferActions = () => { }} > - + {assetType(originChain, destinationChain) === AssetType.TOKEN && originChain !== ChainType.NONE && @@ -133,11 +122,7 @@ const TransferActions = () => { > < Home - + ); diff --git a/src/components/Transfer/transferForm.tsx b/src/components/Transfer/transferForm.tsx index ffa1fa9b..2da8d073 100644 --- a/src/components/Transfer/transferForm.tsx +++ b/src/components/Transfer/transferForm.tsx @@ -40,9 +40,7 @@ const TransferForm = () => { > {/* Origin Chain */} - + Origin chain: @@ -61,15 +59,10 @@ const TransferForm = () => { {/* Destination Chain */} - + Destination chain: - + {/* Region Selector */} @@ -81,9 +74,7 @@ const TransferForm = () => { - setSelectedRegion(filteredRegions[indx]) - } + handleRegionChange={(indx) => setSelectedRegion(filteredRegions[indx])} /> )} diff --git a/src/components/Transfer/transferHeader.tsx b/src/components/Transfer/transferHeader.tsx index 6ebcaa77..7b4a5690 100644 --- a/src/components/Transfer/transferHeader.tsx +++ b/src/components/Transfer/transferHeader.tsx @@ -8,16 +8,10 @@ const TransferHeader = () => { return ( - + Cross-Chain Transfer - + Cross-chain transfer regions diff --git a/src/consts/index.ts b/src/consts/index.ts index 5f8c66d7..2581aae8 100644 --- a/src/consts/index.ts +++ b/src/consts/index.ts @@ -36,12 +36,9 @@ export const WS_ROCOCO_RELAY_CHAIN = process.env.WS_ROCOCO_RELAY_CHAIN ?? ''; export const WS_KUSAMA_RELAY_CHAIN = process.env.WS_KUSAMA_RELAY_CHAIN ?? ''; export const WS_WESTEND_RELAY_CHAIN = process.env.WS_WESTEND_RELAY_CHAIN ?? ''; -export const WS_ROCOCO_CORETIME_CHAIN = - process.env.WS_ROCOCO_CORETIME_CHAIN ?? ''; -export const WS_KUSAMA_CORETIME_CHAIN = - process.env.WS_KUSAMA_CORETIME_CHAIN ?? ''; -export const WS_WESTEND_CORETIME_CHAIN = - process.env.WS_WESTEND_CORETIME_CHAIN ?? ''; +export const WS_ROCOCO_CORETIME_CHAIN = process.env.WS_ROCOCO_CORETIME_CHAIN ?? ''; +export const WS_KUSAMA_CORETIME_CHAIN = process.env.WS_KUSAMA_CORETIME_CHAIN ?? ''; +export const WS_WESTEND_CORETIME_CHAIN = process.env.WS_WESTEND_CORETIME_CHAIN ?? ''; export const WS_REGIONX_COCOS_CHAIN = process.env.WS_REGIONX_COCOS_CHAIN ?? ''; export const EXPERIMENTAL = process.env.EXPERIMENTAL == 'true' ? true : false; diff --git a/src/contexts/account/index.tsx b/src/contexts/account/index.tsx index 9abd1ec4..68797d90 100644 --- a/src/contexts/account/index.tsx +++ b/src/contexts/account/index.tsx @@ -122,8 +122,7 @@ const AccountProvider = ({ children }: Props) => { if (accounts.length) { const activeAccount = localStorage.getItem(LOCAL_STORAGE_ACTIVE_ACCOUNT); const account: InjectedAccountWithMeta = activeAccount - ? (accounts.find((acc: any) => acc.address == activeAccount) ?? - accounts[0]) + ? (accounts.find((acc: any) => acc.address == activeAccount) ?? accounts[0]) : accounts[0]; setActiveAccount(account); @@ -158,14 +157,12 @@ const AccountProvider = ({ children }: Props) => { const metaKeys = ['genesisHash', 'name', 'source']; for (const key of keys) if (!Object.hasOwn(item, key)) return false; - for (const key of Object.keys(item)) - if (keys.indexOf(key) === -1) return false; + for (const key of Object.keys(item)) if (keys.indexOf(key) === -1) return false; if (!isValidAddress(item.address)) return false; if (!Object.hasOwn(item.meta, 'source')) return false; - for (const key of Object.keys(item.meta)) - if (metaKeys.indexOf(key) === -1) return false; + for (const key of Object.keys(item.meta)) if (metaKeys.indexOf(key) === -1) return false; } return true; diff --git a/src/contexts/apis/CoretimeApi/index.tsx b/src/contexts/apis/CoretimeApi/index.tsx index 1a924538..b8444a04 100644 --- a/src/contexts/apis/CoretimeApi/index.tsx +++ b/src/contexts/apis/CoretimeApi/index.tsx @@ -61,8 +61,7 @@ const CoretimeApiContextProvider = (props: any) => { const disconnectCoretime = () => disconnect(state); useEffect(() => { - state.apiState === ApiState.ERROR && - toastError(`Failed to connect to Coretime chain`); + state.apiState === ApiState.ERROR && toastError(`Failed to connect to Coretime chain`); }, [state.apiState, toastError]); useEffect(() => { diff --git a/src/contexts/apis/RegionXApi/index.tsx b/src/contexts/apis/RegionXApi/index.tsx index c18527e7..fcf3501a 100644 --- a/src/contexts/apis/RegionXApi/index.tsx +++ b/src/contexts/apis/RegionXApi/index.tsx @@ -95,8 +95,7 @@ const RegionXApiContextProvider = (props: any) => { const { network } = useNetwork(); useEffect(() => { - state.apiState === ApiState.ERROR && - toastError(`Failed to connect to RegionX chain`); + state.apiState === ApiState.ERROR && toastError(`Failed to connect to RegionX chain`); }, [state.apiState, toastError]); const disconnectRegionX = () => disconnect(state); diff --git a/src/contexts/apis/RelayApi/index.tsx b/src/contexts/apis/RelayApi/index.tsx index ea0bac0b..c65013c9 100644 --- a/src/contexts/apis/RelayApi/index.tsx +++ b/src/contexts/apis/RelayApi/index.tsx @@ -2,11 +2,7 @@ import React, { useContext, useEffect, useReducer, useState } from 'react'; import { parseHNString } from '@/utils/functions'; -import { - WS_KUSAMA_RELAY_CHAIN, - WS_ROCOCO_RELAY_CHAIN, - WS_WESTEND_RELAY_CHAIN, -} from '@/consts'; +import { WS_KUSAMA_RELAY_CHAIN, WS_ROCOCO_RELAY_CHAIN, WS_WESTEND_RELAY_CHAIN } from '@/consts'; import { ApiState } from '@/contexts/apis/types'; import { useNetwork } from '@/contexts/network'; import { useToast } from '@/contexts/toast'; @@ -32,8 +28,7 @@ const RelayApiContextProvider = (props: any) => { const { network } = useNetwork(); useEffect(() => { - state.apiState === ApiState.ERROR && - toastError(`Failed to connect to relay chain`); + state.apiState === ApiState.ERROR && toastError(`Failed to connect to relay chain`); }, [state.apiState, toastError]); const disconnectRelay = () => disconnect(state); @@ -70,9 +65,7 @@ const RelayApiContextProvider = (props: any) => { const fetchParaIds = async () => { if (!api.query.paras) return; const paras = await api.query.registrar.paras.keys(); - const paraIds = paras.map((key: any) => - parseHNString(key.toHuman().toString()) - ); + const paraIds = paras.map((key: any) => parseHNString(key.toHuman().toString())); setParaIds(paraIds); }; fetchParaIds(); diff --git a/src/contexts/balance/index.tsx b/src/contexts/balance/index.tsx index c74f23ec..25e9b035 100644 --- a/src/contexts/balance/index.tsx +++ b/src/contexts/balance/index.tsx @@ -59,8 +59,7 @@ const BalanceProvider = ({ children }: Props) => { setRxCurrencyBalance(0); return; } - if (!isCoretimeReady || !isRelayReady || !coretimeApi || !relayApi) - return; + if (!isCoretimeReady || !isRelayReady || !coretimeApi || !relayApi) return; const { address } = activeAccount; const unsubscribeCoretime = await coretimeApi.queryMulti( diff --git a/src/contexts/market/index.tsx b/src/contexts/market/index.tsx index bd7d110f..ce254029 100644 --- a/src/contexts/market/index.tsx +++ b/src/contexts/market/index.tsx @@ -1,12 +1,6 @@ import { BN } from '@polkadot/util'; import { ContextData, Region, RegionId } from 'coretime-utils'; -import React, { - createContext, - useCallback, - useContext, - useEffect, - useState, -} from 'react'; +import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'; import { parseHNString, timesliceToTimestamp } from '@/utils/functions'; @@ -42,11 +36,7 @@ const MarketProvider = ({ children }: Props) => { } = useRegionXApi(); const { timeslicePeriod } = useCoretimeApi(); const { - state: { - api: relayApi, - isApiReady: isRelayReady, - height: relayBlockNumber, - }, + state: { api: relayApi, isApiReady: isRelayReady, height: relayBlockNumber }, } = useRelayApi(); const { network } = useNetwork(); @@ -54,14 +44,7 @@ const MarketProvider = ({ children }: Props) => { const [listedRegions, setListedRegions] = useState>([]); const fetchMarket = useCallback(async () => { - if ( - !regionXApi || - !isRegionXReady || - !relayApi || - !isRelayReady || - !relayBlockNumber - ) - return; + if (!regionXApi || !isRegionXReady || !relayApi || !isRelayReady || !relayBlockNumber) return; try { setStatus(ContextStatus.LOADING); @@ -94,8 +77,7 @@ const MarketProvider = ({ children }: Props) => { for await (const [key, value] of listingEntries) { const [{ begin, core, mask }] = key.toHuman() as [any]; - const { seller, timeslicePrice, saleRecipient } = - value.toJSON() as ListingRecord; + const { seller, timeslicePrice, saleRecipient } = value.toJSON() as ListingRecord; const regionId = { begin: parseHNString(begin), @@ -104,8 +86,7 @@ const MarketProvider = ({ children }: Props) => { } as RegionId; const region = regions.find( - (item) => - JSON.stringify(item.getRegionId()) === JSON.stringify(regionId) + (item) => JSON.stringify(item.getRegionId()) === JSON.stringify(regionId) ); if (!region) continue; const beginTimestamp = await timesliceToTimestamp( @@ -113,11 +94,7 @@ const MarketProvider = ({ children }: Props) => { region.getBegin(), timeslicePeriod ); - const endTimestamp = await timesliceToTimestamp( - relayApi, - region.getEnd(), - timeslicePeriod - ); + const endTimestamp = await timesliceToTimestamp(relayApi, region.getEnd(), timeslicePeriod); const record: Listing = Listing.construct( { timeslicePeriod, relayBlockNumber } as ContextData, region, @@ -141,8 +118,7 @@ const MarketProvider = ({ children }: Props) => { }, [regionXApi, isRegionXReady, relayApi, isRelayReady, relayBlockNumber]); useEffect(() => { - if (relayBlockNumber > 0 && status === ContextStatus.UNINITIALIZED) - fetchMarket(); + if (relayBlockNumber > 0 && status === ContextStatus.UNINITIALIZED) fetchMarket(); }, [relayBlockNumber, status, fetchMarket]); useEffect(() => { diff --git a/src/contexts/network/index.tsx b/src/contexts/network/index.tsx index 58b3f608..196e0e00 100644 --- a/src/contexts/network/index.tsx +++ b/src/contexts/network/index.tsx @@ -22,9 +22,7 @@ interface Props { } const NetworkProvider = ({ children }: Props) => { - const [activeNetwork, setActiveNetwork] = useState( - NetworkType.NONE - ); + const [activeNetwork, setActiveNetwork] = useState(NetworkType.NONE); const router = useRouter(); const { network } = router.query; diff --git a/src/contexts/orders/index.tsx b/src/contexts/orders/index.tsx index e9fea2a0..08b214fe 100644 --- a/src/contexts/orders/index.tsx +++ b/src/contexts/orders/index.tsx @@ -1,10 +1,4 @@ -import { - createContext, - useCallback, - useContext, - useEffect, - useState, -} from 'react'; +import { createContext, useCallback, useContext, useEffect, useState } from 'react'; import { fetchOrders as fetchOrdersApi, fetchUserContribution } from '@/apis'; import { ApiResponse, ContextStatus, Order } from '@/models'; @@ -65,10 +59,7 @@ const OrderProvider = ({ children }: Props) => { if (status !== 200 || nodes === null) break; - sum += nodes.reduce( - (acc: number, item: Contribution) => acc + parseInt(item.amount), - 0 - ); + sum += nodes.reduce((acc: number, item: Contribution) => acc + parseInt(item.amount), 0); finished = !pageInfo.hasNextPage; after = pageInfo.endCursor; diff --git a/src/contexts/regions/coretime/index.ts b/src/contexts/regions/coretime/index.ts index af8a06f4..db475183 100644 --- a/src/contexts/regions/coretime/index.ts +++ b/src/contexts/regions/coretime/index.ts @@ -3,9 +3,7 @@ import { Region } from 'coretime-utils'; import { parseHNString } from '@/utils/functions'; -export const fetchRegions = async ( - coretimeApi: ApiPromise | null -): Promise> => { +export const fetchRegions = async (coretimeApi: ApiPromise | null): Promise> => { if (!coretimeApi) { return []; } diff --git a/src/contexts/regions/index.tsx b/src/contexts/regions/index.tsx index 790e82a5..75f91c85 100644 --- a/src/contexts/regions/index.tsx +++ b/src/contexts/regions/index.tsx @@ -1,12 +1,6 @@ import { encodeAddress } from '@polkadot/util-crypto'; import { CoreIndex, getEncodedRegionId, Region } from 'coretime-utils'; -import React, { - createContext, - useCallback, - useContext, - useEffect, - useState, -} from 'react'; +import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'; import { enableRegionX } from '@/utils/functions'; @@ -58,11 +52,7 @@ const RegionDataProvider = ({ children }: Props) => { state: { api: regionxApi, isApiReady: isRegionXReady }, } = useRegionXApi(); const { - state: { - api: relayApi, - isApiReady: isRelayReady, - height: relayBlockNumber, - }, + state: { api: relayApi, isApiReady: isRelayReady, height: relayBlockNumber }, } = useRelayApi(); const { state: { activeAccount }, @@ -73,9 +63,7 @@ const RegionDataProvider = ({ children }: Props) => { const [currentAddress, setCurrentAddress] = useState(null); const [regions, setRegions] = useState>([]); - const [status, setStatus] = useState( - ContextStatus.UNINITIALIZED - ); + const [status, setStatus] = useState(ContextStatus.UNINITIALIZED); useEffect(() => { setStatus(ContextStatus.UNINITIALIZED); @@ -121,35 +109,25 @@ const RegionDataProvider = ({ children }: Props) => { const tasks = await fetchWorkplan(); const ctRegions = await collectCoretimeRegions(tasks); - const rxRegions = enableRegionX(network) - ? await collectRegionXRegions(tasks) - : []; + const rxRegions = enableRegionX(network) ? await collectRegionXRegions(tasks) : []; setRegions(ctRegions.concat(rxRegions)); setStatus(ContextStatus.LOADED); }; - const collectCoretimeRegions = async ( - tasks: Tasks - ): Promise> => { + const collectCoretimeRegions = async (tasks: Tasks): Promise> => { const region_metadata: Array = []; const regions = await CoretimeRegions.fetchRegions(coretimeApi); for await (const region of regions) { - const metadata = await constructMetadata( - region, - tasks, - RegionLocation.CORETIME_CHAIN - ); + const metadata = await constructMetadata(region, tasks, RegionLocation.CORETIME_CHAIN); metadata && region_metadata.push(metadata); } return region_metadata; }; - const collectRegionXRegions = async ( - tasks: Tasks - ): Promise> => { + const collectRegionXRegions = async (tasks: Tasks): Promise> => { const region_metadata: Array = []; const regions = await RegionXRegions.fetchRegions(regionxApi); @@ -178,8 +156,7 @@ const RegionDataProvider = ({ children }: Props) => { if (!activeAccount || !region.getOwner()) return null; // Only user owned non-expired regions. if ( - encodeAddress(region.getOwner(), 42) !== - encodeAddress(activeAccount.address, 42) || + encodeAddress(region.getOwner(), 42) !== encodeAddress(activeAccount.address, 42) || region.consumed({ timeslicePeriod, relayBlockNumber }) > 1 ) return null; @@ -189,8 +166,7 @@ const RegionDataProvider = ({ children }: Props) => { location === RegionLocation.CORETIME_CHAIN ? coretimeApi : regionxApi ).toString(); - const name = - localStorage.getItem(`region-${rawId}`) ?? `Region #${region.getCore()}`; // RegionId is the first three digits. + const name = localStorage.getItem(`region-${rawId}`) ?? `Region #${region.getCore()}`; // RegionId is the first three digits. let task = tasks[rawId.toString()] ?? null; // If the region isn't still active it cannot be in the workload. diff --git a/src/contexts/regions/regionx/index.ts b/src/contexts/regions/regionx/index.ts index 12cf410e..1e465525 100644 --- a/src/contexts/regions/regionx/index.ts +++ b/src/contexts/regions/regionx/index.ts @@ -43,9 +43,7 @@ export const fetchRegions = async ( ); return [ region, - record.pending - ? ISMPRecordStatus.PENDING - : ISMPRecordStatus.UNAVAILABLE, + record.pending ? ISMPRecordStatus.PENDING : ISMPRecordStatus.UNAVAILABLE, record.pending, ]; } diff --git a/src/contexts/sales/index.tsx b/src/contexts/sales/index.tsx index 355a18cc..42356798 100644 --- a/src/contexts/sales/index.tsx +++ b/src/contexts/sales/index.tsx @@ -95,15 +95,11 @@ const SaleInfoProvider = ({ children }: Props) => { } = useCoretimeApi(); const [saleInfo, setSaleInfo] = useState(defaultSaleData.saleInfo); - const [saleStatus, setSaleStatus] = useState( - defaultSaleData.saleStatus - ); + const [saleStatus, setSaleStatus] = useState(defaultSaleData.saleStatus); const [config, setConfig] = useState(defaultSaleData.config); const [status, setStatus] = useState(ContextStatus.UNINITIALIZED); - const [currentPhase, setCurrentPhase] = useState( - SalePhase.Interlude - ); + const [currentPhase, setCurrentPhase] = useState(SalePhase.Interlude); const [at, setAt] = useState(0); const [currentPrice, setCurrentPrice] = useState(); const [endpoints, setEndpoints] = useState(defaultEndpoints); @@ -114,9 +110,7 @@ const SaleInfoProvider = ({ children }: Props) => { useEffect(() => { setCurrentPrice( - status !== ContextStatus.LOADED || height === 0 - ? undefined - : getCorePriceAt(at, saleInfo) + status !== ContextStatus.LOADED || height === 0 ? undefined : getCorePriceAt(at, saleInfo) ); }, [status, at, height, network, saleInfo]); @@ -128,20 +122,18 @@ const SaleInfoProvider = ({ children }: Props) => { return; } - const [brokerStatusRaw, saleInfoRaw, configRaw] = (await new Promise( - (resolve, _reject) => { - coretimeApi.queryMulti( - [ - coretimeApi.query.broker.status, - coretimeApi.query.broker.saleInfo, - coretimeApi.query.broker.configuration, - ], - (result) => { - resolve(result); - } - ); - } - )) as Array; + const [brokerStatusRaw, saleInfoRaw, configRaw] = (await new Promise((resolve, _reject) => { + coretimeApi.queryMulti( + [ + coretimeApi.query.broker.status, + coretimeApi.query.broker.saleInfo, + coretimeApi.query.broker.configuration, + ], + (result) => { + resolve(result); + } + ); + })) as Array; const saleInfo = saleInfoRaw.toJSON() as SaleInfo; // On Rococo we have `endPrice` while on Kusama we still have `price`. @@ -156,11 +148,7 @@ const SaleInfoProvider = ({ children }: Props) => { const saleStart = saleInfo.saleStart; // Sale start != bulk phase start. sale_start = bulk_phase_start + interlude_length. - const saleStartTimestamp = await getBlockTimestamp( - coretimeApi, - saleStart, - network - ); + const saleStartTimestamp = await getBlockTimestamp(coretimeApi, saleStart, network); const regionDuration = saleInfo.regionEnd - saleInfo.regionBegin; const blockTime = getBlockTime(network); // Block time on the coretime chain diff --git a/src/contexts/settings/index.tsx b/src/contexts/settings/index.tsx index 173fbf62..7ac4d594 100644 --- a/src/contexts/settings/index.tsx +++ b/src/contexts/settings/index.tsx @@ -40,9 +40,7 @@ const SettingsProvider = ({ children }: Props) => { }; return ( - + {children} ); diff --git a/src/contexts/tasks/index.tsx b/src/contexts/tasks/index.tsx index bf654a17..962a35b3 100644 --- a/src/contexts/tasks/index.tsx +++ b/src/contexts/tasks/index.tsx @@ -24,10 +24,7 @@ const defaultTasksData: TasksData = { fetchWorkplan: async (): Promise => { return {}; }, - fetchRegionWorkload: async ( - _core: CoreIndex, - _mask: string - ): Promise => { + fetchRegionWorkload: async (_core: CoreIndex, _mask: string): Promise => { return null; }, loadTasksFromLocalStorage: () => { @@ -58,8 +55,7 @@ const TaskDataProvider = ({ children }: Props) => { // The tasks which will run on Polkadot cores in the future. const fetchWorkplan = async (): Promise => { - if (!coretimeApi || !isCoretimeReady || !coretimeApi.query.broker) - return {}; + if (!coretimeApi || !isCoretimeReady || !coretimeApi.query.broker) return {}; try { const workplan = await coretimeApi.query.broker.workplan.entries(); const tasks: Record = {}; @@ -77,11 +73,11 @@ const TaskDataProvider = ({ children }: Props) => { }; if (assignment === 'Pool') { - tasks[getEncodedRegionId(regionId, coretimeApi).toString()] = - POOLING_TASK_ID; + tasks[getEncodedRegionId(regionId, coretimeApi).toString()] = POOLING_TASK_ID; } else { - tasks[getEncodedRegionId(regionId, coretimeApi).toString()] = - assignment.Task ? parseHNString(assignment.Task) : null; + tasks[getEncodedRegionId(regionId, coretimeApi).toString()] = assignment.Task + ? parseHNString(assignment.Task) + : null; } }); } @@ -93,16 +89,10 @@ const TaskDataProvider = ({ children }: Props) => { }; // The tasks currently running on a Polkadot core. - const fetchRegionWorkload = async ( - core: CoreIndex, - regionMask: string - ): Promise => { - if (!coretimeApi || !isCoretimeReady || !coretimeApi.query.broker) - return null; + const fetchRegionWorkload = async (core: CoreIndex, regionMask: string): Promise => { + if (!coretimeApi || !isCoretimeReady || !coretimeApi.query.broker) return null; const workload = ( - ( - await coretimeApi.query.broker.workload(core) - ).toHuman() as ScheduleItem[] + (await coretimeApi.query.broker.workload(core)).toHuman() as ScheduleItem[] )[0]; if (!workload) return null; diff --git a/src/contexts/toast/index.tsx b/src/contexts/toast/index.tsx index 155d3105..ae55282d 100644 --- a/src/contexts/toast/index.tsx +++ b/src/contexts/toast/index.tsx @@ -73,9 +73,7 @@ const ToastProviderWrapper = ({ children }: Props) => { ); return ( - + {children} ); diff --git a/src/hooks/accountExtrinsics.ts b/src/hooks/accountExtrinsics.ts index 5d204c77..e2d2d5e9 100644 --- a/src/hooks/accountExtrinsics.ts +++ b/src/hooks/accountExtrinsics.ts @@ -1,17 +1,9 @@ import { useEffect, useState } from 'react'; import { fetchAccountExtrinsics } from '@/apis'; -import { - AccountTxHistoryItem, - Address, - ApiResponse, - NetworkType, -} from '@/models'; +import { AccountTxHistoryItem, Address, ApiResponse, NetworkType } from '@/models'; -export const useAccountExtrinsics = ( - network: NetworkType, - account: Address -) => { +export const useAccountExtrinsics = (network: NetworkType, account: Address) => { const [loading, setLoading] = useState(false); const [data, setData] = useState([]); const [isError, setError] = useState(false); @@ -32,16 +24,11 @@ export const useAccountExtrinsics = ( const result = []; while (!finished) { - const res: ApiResponse = await fetchAccountExtrinsics( - network, - account, - after - ); + const res: ApiResponse = await fetchAccountExtrinsics(network, account, after); const { status, data } = res; if (status !== 200) break; - if (data.extrinsics.nodes !== null) - result.push(...data.extrinsics.nodes); + if (data.extrinsics.nodes !== null) result.push(...data.extrinsics.nodes); finished = !data.extrinsics.pageInfo.hasNextPage; after = data.extrinsics.pageInfo.endCursor; diff --git a/src/hooks/order/processed.ts b/src/hooks/order/processed.ts index 80f05f81..514343e5 100644 --- a/src/hooks/order/processed.ts +++ b/src/hooks/order/processed.ts @@ -26,8 +26,7 @@ export const useProcessedOrders = () => { const { status, data } = res; if (status !== 200) break; - if (data.processedOrders.nodes !== null) - result.push(...data.processedOrders.nodes); + if (data.processedOrders.nodes !== null) result.push(...data.processedOrders.nodes); finished = !data.processedOrders.pageInfo.hasNextPage; after = data.processedOrders.pageInfo.endCursor; @@ -37,17 +36,7 @@ export const useProcessedOrders = () => { } else { setData( result.map( - ({ - orderId, - height, - extrinsicId, - timestamp, - begin, - core, - mask, - seller, - reward, - }) => + ({ orderId, height, extrinsicId, timestamp, begin, core, mask, seller, reward }) => ({ orderId, height, diff --git a/src/hooks/parasInfo.ts b/src/hooks/parasInfo.ts index f0a5de5d..d6c138e9 100644 --- a/src/hooks/parasInfo.ts +++ b/src/hooks/parasInfo.ts @@ -67,9 +67,9 @@ export const useParasInfo = () => { const fetchLeaseHoldingParas = async (): Promise => { if (!coretimeApi || !isCoretimeReady) return []; const leases = await coretimeApi.query.broker.leases(); - const ids = ( - leases.toJSON() as Array<{ until: number; task: number }> - ).map((lease) => lease.task); + const ids = (leases.toJSON() as Array<{ until: number; task: number }>).map( + (lease) => lease.task + ); return ids; }; @@ -160,31 +160,19 @@ export const useParasInfo = () => { }; const fetchRegistrationConsts = async () => { - const value = BigInt( - relayApi.consts.registrar.dataDepositPerByte.toString() - ); + const value = BigInt(relayApi.consts.registrar.dataDepositPerByte.toString()); setDataDepositPerByte(value); - const { maxCodeSize } = ( - await relayApi.query.configuration.activeConfig() - ).toJSON() as any; + const { maxCodeSize } = (await relayApi.query.configuration.activeConfig()).toJSON() as any; setMaxCodeSize(BigInt(maxCodeSize)); }; - await Promise.all([ - fetchNextParaId(), - fetchReservationCost(), - fetchRegistrationConsts(), - ]); + await Promise.all([fetchNextParaId(), fetchReservationCost(), fetchRegistrationConsts()]); const paras = await fetchParachainList(); const reservedParas = await fetchReservedParas(); - paras.push( - ...reservedParas.filter( - ({ id }) => paras.find((v) => v.id === id) === undefined - ) - ); + paras.push(...reservedParas.filter(({ id }) => paras.find((v) => v.id === id) === undefined)); paras.sort((a, b) => a.id - b.id); setParachains(paras); diff --git a/src/hooks/renewableParas.ts b/src/hooks/renewableParas.ts index 9bee53ce..b4ae5b87 100644 --- a/src/hooks/renewableParas.ts +++ b/src/hooks/renewableParas.ts @@ -20,9 +20,7 @@ export const useRenewableParachains = () => { state: { api, apiState }, } = useCoretimeApi(); - const [status, setStatus] = useState( - ContextStatus.UNINITIALIZED - ); + const [status, setStatus] = useState(ContextStatus.UNINITIALIZED); const [parachains, setParachains] = useState([]); const { network } = useNetwork(); @@ -37,9 +35,7 @@ export const useRenewableParachains = () => { setStatus(ContextStatus.LOADING); - const renewals = [NetworkType.ROCOCO, NetworkType.WESTEND].includes( - network - ) + const renewals = [NetworkType.ROCOCO, NetworkType.WESTEND].includes(network) ? await api.query.broker.potentialRenewals.entries() : await api.query.broker.allowedRenewals.entries(); const chains: RenewableParachain[] = []; diff --git a/src/hooks/sale/purchaseHistory.ts b/src/hooks/sale/purchaseHistory.ts index 6820b4d3..dc7acd99 100644 --- a/src/hooks/sale/purchaseHistory.ts +++ b/src/hooks/sale/purchaseHistory.ts @@ -3,10 +3,7 @@ import { useEffect, useState } from 'react'; import { fetchPurchaseHistoryData } from '@/apis'; import { ApiResponse, NetworkType, PurchaseHistoryItem } from '@/models'; -export const usePurchaseHistory = ( - network: NetworkType, - regionBegin: number -) => { +export const usePurchaseHistory = (network: NetworkType, regionBegin: number) => { const [loading, setLoading] = useState(false); const [data, setData] = useState([]); const [isError, setError] = useState(false); @@ -26,17 +23,12 @@ export const usePurchaseHistory = ( const result = []; while (!finished) { - const res: ApiResponse = await fetchPurchaseHistoryData( - network, - regionBegin, - after - ); + const res: ApiResponse = await fetchPurchaseHistoryData(network, regionBegin, after); const { status, data } = res; if (status !== 200) break; - if (data.purchases.nodes !== null) - result.push(...data.purchases.nodes); + if (data.purchases.nodes !== null) result.push(...data.purchases.nodes); finished = !data.purchases.pageInfo.hasNextPage; after = data.purchases.pageInfo.endCursor; @@ -46,15 +38,7 @@ export const usePurchaseHistory = ( } else { setData( result.map( - ({ - account, - core, - extrinsicId, - height, - price, - purchaseType, - timestamp, - }) => + ({ account, core, extrinsicId, height, price, purchaseType, timestamp }) => ({ address: account, core, diff --git a/src/hooks/sale/saleDetails.ts b/src/hooks/sale/saleDetails.ts index c1d08581..9401afe2 100644 --- a/src/hooks/sale/saleDetails.ts +++ b/src/hooks/sale/saleDetails.ts @@ -21,17 +21,12 @@ export const useSaleDetails = (network: NetworkType, saleCycle: number) => { const result = []; while (!finished) { - const res: ApiResponse = await fetchSaleDetailsData( - network, - saleCycle, - after - ); + const res: ApiResponse = await fetchSaleDetailsData(network, saleCycle, after); const { status, data } = res; if (status !== 200) break; - if (data.purchases.nodes !== null) - result.push(...data.purchases.nodes); + if (data.purchases.nodes !== null) result.push(...data.purchases.nodes); finished = !data.purchases.pageInfo.hasNextPage; after = data.purchases.pageInfo.endCursor; @@ -41,15 +36,7 @@ export const useSaleDetails = (network: NetworkType, saleCycle: number) => { } else { setData( result.map( - ({ - account, - core, - extrinsicId, - height, - price, - purchaseType, - timestamp, - }) => + ({ account, core, extrinsicId, height, price, purchaseType, timestamp }) => ({ address: account, core, diff --git a/src/icons/Assign.tsx b/src/icons/Assign.tsx index 1cc17bf3..8096efdf 100644 --- a/src/icons/Assign.tsx +++ b/src/icons/Assign.tsx @@ -3,13 +3,7 @@ type IconProps = { }; export const AssignmentIcon = ({ color }: IconProps) => { return ( - + { return ( - + { return ( - + { return ( - + { return ( - + { phase: { currentPrice }, } = useSaleInfo(); - const { data: purchaseHistoryData, loading: loadingPurchaseHistory } = - usePurchaseHistory(network, regionBegin); - - const renewals = purchaseHistoryData.filter( - (item) => item.type === PurchaseType.RENEWAL + const { data: purchaseHistoryData, loading: loadingPurchaseHistory } = usePurchaseHistory( + network, + regionBegin ); + + const renewals = purchaseHistoryData.filter((item) => item.type === PurchaseType.RENEWAL); const numRenewals = renewals.length; const renewalCost = numRenewals === 0 ? 0 - : Math.floor( - renewals.reduce((sum, item) => sum + item.price, 0) / numRenewals - ); + : Math.floor(renewals.reduce((sum, item) => sum + item.price, 0) / numRenewals); - const { - currentBurn, - prevBurn, - totalBurn, - loading: loadingBurnInfo, - } = useBurnInfo(network); + const { currentBurn, prevBurn, totalBurn, loading: loadingBurnInfo } = useBurnInfo(network); const formatBalance = (value: number): string => { return getBalanceString(value.toString(), decimals, symbol); @@ -191,9 +184,7 @@ const Home = () => { > RegionX | Coretime Hub - - Explore all the possibilities RegionX Coretime Hub offers - + Explore all the possibilities RegionX Coretime Hub offers {sections.map(({ top, bottom }, index) => ( @@ -250,9 +241,7 @@ const Home = () => { padding: '1rem 1.25rem', }} > - - {bottom.label} - + {bottom.label} { - + Purchase History - - Get an insight into all purchases and renewals made during the - current bulk period + + Get an insight into all purchases and renewals made during the current bulk period diff --git a/src/pages/marketplace.tsx b/src/pages/marketplace.tsx index 1d3bc87c..d9735ae1 100644 --- a/src/pages/marketplace.tsx +++ b/src/pages/marketplace.tsx @@ -17,12 +17,7 @@ import { useEffect, useState } from 'react'; import { useSubmitExtrinsic } from '@/hooks/submitExtrinsic'; -import { - Balance, - MarketFilter, - MarketRegion, - PurchaseModal, -} from '@/components'; +import { Balance, MarketFilter, MarketRegion, PurchaseModal } from '@/components'; import { useAccounts } from '@/contexts/account'; import { useRegionXApi } from '@/contexts/apis/RegionXApi'; @@ -99,78 +94,54 @@ const Marketplace = () => { const txUnlist = regionXApi.tx.market.unlistRegion(regionId); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txUnlist, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess('Transaction successful'); - fetchMarket(); - }, - fail: () => { - toastError(`Failed to unlist the region`); - }, - error: (e) => { - toastError( - `Failed to unlist the region. Error: ${ - e.errorMessage === 'Error' - ? 'Please check your balance.' - : e.errorMessage - }` - ); - setWorking(false); - }, - } - ); + submitExtrinsicWithFeeInfo(symbol, decimals, txUnlist, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Transaction successful'); + fetchMarket(); + }, + fail: () => { + toastError(`Failed to unlist the region`); + }, + error: (e) => { + toastError( + `Failed to unlist the region. Error: ${ + e.errorMessage === 'Error' ? 'Please check your balance.' : e.errorMessage + }` + ); + setWorking(false); + }, + }); }; const onUnlist = (region: Region) => { confirm({ - description: - 'Are you sure that you are going to unlist the selected region from the market?', + description: 'Are you sure that you are going to unlist the selected region from the market?', }).then(() => unlistRegion(region.getOnChainRegionId())); }; useEffect(() => { const checkConditions = (listing: Listing): boolean => { const { region, beginTimestamp, endTimestamp, currentPrice } = listing; - const { startDate, endDate, coreOccupancy, minDuration, price } = - filterOptions; + const { startDate, endDate, coreOccupancy, minDuration, price } = filterOptions; - if ( - startDate && - !moment(beginTimestamp).isSameOrAfter(moment(startDate), 'day') - ) - return false; - if ( - endDate && - !moment(endTimestamp).isSameOrAfter(moment(endDate), 'day') - ) + if (startDate && !moment(beginTimestamp).isSameOrAfter(moment(startDate), 'day')) return false; + if (endDate && !moment(endTimestamp).isSameOrAfter(moment(endDate), 'day')) return false; const occupancy = region.coreOccupancy(); - if ( - coreOccupancy && - !(occupancy >= coreOccupancy.min && occupancy <= coreOccupancy.max) - ) + if (coreOccupancy && !(occupancy >= coreOccupancy.min && occupancy <= coreOccupancy.max)) return false; const duration = endTimestamp - beginTimestamp; if (minDuration && duration < minDuration) return false; - if ( - price && - !(currentPrice.cmp(price.min) >= 0 && currentPrice.cmp(price.max) <= 0) - ) { + if (price && !(currentPrice.cmp(price.min) >= 0 && currentPrice.cmp(price.max) <= 0)) { return false; } @@ -215,16 +186,10 @@ const Marketplace = () => { }} > - + Explore the market - + Explore all the regions listed on the marketplace @@ -256,12 +221,7 @@ const Marketplace = () => { {filteredListings.length > 0 && ( - + {filteredListings.map((listing, index) => ( @@ -283,9 +243,7 @@ const Marketplace = () => { } disabled={working} > - {listing.seller === activeAccount.address - ? 'Unlist' - : 'Purchase'} + {listing.seller === activeAccount.address ? 'Unlist' : 'Purchase'} ) : ( <> diff --git a/src/pages/orders/index.tsx b/src/pages/orders/index.tsx index 5a08dd9a..68de60a0 100644 --- a/src/pages/orders/index.tsx +++ b/src/pages/orders/index.tsx @@ -45,9 +45,7 @@ const OrderDashboard = () => { let _orders: Array = orders.filter(({ processed }) => !processed); if (saleInfoStatus === ContextStatus.LOADED) { - _orders = _orders.filter( - ({ end }) => end > saleStatus.lastCommittedTimeslice - ); + _orders = _orders.filter(({ end }) => end > saleStatus.lastCommittedTimeslice); } setOrdersToShow(_orders); }, [orders, saleInfoStatus, saleStatus]); @@ -65,24 +63,15 @@ const OrderDashboard = () => { }} > - + Orders Dashboard - + Explorer the orders - openOrderCreationModal(true)} - /> + openOrderCreationModal(true)} /> {orderStatus === ContextStatus.ERROR ? ( @@ -94,12 +83,7 @@ const OrderDashboard = () => { ) : ( - + {ordersToShow.map((order: Order, index: number) => ( diff --git a/src/pages/orders/processor.tsx b/src/pages/orders/processor.tsx index 297495fe..0bac7a78 100644 --- a/src/pages/orders/processor.tsx +++ b/src/pages/orders/processor.tsx @@ -1,12 +1,4 @@ -import { - Backdrop, - Box, - Card, - CircularProgress, - Stack, - Typography, - useTheme, -} from '@mui/material'; +import { Backdrop, Box, Card, CircularProgress, Stack, Typography, useTheme } from '@mui/material'; import { useProcessedOrders } from '@/hooks/order'; @@ -22,8 +14,7 @@ const OrderProcessor = () => { state: { apiState }, } = useRegionXApi(); - const { data: processedOrderData, loading: loadingProcessedOrders } = - useProcessedOrders(); + const { data: processedOrderData, loading: loadingProcessedOrders } = useProcessedOrders(); return apiState !== ApiState.READY || loadingProcessedOrders ? ( @@ -34,16 +25,10 @@ const OrderProcessor = () => { - + Order Processor UI - + See all the orders that were fulfilled diff --git a/src/pages/paras/index.tsx b/src/pages/paras/index.tsx index 094e5de6..6c3e8252 100644 --- a/src/pages/paras/index.tsx +++ b/src/pages/paras/index.tsx @@ -15,13 +15,7 @@ import React, { useEffect, useState } from 'react'; import { useParasInfo, useRenewableParachains } from '@/hooks'; -import { - ActionButton, - Order, - ParachainTable, - RegisterModal, - ReserveModal, -} from '@/components'; +import { ActionButton, Order, ParachainTable, RegisterModal, ReserveModal } from '@/components'; import { leases } from '@/chaindata'; import { useCoretimeApi, useRelayApi } from '@/contexts/apis'; @@ -143,9 +137,7 @@ const ParachainManagement = () => { watching: watchList.includes(para.id), })); const filtered = parasWithWatchInfo.filter( - (para) => - para.id.toString().includes(search) && - (watchAll ? true : para.watching === true) + (para) => para.id.toString().includes(search) && (watchAll ? true : para.watching === true) ); if (orderBy === 'id') { filtered.sort(compId); @@ -166,16 +158,10 @@ const ParachainManagement = () => { }} > - + Parachain Dashboard - + Watch parachains state, register and manage parachains @@ -214,10 +200,7 @@ const ParachainManagement = () => { }, }} /> - openReserveModal(true)} - /> + openReserveModal(true)} /> {loading ? ( diff --git a/src/pages/paras/renewal.tsx b/src/pages/paras/renewal.tsx index 87b546c2..fa4e48a0 100644 --- a/src/pages/paras/renewal.tsx +++ b/src/pages/paras/renewal.tsx @@ -59,37 +59,29 @@ const Renewal = () => { const formatDuration = humanizer({ units: ['w', 'd', 'h'], round: true }); const handleRenew = () => { - if (!activeAccount || !coretimeApi || !isCoretimeReady || !activeSigner) - return; + if (!activeAccount || !coretimeApi || !isCoretimeReady || !activeSigner) return; const { core } = parachains[activeIdx]; const txRenewal = coretimeApi.tx.broker.renew(core); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txRenewal, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess('Successfully renewed the selected parachain'); - }, - fail: () => { - toastError(`Failed to renew the selected parachain`); - }, - error: (e) => { - toastError(`Failed to renew the selected parachain ${e}`); - setWorking(false); - }, - } - ); + submitExtrinsicWithFeeInfo(symbol, decimals, txRenewal, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Successfully renewed the selected parachain'); + }, + fail: () => { + toastError(`Failed to renew the selected parachain`); + }, + error: (e) => { + toastError(`Failed to renew the selected parachain ${e}`); + setWorking(false); + }, + }); }; useEffect(() => { @@ -140,12 +132,7 @@ const Renewal = () => { ]); useEffect(() => { - if ( - !router.isReady || - status !== ContextStatus.LOADED || - parachains.length === 0 - ) - return; + if (!router.isReady || status !== ContextStatus.LOADED || parachains.length === 0) return; const { query } = router; if (query['paraId'] === undefined) return; const paraId = parseInt(query['paraId'] as string); @@ -173,16 +160,10 @@ const Renewal = () => { }} > - + Renew a parachain - + Renew a parachain @@ -198,13 +179,7 @@ const Renewal = () => { boxShadow: 'none', }} > - + { borderColor={theme.palette.grey[400]} borderRadius='1rem' > - + { /> @@ -287,18 +255,8 @@ const Renewal = () => { /> )} - - + + diff --git a/src/pages/purchase.tsx b/src/pages/purchase.tsx index 9b278871..57786617 100644 --- a/src/pages/purchase.tsx +++ b/src/pages/purchase.tsx @@ -1,11 +1,4 @@ -import { - Backdrop, - Box, - Button, - CircularProgress, - Typography, - useTheme, -} from '@mui/material'; +import { Backdrop, Box, Button, CircularProgress, Typography, useTheme } from '@mui/material'; import { useRouter } from 'next/router'; import { useState } from 'react'; @@ -56,13 +49,10 @@ const Purchase = () => { const { submitExtrinsicWithFeeInfo } = useSubmitExtrinsic(); const onPurchase = async () => { - if (!api || apiState !== ApiState.READY || !activeAccount || !activeSigner) - return; + if (!api || apiState !== ApiState.READY || !activeAccount || !activeSigner) return; if (currentPhase === SalePhase.Interlude) { - toastWarning( - 'Sales start after the interlude period ends. Purchases can then be made.' - ); + toastWarning('Sales start after the interlude period ends. Purchases can then be made.'); return; } @@ -73,33 +63,26 @@ const Purchase = () => { const txPurchase = api.tx.broker.purchase(currentPrice); - submitExtrinsicWithFeeInfo( - symbol, - decimals, - txPurchase, - activeAccount.address, - activeSigner, - { - ready: () => { - setWorking(true); - toastInfo('Transaction was initiated'); - }, - inBlock: () => toastInfo('In Block'), - finalized: () => setWorking(false), - success: () => { - toastSuccess('Transaction successful'); - fetchSaleInfo(); - fetchRegions(); - }, - fail: () => { - toastError('Failed to purchase a core'); - }, - error: (e) => { - toastError(`Failed to purchase a core. ${e}`); - setWorking(false); - }, - } - ); + submitExtrinsicWithFeeInfo(symbol, decimals, txPurchase, activeAccount.address, activeSigner, { + ready: () => { + setWorking(true); + toastInfo('Transaction was initiated'); + }, + inBlock: () => toastInfo('In Block'), + finalized: () => setWorking(false), + success: () => { + toastSuccess('Transaction successful'); + fetchSaleInfo(); + fetchRegions(); + }, + fail: () => { + toastError('Failed to purchase a core'); + }, + error: (e) => { + toastError(`Failed to purchase a core. ${e}`); + setWorking(false); + }, + }); }; const onManage = () => { @@ -119,16 +102,10 @@ const Purchase = () => { }} > - + Purchase a core - + Buy a core straight from the Coretime chain @@ -154,9 +131,7 @@ const Purchase = () => { ) : ( - + diff --git a/src/pages/regions.tsx b/src/pages/regions.tsx index ab0a4305..c793cb15 100644 --- a/src/pages/regions.tsx +++ b/src/pages/regions.tsx @@ -27,18 +27,8 @@ import { useAccounts } from '@/contexts/account'; import { useMarket } from '@/contexts/market'; import { useRegions } from '@/contexts/regions'; import { useToast } from '@/contexts/toast'; -import { - AssignmentIcon, - InterlaceIcon, - PartitionIcon, - TransferIcon, -} from '@/icons'; -import { - ContextStatus, - ISMPRecordStatus, - RegionLocation, - RegionMetadata, -} from '@/models'; +import { AssignmentIcon, InterlaceIcon, PartitionIcon, TransferIcon } from '@/icons'; +import { ContextStatus, ISMPRecordStatus, RegionLocation, RegionMetadata } from '@/models'; const Dashboard = () => { const theme = useTheme(); @@ -60,16 +50,12 @@ const Dashboard = () => { const { toastInfo } = useToast(); const selectedRegion = - currentRegionIndex === undefined - ? undefined - : regionsToShow[currentRegionIndex]; + currentRegionIndex === undefined ? undefined : regionsToShow[currentRegionIndex]; const regionSelected = selectedRegion !== undefined; const manage = (openModal: (_v: boolean) => void) => { if (!regionSelected) { - toastInfo( - 'First select a region by clicking on one of the regions displayed.' - ); + toastInfo('First select a region by clicking on one of the regions displayed.'); } else { openModal(true); } @@ -129,8 +115,7 @@ const Dashboard = () => { ({ region }) => listedRegions.findIndex( (item) => - JSON.stringify(item.region.getRegionId()) === - JSON.stringify(region.getRegionId()) + JSON.stringify(item.region.getRegionId()) === JSON.stringify(region.getRegionId()) ) === -1 ) ); @@ -145,16 +130,10 @@ const Dashboard = () => { }} > - + Regions Dashboard - + Manage your cores @@ -188,8 +167,7 @@ const Dashboard = () => { Please connect your wallet. ) : regionsToShow.length === 0 ? ( - No regions owned. Go to bulk sales{' '} - to make a purchase + No regions owned. Go to bulk sales to make a purchase ) : ( <> diff --git a/src/pages/sales.tsx b/src/pages/sales.tsx index 98dc59d1..749129db 100644 --- a/src/pages/sales.tsx +++ b/src/pages/sales.tsx @@ -1,12 +1,4 @@ -import { - Backdrop, - Box, - Card, - CircularProgress, - Stack, - Typography, - useTheme, -} from '@mui/material'; +import { Backdrop, Box, Card, CircularProgress, Stack, Typography, useTheme } from '@mui/material'; import { useSalesHistory } from '@/hooks'; @@ -27,8 +19,7 @@ const Home = () => { } = useCoretimeApi(); const { status } = useSaleInfo(); - const { data: salesHistoryData, loading: loadingPurchaseHistory } = - useSalesHistory(network); + const { data: salesHistoryData, loading: loadingPurchaseHistory } = useSalesHistory(network); return status !== ContextStatus.LOADED || apiState !== ApiState.READY || @@ -42,16 +33,10 @@ const Home = () => { - + Historical sales - + Shows the full sale history diff --git a/src/utils/functions/api.ts b/src/utils/functions/api.ts index a674dc35..2a00294f 100644 --- a/src/utils/functions/api.ts +++ b/src/utils/functions/api.ts @@ -11,25 +11,21 @@ export const sendTx = async ( handlers: TxStatusHandlers ) => { try { - const unsub = await tx.signAndSend( - account, - { signer }, - ({ status, events }) => { - if (status.isReady) handlers.ready(); - else if (status.isInBlock) handlers.inBlock(); - else if (status.isFinalized) { - handlers.finalized(); - events.forEach(({ event: { method } }) => { - if (method === 'ExtrinsicSuccess') { - handlers.success(); - } else if (method === 'ExtrinsicFailed') { - handlers.fail(); - } - }); - unsub(); - } + const unsub = await tx.signAndSend(account, { signer }, ({ status, events }) => { + if (status.isReady) handlers.ready(); + else if (status.isInBlock) handlers.inBlock(); + else if (status.isFinalized) { + handlers.finalized(); + events.forEach(({ event: { method } }) => { + if (method === 'ExtrinsicSuccess') { + handlers.success(); + } else if (method === 'ExtrinsicFailed') { + handlers.fail(); + } + }); + unsub(); } - ); + }); } catch (e) { handlers.error(e); } finally { diff --git a/src/utils/functions/balance.ts b/src/utils/functions/balance.ts index b9084be8..c8d1f84e 100644 --- a/src/utils/functions/balance.ts +++ b/src/utils/functions/balance.ts @@ -31,11 +31,7 @@ const toFixedWithoutRounding = (value: number, decimalDigits: number) => { return Math.floor(value * factor) / factor; }; -export const getBalanceString = ( - balance: string, - decimals: number, - symbol: string -): string => { +export const getBalanceString = (balance: string, decimals: number, symbol: string): string => { if (balance == '0') return `0 ${symbol} `; const balanceNumber = Number(balance) / 10 ** decimals; if (balanceNumber > 1) { diff --git a/src/utils/functions/common.ts b/src/utils/functions/common.ts index b1d495da..de9d22a2 100644 --- a/src/utils/functions/common.ts +++ b/src/utils/functions/common.ts @@ -21,9 +21,7 @@ export const isValidAddress = (chainAddress: string, ss58Prefix = 42) => { }; export const truncateAddres = (address: string) => { - return ( - address.substring(0, 6) + '...' + address.substring(address.length - 6) - ); + return address.substring(0, 6) + '...' + address.substring(address.length - 6); }; export const writeToClipboard = async (value: string) => { diff --git a/src/utils/functions/timestamps.ts b/src/utils/functions/timestamps.ts index ea3fecea..bd7b6596 100644 --- a/src/utils/functions/timestamps.ts +++ b/src/utils/functions/timestamps.ts @@ -10,9 +10,7 @@ export const getBlockTimestamp = async ( try { const blockTime = network !== undefined ? getBlockTime(network) : 6 * 1000; const currentHeight = (await api.query.system.number()).toJSON() as number; - const currentTimestamp = ( - await api.query.timestamp.now() - ).toJSON() as number; + const currentTimestamp = (await api.query.timestamp.now()).toJSON() as number; return currentTimestamp + (height - currentHeight) * blockTime; } catch { return 0; diff --git a/src/utils/ismp/index.ts b/src/utils/ismp/index.ts index 30d41d6b..3d6152f1 100644 --- a/src/utils/ismp/index.ts +++ b/src/utils/ismp/index.ts @@ -13,10 +13,7 @@ export const waitForRegionRecordRequestEvent = async ( .events((events: any) => { events.forEach((record: any) => { const { event } = record; - if ( - event.section === 'regions' && - event.method === 'RegionRecordRequested' - ) { + if (event.section === 'regions' && event.method === 'RegionRecordRequested') { const id = event.data.toHuman().regionId; if ( id.begin === regionId.begin.toString() && @@ -38,9 +35,7 @@ export const queryRequest = async ( commitment: string ): Promise => { const leafIndex = regionxApi.createType('LeafIndexQuery', { commitment }); - const requests = await (regionxApi as any).rpc.ismp.queryRequests([ - leafIndex, - ]); + const requests = await (regionxApi as any).rpc.ismp.queryRequests([leafIndex]); // We only requested a single request so we only get one in the response. return requests.toJSON()[0] as IsmpRequest; }; @@ -56,10 +51,7 @@ export const makeResponse = async ( const hashAt = ( await coretimeApi.query.system.blockHash(Number(request.get.height)) ).toString(); - const proofData = await coretimeApi.rpc.state.getReadProof( - [request.get.keys[0]], - hashAt - ); + const proofData = await coretimeApi.rpc.state.getReadProof([request.get.keys[0]], hashAt); const stateMachineProof = regionxApi.createType('StateMachineProof', { hasher: 'Blake2', diff --git a/src/utils/sale/index.ts b/src/utils/sale/index.ts index 0eb6c1fc..92ba05e1 100644 --- a/src/utils/sale/index.ts +++ b/src/utils/sale/index.ts @@ -2,10 +2,7 @@ import { NetworkType, SaleInfo, SalePhase } from '@/models'; import { leadinFactorAt } from '../coretime'; -export const getCurrentPhase = ( - saleInfo: SaleInfo, - blockNumber: number -): SalePhase => { +export const getCurrentPhase = (saleInfo: SaleInfo, blockNumber: number): SalePhase => { if (blockNumber < saleInfo.saleStart) { return SalePhase.Interlude; } else if (blockNumber < saleInfo.saleStart + saleInfo.leadinLength) { diff --git a/src/utils/sale/sales.test.ts b/src/utils/sale/sales.test.ts index 77be3a02..e8c81fca 100644 --- a/src/utils/sale/sales.test.ts +++ b/src/utils/sale/sales.test.ts @@ -21,19 +21,13 @@ describe('Purchase page', () => { describe('getCurrentPhase', () => { it('Successfully recognizes interlude phase', () => { let blockNumber = mockSaleInfo.saleStart - 50; - expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe( - SalePhase.Interlude - ); + expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe(SalePhase.Interlude); blockNumber = mockSaleInfo.saleStart - 1; - expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe( - SalePhase.Interlude - ); + expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe(SalePhase.Interlude); blockNumber = mockSaleInfo.saleStart; - expect(getCurrentPhase(mockSaleInfo, blockNumber)).not.toBe( - SalePhase.Interlude - ); + expect(getCurrentPhase(mockSaleInfo, blockNumber)).not.toBe(SalePhase.Interlude); }); it('Successfully recognizes leadin phase', () => { @@ -44,30 +38,22 @@ describe('Purchase page', () => { expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe(SalePhase.Leadin); blockNumber = mockSaleInfo.saleStart + mockSaleInfo.leadinLength; - expect(getCurrentPhase(mockSaleInfo, blockNumber)).not.toBe( - SalePhase.Leadin - ); + expect(getCurrentPhase(mockSaleInfo, blockNumber)).not.toBe(SalePhase.Leadin); }); it('Successfully recognizes fixed price phase', () => { let blockNumber = mockSaleInfo.saleStart + mockSaleInfo.leadinLength; - expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe( - SalePhase.Regular - ); + expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe(SalePhase.Regular); blockNumber = mockSaleInfo.saleStart + mockSaleInfo.leadinLength + 50; - expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe( - SalePhase.Regular - ); + expect(getCurrentPhase(mockSaleInfo, blockNumber)).toBe(SalePhase.Regular); }); }); describe('getCorePriceAt', () => { it('getCorePriceAt works', () => { const blockNumber = mockSaleInfo.saleStart; - expect(getCorePriceAt(blockNumber, mockSaleInfo)).toBe( - mockSaleInfo.price * 100 - ); + expect(getCorePriceAt(blockNumber, mockSaleInfo)).toBe(mockSaleInfo.price * 100); }); }); }); diff --git a/src/utils/transfers/crossChain/index.ts b/src/utils/transfers/crossChain/index.ts index f1bc9325..1094a3bd 100644 --- a/src/utils/transfers/crossChain/index.ts +++ b/src/utils/transfers/crossChain/index.ts @@ -39,20 +39,16 @@ export async function coretimeToRegionXTransfer( const feeAssetItem = 0; const weightLimit = 'Unlimited'; - const reserveTransfer = - coretimeApi.tx.polkadotXcm.limitedReserveTransferAssets( - versionWrap(RegionXChain), - versionWrap(beneficiary), - versionWrap([ - fungibleAsset(RcTokenFromParachainPerspective, '2500000000'), // Fee payment asset - nonFungibleAsset( - CoretimeRegionFromCoretimePerspective, - rawRegionId.toString() - ), - ]), - feeAssetItem, - weightLimit - ); + const reserveTransfer = coretimeApi.tx.polkadotXcm.limitedReserveTransferAssets( + versionWrap(RegionXChain), + versionWrap(beneficiary), + versionWrap([ + fungibleAsset(RcTokenFromParachainPerspective, '2500000000'), // Fee payment asset + nonFungibleAsset(CoretimeRegionFromCoretimePerspective, rawRegionId.toString()), + ]), + feeAssetItem, + weightLimit + ); const { address, signer } = sender; sendTx(reserveTransfer, address, signer, handlers); @@ -85,10 +81,7 @@ export function coretimeFromRegionXTransfer( versionWrap(beneficiary), versionWrap([ fungibleAsset(RcTokenFromParachainPerspective, '2500000000'), // Fee payment asset - nonFungibleAsset( - CoretimeRegionFromRegionXPerspective, - rawRegionId.toString() - ), + nonFungibleAsset(CoretimeRegionFromRegionXPerspective, rawRegionId.toString()), ]), feeAssetItem, weightLimit @@ -190,14 +183,13 @@ export function transferTokensFromRegionXToRelay( const feeAssetItem = 0; const weightLimit = 'Unlimited'; - const teleportTransfer = - regionXApi.tx.polkadotXcm.limitedReserveTransferAssets( - versionWrap(RelayChainFromParachainPerspective), - versionWrap(beneficiary), - versionWrap([fungibleAsset(RcTokenFromParachainPerspective, amount)]), - feeAssetItem, - weightLimit - ); + const teleportTransfer = regionXApi.tx.polkadotXcm.limitedReserveTransferAssets( + versionWrap(RelayChainFromParachainPerspective), + versionWrap(beneficiary), + versionWrap([fungibleAsset(RcTokenFromParachainPerspective, amount)]), + feeAssetItem, + weightLimit + ); const { address, signer } = sender; diff --git a/src/utils/transfers/native/index.ts b/src/utils/transfers/native/index.ts index 7c4ef656..f5d2fe90 100644 --- a/src/utils/transfers/native/index.ts +++ b/src/utils/transfers/native/index.ts @@ -26,10 +26,7 @@ export const transferRegionOnCoretimeChain = async ( newOwner: string, handlers: TxStatusHandlers ) => { - const txTransfer = coretimeApi.tx.broker.transfer( - region.getOnChainRegionId(), - newOwner - ); + const txTransfer = coretimeApi.tx.broker.transfer(region.getOnChainRegionId(), newOwner); sendTx(txTransfer, senderAddress, signer, handlers); }; @@ -41,9 +38,6 @@ export const transferRegionOnRegionXChain = async ( newOwner: string, handlers: TxStatusHandlers ) => { - const txTransfer = regionxApi.tx.regions.transfer( - region.getOnChainRegionId(), - newOwner - ); + const txTransfer = regionxApi.tx.regions.transfer(region.getOnChainRegionId(), newOwner); sendTx(txTransfer, senderAddress, signer, handlers); };