linting, conflict fixes, and general tidy

This commit is contained in:
fmtabbara
2022-03-13 01:20:46 +00:00
parent 51bced8766
commit 47ffdfe496
33 changed files with 212 additions and 144 deletions
@@ -29,14 +29,13 @@ pub async fn locked_coins(
#[tauri::command]
pub async fn spendable_coins(
vesting_account_address: &str,
block_time: Option<u64>,
state: tauri::State<'_, Arc<RwLock<State>>>,
) -> Result<Coin, BackendError> {
Ok(
nymd_client!(state)
.spendable_coins(
vesting_account_address,
&nymd_client!(state).address().to_string(),
block_time.map(Timestamp::from_seconds),
)
.await?
@@ -39,7 +39,12 @@ export const TokenPoolSelector: React.FC<{ onSelect: (pool: TPoolOption) => void
/>
</MenuItem>
<MenuItem value="locked">
<ListItemText primary="Locked" secondary={`${tokenAllocation?.locked} ${currency?.major}`} />
{tokenAllocation && (
<ListItemText
primary="Locked"
secondary={`${+tokenAllocation.locked + +tokenAllocation.spendable} ${currency?.major}`}
/>
)}
</MenuItem>
</Select>
</FormControl>
-1
View File
@@ -13,6 +13,5 @@ export * from './AppBar';
export * from './NetworkSelector';
export * from './ClientAddress';
export * from './InfoToolTip';
export * from './Nav';
export * from './Title';
export * from './TokenPoolSelector';
+3 -4
View File
@@ -1,12 +1,11 @@
import React, { createContext, useEffect, useState } from 'react';
import React, { useMemo, createContext, useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { useSnackbar } from 'notistack';
import { Account, Network, TCurrency, TMixnodeBondDetails } from '../types';
import { TUseuserBalance, useGetBalance } from '../hooks/useGetBalance';
import { config } from '../../config';
import { getMixnodeBondDetails, selectNetwork, signInWithMnemonic, signOut } from '../requests';
import { currencyMap } from '../utils';
import { useHistory } from 'react-router-dom';
import { useSnackbar } from 'notistack';
import { useMemo } from 'react';
export const { ADMIN_ADDRESS, IS_DEV_MODE } = config;
+1 -1
View File
@@ -1,7 +1,7 @@
import { useCallback, useContext, useEffect, useState } from 'react';
import { ClientContext } from '../context/main';
import { checkGatewayOwnership, checkMixnodeOwnership, getVestingPledgeInfo } from '../requests';
import { EnumNodeType, TNodeOwnership, PledgeData } from '../types';
import { EnumNodeType, TNodeOwnership } from '../types';
const initial = {
hasOwnership: false,
+4 -4
View File
@@ -60,7 +60,7 @@ export const useGetBalance = (address?: string): TUseuserBalance => {
getVestingCoins(address),
getVestedCoins(address),
getLockedCoins(),
getSpendableCoins(address),
getSpendableCoins(),
getCurrentVestingPeriod(address),
getVestingAccountInfo(address),
]);
@@ -103,10 +103,10 @@ export const useGetBalance = (address?: string): TUseuserBalance => {
clearOriginalVesting();
};
const handleRefresh = (addr?: string) => {
const handleRefresh = async (addr?: string) => {
if (addr) {
fetchBalance();
fetchTokenAllocation();
await fetchBalance();
await fetchTokenAllocation();
} else {
clearAll();
}
+1 -2
View File
@@ -6,10 +6,9 @@ import { SnackbarProvider } from 'notistack';
import { Routes } from './routes';
import { ClientContext, ClientContextProvider } from './context/main';
import { ApplicationLayout } from './layouts';
import { Admin, Welcome } from './pages';
import { Admin, Welcome, Settings } from './pages';
import { ErrorFallback } from './components';
import { NymWalletTheme, WelcomeTheme } from './theme';
import { Settings } from './pages';
import { maximizeWindow } from './utils';
const App = () => {
+1 -1
View File
@@ -1,7 +1,7 @@
import React from 'react';
import { NymLogo } from '@nymproject/react';
import { Box, Container } from '@mui/material';
import { AppBar, Nav } from '../components';
import { NymLogo } from '@nymproject/react';
export const ApplicationLayout: React.FC = ({ children }) => (
<Box
@@ -45,7 +45,7 @@ export const VestingTimeline: React.FC<{ percentageComplete: number }> = ({ perc
tooltipText="End of vesting schedule"
/>
</svg>
{nextPeriod && (
{!!nextPeriod && (
<Typography variant="caption" sx={{ color: 'grey.500', position: 'absolute', top: 15, left: 0 }}>
Next vesting period: {format(new Date(nextPeriod * 1000), 'HH:mm do MMM yyyy')}
</Typography>
+1 -1
View File
@@ -120,9 +120,9 @@ const TokenTransfer = () => {
};
export const VestingCard = () => {
const { userBalance } = useContext(ClientContext);
const [isLoading, setIsLoading] = useState(false);
const { userBalance } = useContext(ClientContext);
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const refreshBalances = async () => {
+1 -1
View File
@@ -1,5 +1,5 @@
import React, { useContext } from 'react';
import { Box } from '@mui/system';
import { Box } from '@mui/material';
import { SuccessReponse, TransactionDetails } from '../../components';
import { ClientContext } from '../../context/main';
import { useCheckOwnership } from '../../hooks/useCheckOwnership';
+4 -2
View File
@@ -1,5 +1,6 @@
import React, { useEffect, useState } from 'react';
import { Alert, Box, Button, CircularProgress } from '@mui/material';
import { useSnackbar } from 'notistack';
import { BondForm } from './BondForm';
import { SuccessView } from './SuccessView';
import { NymCard } from '../../components';
@@ -7,7 +8,6 @@ import { EnumRequestStatus, RequestStatus } from '../../components/RequestStatus
import { unbond, vestingUnbond } from '../../requests';
import { useCheckOwnership } from '../../hooks/useCheckOwnership';
import { PageLayout } from '../../layouts';
import { useSnackbar } from 'notistack';
export const Bond = () => {
const [status, setStatus] = useState(EnumRequestStatus.initial);
@@ -19,7 +19,9 @@ export const Bond = () => {
useEffect(() => {
if (status === EnumRequestStatus.initial) {
const initialiseForm = async () => await checkOwnership();
const initialiseForm = async () => {
await checkOwnership();
};
initialiseForm();
}
}, [status, checkOwnership]);
+18 -35
View File
@@ -13,21 +13,15 @@ import {
export const validationSchema = Yup.object().shape({
identityKey: Yup.string()
.required('An indentity key is required')
.test('valid-id-key', 'A valid identity key is required', function (value) {
return validateKey(value || '', 32);
}),
.test('valid-id-key', 'A valid identity key is required', (value) => validateKey(value || '', 32)),
sphinxKey: Yup.string()
.required('A sphinx key is required')
.test('valid-sphinx-key', 'A valid sphinx key is required', function (value) {
return validateKey(value || '', 32);
}),
.test('valid-sphinx-key', 'A valid sphinx key is required', (value) => validateKey(value || '', 32)),
ownerSignature: Yup.string()
.required('Signature is required')
.test('valid-signature', 'A valid signature is required', function (value) {
return validateKey(value || '', 64);
}),
.test('valid-signature', 'A valid signature is required', (value) => validateKey(value || '', 64)),
profitMarginPercent: Yup.number().required('Profit Percentage is required').min(0).max(100),
@@ -37,17 +31,16 @@ export const validationSchema = Yup.object().shape({
const isValid = await validateAmount(value || '', '100000000');
if (!isValid) {
return this.createError({ message: `A valid amount is required (min 100)` });
} else {
const hasEnoughBalance = await checkHasEnoughFunds(value || '');
const hasEnoughLocked = await checkHasEnoughLockedTokens(value || '');
if (this.parent.tokenPool === 'balance' && !hasEnoughBalance) {
return this.createError({ message: 'Not enough funds in wallet' });
}
return this.createError({ message: 'A valid amount is required (min 100)' });
}
const hasEnoughBalance = await checkHasEnoughFunds(value || '');
const hasEnoughLocked = await checkHasEnoughLockedTokens(value || '');
if (this.parent.tokenPool === 'balance' && !hasEnoughBalance) {
return this.createError({ message: 'Not enough funds in wallet' });
}
if (this.parent.tokenPool === 'locked' && !hasEnoughLocked) {
return this.createError({ message: 'Not enough locked tokens' });
}
if (this.parent.tokenPool === 'locked' && !hasEnoughLocked) {
return this.createError({ message: 'Not enough locked tokens' });
}
return true;
@@ -55,18 +48,14 @@ export const validationSchema = Yup.object().shape({
host: Yup.string()
.required('A host is required')
.test('valid-host', 'A valid host is required', function (value) {
return !!value ? isValidHostname(value) : false;
}),
.test('valid-host', 'A valid host is required', (value) => (value ? isValidHostname(value) : false)),
version: Yup.string()
.required('A version is required')
.test('valid-version', 'A valid version is required', function (value) {
return !!value ? validateVersion(value) : false;
}),
.test('valid-version', 'A valid version is required', (value) => (value ? validateVersion(value) : false)),
location: Yup.lazy((value) => {
if (!!value) {
if (value) {
return Yup.string()
.required('A location is required')
.test('valid-location', 'A valid version is required', (locationValueTest) =>
@@ -78,21 +67,15 @@ export const validationSchema = Yup.object().shape({
mixPort: Yup.number()
.required('A mixport is required')
.test('valid-mixport', 'A valid mixport is required', function (value) {
return !!value ? validateRawPort(value) : false;
}),
.test('valid-mixport', 'A valid mixport is required', (value) => (value ? validateRawPort(value) : false)),
verlocPort: Yup.number()
.required('A verloc port is required')
.test('valid-verloc', 'A valid verloc port is required', function (value) {
return !!value ? validateRawPort(value) : false;
}),
.test('valid-verloc', 'A valid verloc port is required', (value) => (value ? validateRawPort(value) : false)),
httpApiPort: Yup.number()
.required('A http-api port is required')
.test('valid-http', 'A valid http-api port is required', function (value) {
return !!value ? validateRawPort(value) : false;
}),
.test('valid-http', 'A valid http-api port is required', (value) => (value ? validateRawPort(value) : false)),
clientsPort: Yup.number()
.required('A clients port is required')
@@ -1,5 +1,5 @@
import React, { useEffect, useContext } from 'react';
import { Box, Button, CircularProgress, FormControl, Grid, InputAdornment, TextField, Typography } from '@mui/material';
import { Box, Button, CircularProgress, FormControl, Grid, InputAdornment, TextField } from '@mui/material';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import { DelegationResult, EnumNodeType, TDelegateArgs } from '../../types';
@@ -16,18 +16,18 @@ export const validationSchema = Yup.object().shape({
const isValid = await validateAmount(value || '', '0');
if (!isValid) {
return this.createError({ message: `A valid amount is required` });
} else {
const hasEnoughBalance = await checkHasEnoughFunds(value || '');
const hasEnoughLocked = await checkHasEnoughLockedTokens(value || '');
return this.createError({ message: 'A valid amount is required' });
}
if (this.parent.tokenPool === 'balance' && !hasEnoughBalance) {
return this.createError({ message: 'Not enough funds in wallet' });
}
const hasEnoughBalance = await checkHasEnoughFunds(value || '');
const hasEnoughLocked = await checkHasEnoughLockedTokens(value || '');
if (this.parent.tokenPool === 'locked' && !hasEnoughLocked) {
return this.createError({ message: 'Not enough locked tokens' });
}
if (this.parent.tokenPool === 'balance' && !hasEnoughBalance) {
return this.createError({ message: 'Not enough funds in wallet' });
}
if (this.parent.tokenPool === 'locked' && !hasEnoughLocked) {
return this.createError({ message: 'Not enough locked tokens' });
}
return true;
+1 -1
View File
@@ -2,7 +2,7 @@ import React, { useContext } from 'react';
import { Grid, InputAdornment, TextField } from '@mui/material';
import { useFormContext } from 'react-hook-form';
import { ClientContext } from '../../context/main';
import { Fee, ClientAddress } from '../../components';
import { Fee } from '../../components';
export const SendForm = () => {
const {
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable no-nested-ternary */
import React, { useEffect, useContext, useState } from 'react';
import { useForm, FormProvider } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
@@ -1,14 +1,15 @@
/* eslint-disable no-nested-ternary */
import React, { useContext, useState } from 'react';
import { Box, Button, CircularProgress, Grid, LinearProgress, Stack, TextField, Typography } from '@mui/material';
import { PercentOutlined } from '@mui/icons-material';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import { validationSchema } from './validationSchema';
import { Fee, InfoTooltip } from '../../components';
import { InclusionProbabilityResponse } from '../../types';
import { validationSchema } from './validationSchema';
import { useCheckOwnership } from '../../hooks/useCheckOwnership';
import { updateMixnode, vestingUpdateMixnode } from '../../requests';
import { ClientContext } from '../../context/main';
import { useCheckOwnership } from 'src/hooks/useCheckOwnership';
const DataField = ({ title, info, Indicator }: { title: string; info: string; Indicator: React.ReactElement }) => (
<Grid container justifyContent="space-between">
@@ -55,7 +56,7 @@ export const SystemVariables = ({
inclusionProbability: InclusionProbabilityResponse;
}) => {
const [nodeUpdateResponse, setNodeUpdateResponse] = useState<'success' | 'failed'>();
const { currency, mixnodeDetails, getBondDetails } = useContext(ClientContext);
const { currency, mixnodeDetails } = useContext(ClientContext);
const { ownership } = useCheckOwnership();
const {
@@ -1,4 +1,4 @@
import React, { useContext } from 'react';
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
import { Box, Autocomplete, Button, CircularProgress, FormControl, Grid, TextField } from '@mui/material';
import { yupResolver } from '@hookform/resolvers/yup';
@@ -1,4 +1,4 @@
/* eslint-disable react/no-unused-prop-types */
/* eslint-disable no-unused-vars */
import React, { useEffect, useState } from 'react';
import { Alert, Button, Card, CardActions, CardContent, CardHeader, Stack, Typography } from '@mui/material';
import { createAccount } from '../../requests';
@@ -25,7 +25,7 @@ export const CreateAccountContent: React.FC<{ page: TPages; showSignIn: () => vo
}, []);
return (
<Stack spacing={4} alignItems="center" sx={{ width: 700 }}>
<Stack spacing={4} alignItems="center" sx={{ width: 700 }} id={page}>
<Typography sx={{ color: 'common.white' }} variant="h4">
Congratulations
</Typography>
@@ -1,7 +1,7 @@
import React, { useContext, useState } from 'react';
import { NymLogo } from '@nymproject/react';
import { Alert, Button, CircularProgress, Grid, Stack, Typography } from '@mui/material';
import { ClientContext } from '../../context/main';
import { NymLogo } from '@nymproject/react';
export const SignInContent: React.FC = () => {
const [mnemonic] = useState<string>('');
@@ -1,3 +1,4 @@
/* eslint-disable no-nested-ternary */
import React, { useEffect, useState } from 'react';
import { LockOutlined } from '@mui/icons-material';
import { LinearProgress, Stack, Typography, Box } from '@mui/material';
+1 -1
View File
@@ -1,7 +1,7 @@
import React, { useContext, useState } from 'react';
import { NymLogo } from '@nymproject/react';
import { CircularProgress, Stack, Box } from '@mui/material';
import { ExistingAccount, WelcomeContent } from './pages';
import { NymLogo } from '@nymproject/react';
import { TPages } from './types';
import { RenderPage } from './components';
import { CreateAccountContent } from './_legacy_create-account';
@@ -10,8 +10,8 @@ export const ExistingAccount: React.FC<{ page: TPages; onPrev: () => void }> = (
const { logIn, error } = useContext(ClientContext);
const handleSignIn = async ({ preventDefault }: React.MouseEvent<HTMLElement>) => {
logIn(mnemonic);
const handleSignIn = async () => {
await logIn(mnemonic);
};
const handleSignInOnEnter = ({ key }: React.KeyboardEvent<HTMLDivElement>) => {
+11 -4
View File
@@ -1,9 +1,16 @@
import { invoke } from '@tauri-apps/api';
import { Account, TCreateAccount } from '../types';
export const createAccount = async (): Promise<TCreateAccount> => invoke('create_new_account');
export const createAccount = async (): Promise<TCreateAccount> => {
const res: TCreateAccount = await invoke('create_new_account');
return res;
};
export const signInWithMnemonic = async (mnemonic: string): Promise<Account> =>
invoke('connect_with_mnemonic', { mnemonic });
export const signInWithMnemonic = async (mnemonic: string): Promise<Account> => {
const res: Account = await invoke('connect_with_mnemonic', { mnemonic });
return res;
};
export const signOut = async () => invoke('logout');
export const signOut = async (): Promise<void> => {
await invoke('logout');
};
+18 -8
View File
@@ -1,10 +1,13 @@
import { invoke } from '@tauri-apps/api';
import { Coin, DelegationResult, EnumNodeType, Gateway, MixNode, TauriTxResult, TBondArgs } from '../types';
import { Coin, DelegationResult, EnumNodeType, TauriTxResult, TBondArgs } from '../types';
export const bond = async ({ type, data, pledge, ownerSignature }: TBondArgs): Promise<any> =>
export const bond = async ({ type, data, pledge, ownerSignature }: TBondArgs): Promise<any> => {
await invoke(`bond_${type}`, { [type]: data, ownerSignature, pledge });
};
export const unbond = async (type: EnumNodeType) => invoke(`unbond_${type}`);
export const unbond = async (type: EnumNodeType): Promise<void> => {
await invoke(`unbond_${type}`);
};
export const delegate = async ({
type,
@@ -14,7 +17,10 @@ export const delegate = async ({
type: EnumNodeType;
identity: string;
amount: Coin;
}): Promise<DelegationResult> => invoke(`delegate_to_${type}`, { identity, amount });
}): Promise<DelegationResult> => {
const res: DelegationResult = await invoke(`delegate_to_${type}`, { identity, amount });
return res;
};
export const undelegate = async ({
type,
@@ -24,15 +30,19 @@ export const undelegate = async ({
identity: string;
}): Promise<DelegationResult | undefined> => {
try {
return await invoke(`undelegate_from_${type}`, { identity });
const res: DelegationResult = await invoke(`undelegate_from_${type}`, { identity });
return res;
} catch (e) {
console.log(e);
return undefined;
}
};
export const send = async (args: { amount: Coin; address: string; memo: string }): Promise<TauriTxResult> =>
invoke('send', args);
export const send = async (args: { amount: Coin; address: string; memo: string }): Promise<TauriTxResult> => {
const res: TauriTxResult = await invoke('send', args);
return res;
};
export const updateMixnode = async (profitMarginPercent: number) =>
export const updateMixnode = async (profitMarginPercent: number): Promise<void> => {
await invoke('update_mixnode', { profitMarginPercent });
};
+8 -2
View File
@@ -1,6 +1,12 @@
import { invoke } from '@tauri-apps/api';
import { Coin } from '../types';
export const minorToMajor = async (amount: string): Promise<Coin> => invoke('minor_to_major', { amount });
export const minorToMajor = async (amount: string): Promise<Coin> => {
const res: Coin = await invoke('minor_to_major', { amount });
return res;
};
export const majorToMinor = async (amount: string): Promise<Coin> => invoke('major_to_minor', { amount });
export const majorToMinor = async (amount: string): Promise<Coin> => {
const res: Coin = await invoke('major_to_minor', { amount });
return res;
};
+8 -3
View File
@@ -1,7 +1,12 @@
import { invoke } from '@tauri-apps/api';
import { TauriContractStateParams } from '../types';
export const getContractParams = async (): Promise<TauriContractStateParams> => invoke('get_contract_settings');
export const getContractParams = async (): Promise<TauriContractStateParams> => {
const res: TauriContractStateParams = await invoke('get_contract_settings');
return res;
};
export const setContractParams = async (params: TauriContractStateParams): Promise<TauriContractStateParams> =>
invoke('update_contract_settings', { params });
export const setContractParams = async (params: TauriContractStateParams): Promise<TauriContractStateParams> => {
const res: TauriContractStateParams = await invoke('update_contract_settings', { params });
return res;
};
+4 -1
View File
@@ -1,4 +1,7 @@
import { invoke } from '@tauri-apps/api';
import { Account, Network } from '../types';
export const selectNetwork = async (network: Network): Promise<Account> => invoke('switch_network', { network });
export const selectNetwork = async (network: Network): Promise<Account> => {
const res: Account = await invoke('switch_network', { network });
return res;
};
+44 -18
View File
@@ -11,33 +11,59 @@ import {
TPagedDelegations,
} from '../types';
export const getReverseMixDelegations = async (): Promise<TPagedDelegations> =>
invoke('get_reverse_mix_delegations_paged');
export const getReverseMixDelegations = async (): Promise<TPagedDelegations> => {
const res: TPagedDelegations = await invoke('get_reverse_mix_delegations_paged');
return res;
};
export const getReverseGatewayDelegations = async (): Promise<TPagedDelegations> =>
invoke('get_reverse_gateway_delegations_paged');
export const getReverseGatewayDelegations = async (): Promise<TPagedDelegations> => {
const res: TPagedDelegations = await invoke('get_reverse_gateway_delegations_paged');
return res;
};
export const getMixnodeBondDetails = async (): Promise<TMixnodeBondDetails | null> => invoke('mixnode_bond_details');
export const getMixnodeBondDetails = async (): Promise<TMixnodeBondDetails | null> => {
const res: TMixnodeBondDetails = await invoke('mixnode_bond_details');
return res;
};
export const getMixnodeStakeSaturation = async (identity: string): Promise<StakeSaturationResponse> =>
invoke('mixnode_stake_saturation', { identity });
export const getMixnodeStakeSaturation = async (identity: string): Promise<StakeSaturationResponse> => {
const res: StakeSaturationResponse = await invoke('mixnode_stake_saturation', { identity });
return res;
};
export const getMixnodeRewardEstimation = async (identity: string): Promise<RewardEstimationResponse> =>
invoke('mixnode_reward_estimation', { identity });
export const getMixnodeRewardEstimation = async (identity: string): Promise<RewardEstimationResponse> => {
const res: RewardEstimationResponse = await invoke('mixnode_reward_estimation', { identity });
return res;
};
export const getMixnodeStatus = async (identity: string): Promise<MixnodeStatusResponse> =>
invoke('mixnode_status', { identity });
export const getMixnodeStatus = async (identity: string): Promise<MixnodeStatusResponse> => {
const res: MixnodeStatusResponse = await invoke('mixnode_status', { identity });
return res;
};
export const checkMixnodeOwnership = async (): Promise<boolean> => invoke('owns_mixnode');
export const checkMixnodeOwnership = async (): Promise<boolean> => {
const res: boolean = await invoke('owns_mixnode');
return res;
};
export const checkGatewayOwnership = async (): Promise<boolean> => invoke('owns_gateway');
export const checkGatewayOwnership = async (): Promise<boolean> => {
const res: boolean = await invoke('owns_gateway');
return res;
};
// NOTE: this uses OUTDATED defaults that might have no resemblance with the reality
// as for the actual transaction, the gas cost is being simulated beforehand
export const getGasFee = async (operation: Operation): Promise<Coin> =>
invoke('outdated_get_approximate_fee', { operation });
export const getGasFee = async (operation: Operation): Promise<Coin> => {
const res: Coin = await invoke('outdated_get_approximate_fee', { operation });
return res;
};
export const getInclusionProbability = async (identity: string): Promise<InclusionProbabilityResponse> =>
invoke('mixnode_inclusion_probability', { identity });
export const getInclusionProbability = async (identity: string): Promise<InclusionProbabilityResponse> => {
const res: InclusionProbabilityResponse = await invoke('mixnode_inclusion_probability', { identity });
return res;
};
export const userBalance = async (): Promise<Balance> => invoke('get_balance');
export const userBalance = async (): Promise<Balance> => {
const res: Balance = await invoke('get_balance');
return res;
};
+48 -27
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,
@@ -13,37 +13,44 @@ import {
} from '../types';
export const getLockedCoins = async (): Promise<Coin> => {
const res: Coin = await invoke('locked_coins');
return await minorToMajor(res.amount);
const coin: Coin = await invoke('locked_coins');
const major = await minorToMajor(coin.amount);
return major;
};
export const getSpendableCoins = async (vestingAccountAddress?: string): Promise<Coin> => {
const res: Coin = await invoke('spendable_coins', { vestingAccountAddress });
return minorToMajor(res.amount);
export const getSpendableCoins = async (): Promise<Coin> => {
const coin: Coin = await invoke('spendable_coins');
const major = await minorToMajor(coin.amount);
return major;
};
export const getVestingCoins = async (vestingAccountAddress: string): Promise<Coin> => {
const res: Coin = await invoke('vesting_coins', { vestingAccountAddress });
return minorToMajor(res.amount);
const coin: Coin = await invoke('vesting_coins', { vestingAccountAddress });
const major = await minorToMajor(coin.amount);
return major;
};
export const getVestedCoins = async (vestingAccountAddress: string): Promise<Coin> => {
const res: Coin = await invoke('vested_coins', { vestingAccountAddress });
return minorToMajor(res.amount);
const coin: Coin = await invoke('vested_coins', { vestingAccountAddress });
const major = await minorToMajor(coin.amount);
return major;
};
export const getOriginalVesting = async (vestingAccountAddress: string): Promise<OriginalVestingResponse> => {
const res: OriginalVestingResponse = await invoke('original_vesting', { vestingAccountAddress });
const majorValue = await minorToMajor(res.amount.amount);
return { ...res, amount: majorValue };
const major = await minorToMajor(res.amount.amount);
return { ...res, amount: major };
};
export const withdrawVestedCoins = async (amount: string) => {
export const withdrawVestedCoins = async (amount: string): Promise<void> => {
const minor = await majorToMinor(amount);
await invoke('withdraw_vested_coins', { amount: { amount: minor.amount, denom: 'Minor' } });
};
export const getCurrentVestingPeriod = async (address: string): Promise<Period> =>
invoke('get_current_vesting_period', { address });
export const getCurrentVestingPeriod = async (address: string): Promise<Period> => {
const res: Period = await invoke('get_current_vesting_period', { address });
return res;
};
export const vestingBond = async ({
type,
@@ -55,9 +62,13 @@ export const vestingBond = async ({
data: MixNode | Gateway;
pledge: Coin;
ownerSignature: string;
}): Promise<any> => await invoke(`vesting_bond_${type}`, { [type]: data, ownerSignature, pledge });
}): Promise<void> => {
await invoke(`vesting_bond_${type}`, { [type]: data, ownerSignature, pledge });
};
export const vestingUnbond = async (type: EnumNodeType) => await invoke(`vesting_unbond_${type}`);
export const vestingUnbond = async (type: EnumNodeType): Promise<void> => {
await invoke(`vesting_unbond_${type}`);
};
export const vestingDelegateToMixnode = async ({
identity,
@@ -65,13 +76,20 @@ export const vestingDelegateToMixnode = async ({
}: {
identity: string;
amount: Coin;
}): Promise<DelegationResult> => invoke('vesting_delegate_to_mixnode', { identity, amount });
}): Promise<DelegationResult> => {
const res: DelegationResult = await invoke('vesting_delegate_to_mixnode', { identity, amount });
return res;
};
export const vestingUnelegateFromMixnode = async (identity: string): Promise<DelegationResult> =>
await invoke('vesting_undelegate_from_mixnode', { identity });
export const vestingUnelegateFromMixnode = async (identity: string): Promise<DelegationResult> => {
const res: DelegationResult = await invoke('vesting_undelegate_from_mixnode', { identity });
return res;
};
export const getVestingAccountInfo = async (address: string): Promise<VestingAccountInfo> =>
await invoke('get_account_info', { address });
export const getVestingAccountInfo = async (address: string): Promise<VestingAccountInfo> => {
const res: VestingAccountInfo = await invoke('get_account_info', { address });
return res;
};
export const getVestingPledgeInfo = async ({
address,
@@ -81,15 +99,18 @@ export const getVestingPledgeInfo = async ({
type: EnumNodeType;
}): Promise<PledgeData | undefined> => {
try {
return await invoke(`vesting_get_${type}_pledge`, { address });
const res: PledgeData = await invoke(`vesting_get_${type}_pledge`, { address });
return res;
} catch (e) {
return undefined;
}
};
export const vestingUpdateMixnode = async (profitMarginPercent: number) =>
export const vestingUpdateMixnode = async (profitMarginPercent: number): Promise<void> => {
await invoke('vesting_update_mixnode', { profitMarginPercent });
export const vestingDelegatedFree = async (vestingAccountAddress: string) => {
await invoke('delegated_free', { vestingAccountAddress });
};
export const vestingDelegatedFree = async (vestingAccountAddress: string): Promise<Coin> => {
const res: Coin = await invoke('delegated_free', { vestingAccountAddress });
return res;
};
+1 -1
View File
@@ -1,4 +1,4 @@
import { Coin, Denom, Gateway, MixNode, PledgeData } from '.';
import { Coin, Denom, Gateway, MixNode, PledgeData } from './rust';
export enum EnumNodeType {
mixnode = 'mixnode',
+3 -2
View File
@@ -2,7 +2,7 @@ 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, getLockedCoins } from '../requests';
import { userBalance, majorToMinor, getLockedCoins, getSpendableCoins } from '../requests';
import { Coin, Network, TCurrency } from '../types';
export const validateKey = (key: string, bytesLength: number): boolean => {
@@ -103,7 +103,8 @@ export const checkHasEnoughFunds = async (allocationValue: string): Promise<bool
export const checkHasEnoughLockedTokens = async (allocationValue: string) => {
try {
const lockedTokens = await getLockedCoins();
const remainingBalance = +lockedTokens.amount - +allocationValue;
const spendableTokens = await getSpendableCoins();
const remainingBalance = +lockedTokens.amount + +spendableTokens.amount - +allocationValue;
return remainingBalance >= 0;
} catch (e) {
console.error(e);