linting fixes

This commit is contained in:
Mark Sinclair
2022-03-10 11:48:57 +00:00
parent 05a9c24437
commit f249e7b497
22 changed files with 178 additions and 211 deletions
+1
View File
@@ -8,6 +8,7 @@
"webpack:prod": "yarn webpack --progress --config webpack.prod.js",
"tauri:dev": "yarn tauri dev",
"tauri:build": "yarn tauri build",
"tsc": "tsc --noEmit true",
"dev": "yarn run webpack:dev & yarn run tauri:dev",
"build": "run-s webpack:prod tauri:build",
"lint": "eslint src",
@@ -3,17 +3,51 @@ import { Box, Button, CircularProgress, Grid, LinearProgress, Stack, TextField,
import { PercentOutlined } from '@mui/icons-material';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import { InfoTooltip } from '../../components/InfoToolTip';
import { Fee, InfoTooltip } from '../../components';
import { InclusionProbabilityResponse, TMixnodeBondDetails } from '../../types';
import { validationSchema } from './validationSchema';
import { updateMixnode } from '../../requests';
import { ClientContext } from '../../context/main';
import { Fee } from '../../components';
type TFormData = {
profitMarginPercent: number;
};
const DataField = ({ title, info, Indicator }: { title: string; info: string; Indicator: React.ReactElement }) => (
<Grid container justifyContent="space-between">
<Grid item xs={12} md={6}>
<Box display="flex" alignItems="center">
<InfoTooltip title={info} tooltipPlacement="right" />
<Typography sx={{ ml: 1 }}>{title}</Typography>
</Box>
</Grid>
<Grid item xs={12} md={6}>
<Box display="flex" justifyContent="flex-end">
{Indicator}
</Box>
</Grid>
</Grid>
);
const PercentIndicator = ({ value, warning }: { value: number; warning?: boolean }) => (
<Grid container alignItems="center">
<Grid item xs={2}>
<Typography component="span" sx={{ color: warning ? 'error.main' : 'nym.fee', fontWeight: 600 }}>
{value}%
</Typography>
</Grid>
<Grid item xs={10}>
<LinearProgress
color="inherit"
sx={{ color: warning ? 'error.main' : 'nym.fee' }}
variant="determinate"
value={value < 100 ? value : 100}
/>
</Grid>
</Grid>
);
export const SystemVariables = ({
mixnodeDetails,
saturation,
@@ -127,38 +161,3 @@ export const SystemVariables = ({
</>
);
};
const DataField = ({ title, info, Indicator }: { title: string; info: string; Indicator: React.ReactElement }) => (
<Grid container justifyContent="space-between">
<Grid item xs={12} md={6}>
<Box display="flex" alignItems="center">
<InfoTooltip title={info} tooltipPlacement="right" />
<Typography sx={{ ml: 1 }}>{title}</Typography>
</Box>
</Grid>
<Grid item xs={12} md={6}>
<Box display="flex" justifyContent="flex-end">
{Indicator}
</Box>
</Grid>
</Grid>
);
const PercentIndicator = ({ value, warning }: { value: number; warning?: boolean }) => (
<Grid container alignItems="center">
<Grid item xs={2}>
<Typography component="span" sx={{ color: warning ? 'error.main' : 'nym.fee', fontWeight: 600 }}>
{value}%
</Typography>
</Grid>
<Grid item xs={10}>
<LinearProgress
color="inherit"
sx={{ color: warning ? 'error.main' : 'nym.fee' }}
variant="determinate"
value={value < 100 ? value : 100}
/>
</Grid>
</Grid>
);
+1 -2
View File
@@ -1,6 +1,5 @@
import React from 'react';
import { Box } from '@mui/system';
import { Tab, Tabs as MuiTabs } from '@mui/material';
import { Tab, Tabs as MuiTabs, Box } from '@mui/material';
export const Tabs: React.FC<{
tabs: string[];
@@ -21,30 +21,32 @@ export const useSettingsState = (shouldUpdate: boolean) => {
const { mixnodeDetails } = useContext(ClientContext);
const getStatus = async (mixnodeKey: string) => {
const status = await getMixnodeStatus(mixnodeKey);
setStatus(status.status);
const newStatus = await getMixnodeStatus(mixnodeKey);
setStatus(newStatus.status);
};
const getStakeSaturation = async (mixnodeKey: string) => {
const saturation = await getMixnodeStakeSaturation(mixnodeKey);
const newSaturation = await getMixnodeStakeSaturation(mixnodeKey);
if (saturation) {
setSaturation(Math.round(saturation.saturation * 100));
if (newSaturation) {
setSaturation(Math.round(newSaturation.saturation * 100));
}
};
const getRewardEstimation = async (mixnodeKey: string) => {
const rewardEstimation = await getMixnodeRewardEstimation(mixnodeKey);
if (rewardEstimation) {
const toMajor = await minorToMajor(rewardEstimation.estimated_total_node_reward.toString());
setRewardEstimation(parseInt(toMajor.amount));
const newRewardEstimation = await getMixnodeRewardEstimation(mixnodeKey);
if (newRewardEstimation) {
const toMajor = await minorToMajor(newRewardEstimation.estimated_total_node_reward.toString());
setRewardEstimation(parseInt(toMajor.amount, Number(10)));
}
};
const getMixnodeInclusionProbability = async (mixnodeKey: string) => {
const probability = await getInclusionProbability(mixnodeKey);
if (probability) {
// eslint-disable-next-line @typescript-eslint/naming-convention
const in_active = Math.round(probability.in_active * 100);
// eslint-disable-next-line @typescript-eslint/naming-convention
const in_reserve = Math.round(probability.in_reserve * 100);
setInclusionProbability({ in_active, in_reserve });
}
+1 -1
View File
@@ -54,7 +54,7 @@ export const Unbond = () => {
</>
) : (
<Alert severity="info" sx={{ m: 3 }} data-testid="no-bond">
You don't currently have a bonded node
You do not currently have a bonded node
</Alert>
)}
{isLoading && (
@@ -1,6 +1,6 @@
import React, { useContext, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { Box, Autocomplete, Button, CircularProgress, FormControl, Grid, TextField, Typography } from '@mui/material';
import { Controller, useForm } from 'react-hook-form';
import { Autocomplete, Box, Button, CircularProgress, FormControl, Grid, TextField } from '@mui/material';
import { yupResolver } from '@hookform/resolvers/yup';
import { validationSchema } from './validationSchema';
import { EnumNodeType, TDelegation, TFee } from '../../types';
@@ -19,7 +19,6 @@ const defaultValues = {
};
export const UndelegateForm = ({
fees,
delegations,
onError,
onSuccess,
+9 -10
View File
@@ -1,8 +1,7 @@
import React, { useContext, useEffect, useState } from 'react';
import { Alert, AlertTitle, Box, Button, CircularProgress } from '@mui/material';
import { NymCard } from '../../components';
import { EnumRequestStatus, NymCard, RequestStatus } from '../../components';
import { UndelegateForm } from './UndelegateForm';
import { EnumRequestStatus, RequestStatus } from '../../components/RequestStatus';
import { getGasFee, getReverseMixDelegations } from '../../requests';
import { TFee, TPagedDelegations } from '../../types';
import { ClientContext } from '../../context/main';
@@ -17,10 +16,6 @@ export const Undelegate = () => {
const { clientDetails } = useContext(ClientContext);
useEffect(() => {
initialize();
}, [clientDetails]);
const initialize = async () => {
setStatus(EnumRequestStatus.initial);
setIsLoading(true);
@@ -44,6 +39,10 @@ export const Undelegate = () => {
setIsLoading(false);
};
useEffect(() => {
initialize();
}, [clientDetails]);
return (
<PageLayout>
<NymCard title="Undelegate" subheader="Undelegate from a mixnode" noPadding>
@@ -63,12 +62,12 @@ export const Undelegate = () => {
<UndelegateForm
fees={fees}
delegations={pagedDelegations?.delegations}
onError={(message) => {
setMessage(message);
onError={(m) => {
setMessage(m);
setStatus(EnumRequestStatus.error);
}}
onSuccess={(message) => {
setMessage(message);
onSuccess={(m) => {
setMessage(m);
setStatus(EnumRequestStatus.success);
}}
/>
@@ -4,9 +4,7 @@ import { createAccount } from '../../requests';
import { TCreateAccount } from '../../types';
import { CopyToClipboard } from '../../components';
export const CreateAccountContent: React.FC<{ page: 'legacy create account'; showSignIn: () => void }> = ({
showSignIn,
}) => {
export const CreateAccountContent: React.FC<{ showSignIn: () => void }> = ({ showSignIn }) => {
const [accountDetails, setAccountDetails] = useState<TCreateAccount>();
const [error, setError] = useState<Error>();
@@ -33,7 +31,7 @@ export const CreateAccountContent: React.FC<{ page: 'legacy create account'; sho
Account setup complete!
</Typography>
<Alert severity="info" variant="outlined" sx={{ color: 'info.light' }} data-testid="mnemonic-warning">
<Typography>Please store your mnemonic in a safe place. You'll need it to access your account!</Typography>
<Typography>Please store your mnemonic in a safe place. You will need it to access your account!</Typography>
</Alert>
<Card variant="outlined" sx={{ bgcolor: 'transparent', p: 2, borderColor: 'common.white' }}>
<CardHeader sx={{ color: 'common.white' }} title="Mnemonic" />
@@ -1,12 +1,10 @@
import React, { useContext, useState } from 'react';
import { Button, CircularProgress, Grid, Stack, TextField, Typography, Alert } from '@mui/material';
import { styled } from '@mui/material/styles';
import { signInWithMnemonic } from '../../requests';
import { Alert, Button, CircularProgress, Grid, Stack, Typography } from '@mui/material';
import { ClientContext } from '../../context/main';
import { NymLogo } from '../../components';
export const SignInContent: React.FC<{ showCreateAccount: () => void }> = ({ showCreateAccount }) => {
const [mnemonic, setMnemonic] = useState<string>('');
export const SignInContent: React.FC = () => {
const [mnemonic] = useState<string>('');
const [inputError, setInputError] = useState<string>();
const [isLoading, setIsLoading] = useState(false);
@@ -19,12 +17,11 @@ export const SignInContent: React.FC<{ showCreateAccount: () => void }> = ({ sho
setInputError(undefined);
try {
await signInWithMnemonic(mnemonic || '');
await logIn(mnemonic || '');
setIsLoading(false);
logIn();
} catch (e: any) {
} catch (error: any) {
setIsLoading(false);
setInputError(e);
setInputError(error);
}
};
@@ -67,23 +64,3 @@ export const SignInContent: React.FC<{ showCreateAccount: () => void }> = ({ sho
</Stack>
);
};
const StyledInput = styled((props) => <TextField {...props} />)(({ theme }) => ({
'& input': {
color: theme.palette.nym.text.light,
},
'& label': {
color: theme.palette.nym.text.light,
},
'& label.Mui-focused': {
color: theme.palette.primary.main,
},
'& .MuiOutlinedInput-root': {
'& fieldset': {
borderColor: theme.palette.common.white,
},
'&:hover fieldset': {
borderColor: theme.palette.primary.main,
},
},
}));
@@ -1,11 +1,10 @@
import React, { useEffect, useState } from 'react';
import { LockOutlined } from '@mui/icons-material';
import { LinearProgress, Stack, Typography } from '@mui/material';
import { Box } from '@mui/system';
import { LinearProgress, Stack, Typography, Box } from '@mui/material';
type TStrength = 'weak' | 'medium' | 'strong' | 'init';
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/;
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/;
const medium = /^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})/;
const colorMap = {
@@ -46,15 +45,18 @@ export const PasswordStrength = ({ password }: { password: string }) => {
useEffect(() => {
if (password.length === 0) {
return setStrength('init');
setStrength('init');
return;
}
if (password.match(strong)) {
return setStrength('strong');
setStrength('strong');
return;
}
if (password.match(medium)) {
return setStrength('medium');
setStrength('medium');
return;
}
setStrength('weak');
}, [password]);
@@ -2,35 +2,6 @@ import React from 'react';
import { Box, Card, CardHeader, Grid, Typography, Stack, Fade } from '@mui/material';
import { THiddenMnemonicWord, THiddenMnemonicWords, TMnemonicWords } from '../types';
export const WordTiles = ({
mnemonicWords,
showIndex,
onClick,
}: {
mnemonicWords?: TMnemonicWords;
showIndex?: boolean;
onClick?: ({ name, index }: { name: string; index: number }) => void;
}) => {
if (mnemonicWords) {
return (
<Grid container spacing={3} justifyContent="center">
{mnemonicWords.map(({ name, index, disabled }) => (
<Grid item xs={2} key={index} onClick={() => onClick?.({ name, index })}>
<WordTile
mnemonicWord={name}
index={showIndex ? index : undefined}
onClick={!!onClick}
disabled={disabled}
/>
</Grid>
))}
</Grid>
);
}
return null;
};
export const WordTile = ({
mnemonicWord,
index,
@@ -65,18 +36,32 @@ export const WordTile = ({
</Card>
);
export const HiddenWords = ({ mnemonicWords }: { mnemonicWords?: THiddenMnemonicWords }) => {
export const WordTiles = ({
mnemonicWords,
showIndex,
onClick,
}: {
mnemonicWords?: TMnemonicWords;
showIndex?: boolean;
onClick?: ({ name, index }: { name: string; index: number }) => void;
}) => {
if (mnemonicWords) {
return (
<Grid container spacing={3} justifyContent="center">
{mnemonicWords.map((mnemonicWord) => (
<Grid item xs={2} key={mnemonicWord.index}>
<HiddenWord mnemonicWord={mnemonicWord} />
{mnemonicWords.map(({ name, index, disabled }) => (
<Grid item xs={2} key={index} onClick={() => onClick?.({ name, index })}>
<WordTile
mnemonicWord={name}
index={showIndex ? index : undefined}
onClick={!!onClick}
disabled={disabled}
/>
</Grid>
))}
</Grid>
);
}
return null;
};
@@ -92,3 +77,18 @@ const HiddenWord = ({ mnemonicWord }: { mnemonicWord: THiddenMnemonicWord }) =>
<Typography>{mnemonicWord.index}.</Typography>
</Stack>
);
export const HiddenWords = ({ mnemonicWords }: { mnemonicWords?: THiddenMnemonicWords }) => {
if (mnemonicWords) {
return (
<Grid container spacing={3} justifyContent="center">
{mnemonicWords.map((mnemonicWord) => (
<Grid item xs={2} key={mnemonicWord.index}>
<HiddenWord mnemonicWord={mnemonicWord} />
</Grid>
))}
</Grid>
);
}
return null;
};
+12 -14
View File
@@ -1,24 +1,23 @@
import React, { useContext, useState } from 'react';
import { Box } from '@mui/system';
import { CircularProgress, Stack } from '@mui/material';
import { WelcomeContent, VerifyMnemonic, MnemonicWords, CreatePassword, ExistingAccount } from './pages';
import { CircularProgress, Stack, Box } from '@mui/material';
import { ExistingAccount, WelcomeContent } from './pages';
import { NymLogo } from '../../components';
import { TMnemonicWords, TPages } from './types';
import { TPages } from './types';
import { RenderPage } from './components';
import { CreateAccountContent } from './_legacy_create-account';
import { ClientContext } from '../../context/main';
const testMnemonic =
'futuristic big receptive caption saw hug odd spoon internal dime bike rake helpless left distribution gusty eyes beg enormous word influence trashy pets curl';
const mnemonicToArray = (mnemonic: string): TMnemonicWords =>
mnemonic
.split(' ')
.reduce((a, c: string, index) => [...a, { name: c, index: index + 1, disabled: false }], [] as TMnemonicWords);
// const testMnemonic =
// 'futuristic big receptive caption saw hug odd spoon internal dime bike rake helpless left distribution gusty eyes beg enormous word influence trashy pets curl';
//
// const mnemonicToArray = (mnemonic: string): TMnemonicWords =>
// mnemonic
// .split(' ')
// .reduce((a, c: string, index) => [...a, { name: c, index: index + 1, disabled: false }], [] as TMnemonicWords);
export const Welcome = () => {
const [page, setPage] = useState<TPages>('welcome');
const [mnemonicWords, setMnemonicWords] = useState<TMnemonicWords>();
// const [mnemonicWords, setMnemonicWords] = useState<TMnemonicWords>();
const { isLoading } = useContext(ClientContext);
@@ -56,7 +55,6 @@ export const Welcome = () => {
<WelcomeContent
onUseExisting={() => setPage('existing account')}
onCreateAccountComplete={() => setPage('legacy create account')}
page="welcome"
/>
<CreateAccountContent page="legacy create account" showSignIn={() => setPage('existing account')} />
@@ -72,7 +70,7 @@ export const Welcome = () => {
page="verify mnemonic"
/>
<CreatePassword page="create password" /> */}
<ExistingAccount page="existing account" onPrev={() => setPage('welcome')} />
<ExistingAccount onPrev={() => setPage('welcome')} />
</RenderPage>
</Stack>
)}
@@ -3,7 +3,7 @@ import { Button, FormControl, Grid, IconButton, Stack, TextField } from '@mui/ma
import { VisibilityOff, Visibility } from '@mui/icons-material';
import { Subtitle, Title, PasswordStrength } from '../components';
export const CreatePassword = ({}: { page: 'create password' }) => {
export const CreatePassword = () => {
const [password, setPassword] = useState<string>('');
const [confirmedPassword, setConfirmedPassword] = useState<string>();
const [showPassword, setShowPassword] = useState(false);
@@ -3,7 +3,7 @@ import { Alert, Button, Stack, TextField } from '@mui/material';
import { Subtitle } from '../components';
import { ClientContext } from '../../../context/main';
export const ExistingAccount: React.FC<{ page: 'existing account'; onPrev: () => void }> = ({ onPrev }) => {
export const ExistingAccount: React.FC<{ onPrev: () => void }> = ({ onPrev }) => {
const [mnemonic, setMnemonic] = useState<string>('');
const { logIn, error } = useContext(ClientContext);
@@ -1,6 +1,6 @@
import React from 'react';
import { Alert, Button, Typography } from '@mui/material';
import { WordTiles } from '../components/word-tiles';
import { WordTiles } from '../components';
import { TMnemonicWords } from '../types';
export const MnemonicWords = ({
@@ -9,7 +9,6 @@ export const MnemonicWords = ({
onPrev,
}: {
mnemonicWords?: TMnemonicWords;
page: 'create account';
onNext: () => void;
onPrev: () => void;
}) => (
@@ -1,9 +1,8 @@
import React, { useEffect, useState } from 'react';
import { Button } from '@mui/material';
import { WordTiles, HiddenWords } from '../components/word-tiles';
import { THiddenMnemonicWords, THiddenMnemonicWord, TMnemonicWord, TMnemonicWords } from '../types';
import { HiddenWords, Subtitle, Title, WordTiles } from '../components';
import { THiddenMnemonicWord, THiddenMnemonicWords, TMnemonicWord, TMnemonicWords } from '../types';
import { randomNumberBetween } from '../../../utils';
import { Title, Subtitle } from '../components';
const numberOfRandomWords = 4;
@@ -11,7 +10,6 @@ export const VerifyMnemonic = ({
mnemonicWords,
onComplete,
}: {
page: 'verify mnemonic';
mnemonicWords?: TMnemonicWords;
onComplete: () => void;
}) => {
@@ -21,10 +19,10 @@ export const VerifyMnemonic = ({
useEffect(() => {
if (mnemonicWords) {
const randomWords = getRandomEntriesFromArray<TMnemonicWord>(mnemonicWords, numberOfRandomWords);
const withHiddenProperty = randomWords.map((word) => ({ ...word, hidden: true }));
const newRandomWords = getRandomEntriesFromArray<TMnemonicWord>(mnemonicWords, numberOfRandomWords);
const withHiddenProperty = newRandomWords.map((word) => ({ ...word, hidden: true }));
const shuffled = getRandomEntriesFromArray<THiddenMnemonicWord>(withHiddenProperty, numberOfRandomWords);
setRandomWords(randomWords);
setRandomWords(newRandomWords);
setHiddenRandomWords(shuffled);
}
}, [mnemonicWords]);
@@ -34,8 +32,8 @@ export const VerifyMnemonic = ({
setHiddenRandomWords((hiddenWords) =>
hiddenWords?.map((word) => (word.name === name ? { ...word, hidden: false } : word)),
);
setRandomWords((randomWords) =>
randomWords?.map((word) => (word.name === name ? { ...word, disabled: true } : word)),
setRandomWords((argRandomWords) =>
argRandomWords?.map((word) => (word.name === name ? { ...word, disabled: true } : word)),
);
setCurrentSelection((current) => current + 1);
}
@@ -3,7 +3,6 @@ import { Button, Stack } from '@mui/material';
import { SubtitleSlick, Title } from '../components';
export const WelcomeContent: React.FC<{
page: 'welcome';
onUseExisting: () => void;
onCreateAccountComplete: () => void;
}> = ({ onUseExisting, onCreateAccountComplete }) => (
+1 -1
View File
@@ -1,6 +1,6 @@
import { invoke } from '@tauri-apps/api';
import { VestingAccountInfo } from 'src/types/rust/vestingaccountinfo';
import { majorToMinor, minorToMajor } from '.';
import { majorToMinor, minorToMajor } from './coin';
import { Coin, DelegationResult, OriginalVestingResponse, Period } from '../types';
export const getLockedCoins = async (address: string): Promise<Coin> => {
+2 -2
View File
@@ -1,13 +1,13 @@
import React from 'react';
import { SvgIcon, SvgIconProps } from '@mui/material';
export const Node = (props: SvgIconProps) => (
export const Node: React.FC<SvgIconProps> = ({ color, ...props }) => (
<SvgIcon {...props}>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M18.9536 6.99307L12 3.05788L5.04641 6.99304L11.5144 10.5864C11.8164 10.7542 12.1837 10.7542 12.4857 10.5864L18.9536 6.99307ZM19.9005 8.75493L13.457 12.3347C13.3093 12.4167 13.1564 12.4854 13 12.5407V20.3762L19.9005 16.4711V8.75493ZM11 12.5407C10.8436 12.4854 10.6908 12.4167 10.5431 12.3347L4.09946 8.75488V16.4711L11 20.3762V12.5407ZM13.0497 1.2757C12.4002 0.908099 11.5998 0.908099 10.9503 1.2757L3.04973 5.74676C2.40015 6.11437 2 6.79373 2 7.52894V16.4711C2 17.2063 2.40015 17.8856 3.04973 18.2532L10.9503 22.7243C11.5998 23.0919 12.4002 23.0919 13.0497 22.7243L20.9503 18.2532C21.5998 17.8856 22 17.2063 22 16.4711V7.52894C22 6.79373 21.5998 6.11437 20.9503 5.74676L13.0497 1.2757Z"
fill={props.color}
fill={color}
/>
</SvgIcon>
);
+1 -1
View File
@@ -65,7 +65,7 @@ const lightMode: NymPaletteVariant = {
* IMPORTANT: do not export this constant, always use the MUI `useTheme` hook to get the correct
* colours for dark/light mode.
*/
const nymWalletPalette = (variant: NymPaletteVariant): NymWalletPalette => ({
const nymWalletPalette = (_variant: NymPaletteVariant): NymWalletPalette => ({
nymWallet: {},
});
+1 -1
View File
@@ -1,4 +1,4 @@
import { Coin, Denom, MixNode } from '.';
import { Coin, Denom, MixNode } from './rust';
export enum EnumNodeType {
mixnode = 'mixnode',
+41 -44
View File
@@ -2,8 +2,8 @@ import { invoke } from '@tauri-apps/api';
import { appWindow } from '@tauri-apps/api/window';
import bs58 from 'bs58';
import { minor, valid } from 'semver';
import { userBalance, majorToMinor, getGasFee } from '../requests';
import { Coin, Network, Period, TCurrency } from '../types';
import { majorToMinor, userBalance } from '../requests';
import { Coin, Network, TCurrency } from '../types';
export const validateKey = (key: string, bytesLength: number): boolean => {
// it must be a valid base58 key
@@ -17,6 +17,23 @@ export const validateKey = (key: string, bytesLength: number): boolean => {
}
};
export const basicRawCoinValueValidation = (rawAmount: string): boolean => {
const amountFloat = parseFloat(rawAmount);
// it cannot have more than 6 decimal places
if (amountFloat !== parseInt(amountFloat.toFixed(6), Number(10))) {
return false;
}
// it cannot be larger than the total supply
if (amountFloat > 1_000_000_000_000_000) {
return false;
}
// it can't be lower than one micro coin
return amountFloat >= 0.000001;
};
export const validateAmount = async (amount: string, minimum: string): Promise<boolean> => {
// tests basic coin value requirements, like no more than 6 decimal places, value lower than total supply, etc
if (!Number(amount)) {
@@ -32,34 +49,17 @@ export const validateAmount = async (amount: string, minimum: string): Promise<b
return false;
}
const minorValue = parseInt(minorValueStr.amount);
const minorValue = parseInt(minorValueStr.amount, Number(10));
return minorValue >= parseInt(minimum);
return minorValue >= parseInt(minimum, Number(10));
} catch (e) {
console.log(e);
console.error(e);
return false;
}
// this conversion seems really iffy but I'm not sure how to better approach it
};
export const basicRawCoinValueValidation = (rawAmount: string): boolean => {
const amountFloat = parseFloat(rawAmount);
// it cannot have more than 6 decimal places
if (amountFloat !== parseInt(amountFloat.toFixed(6))) {
return false;
}
// it cannot be larger than the total supply
if (amountFloat > 1_000_000_000_000_000) {
return false;
}
// it can't be lower than one micro coin
return amountFloat >= 0.000001;
};
export const isValidHostname = (value: string) => {
// regex for ipv4 and ipv6 and hhostname- source http://jsfiddle.net/DanielD/8S4nq/
const hostnameRegex =
@@ -82,55 +82,52 @@ export const validateLocation = (location: string): boolean =>
// right now only perform the stupid check of whether the user copy-pasted the tooltip... (with or without brackets)
!location.trim().includes('physical location of your node');
export const validateRawPort = (rawPort: number): boolean => !isNaN(rawPort) && rawPort >= 1 && rawPort <= 65535;
export const validateRawPort = (rawPort: number): boolean => !Number.isNaN(rawPort) && rawPort >= 1 && rawPort <= 65535;
export const truncate = (text: string, trim: number) => `${text.substring(0, trim)}...`;
export const isGreaterThan = (a: number, b: number) => a > b;
export const checkHasEnoughFunds = async (allocationValue: string) => {
export const checkHasEnoughFunds = async (allocationValue: string): Promise<boolean> => {
try {
const walletValue = await userBalance();
const minorValue = await majorToMinor(allocationValue);
const remainingBalance = +walletValue.coin.amount - +minorValue.amount;
return isGreaterThan(remainingBalance, 0);
} catch (e) {
console.log(e);
console.error(e);
}
return false;
};
export const randomNumberBetween = (min: number, max: number) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
const minCeil = Math.ceil(min);
const maxFloor = Math.floor(max);
return Math.floor(Math.random() * (maxFloor - minCeil + 1) + minCeil);
};
export const currencyMap = (network?: Network) => {
const currency = {
minor: 'UNYM',
major: 'NYM',
} as TCurrency;
export const currencyMap = (network?: Network): TCurrency => {
switch (network) {
case 'MAINNET':
currency.minor = 'UNYM';
currency.major = 'NYM';
break;
case 'SANDBOX':
currency.minor = 'UNYMT';
currency.major = 'NYMT';
break;
return {
minor: 'UNYM',
major: 'NYM',
};
default:
return {
minor: 'UNYMT',
major: 'NYMT',
};
}
return currency;
};
export const splice = (start: number, deleteCount: number, address?: string) => {
export const splice = (start: number, deleteCount: number, address?: string): string => {
if (address) {
const array = address.split('');
array.splice(start, deleteCount, '...');
return array.join('');
}
return '';
};
export const maximizeWindow = async () => {