From a273980aa00791ffe5fdeee28293dbd523d5dc9b Mon Sep 17 00:00:00 2001 From: fmtabbara Date: Mon, 17 Jan 2022 17:34:39 +0000 Subject: [PATCH] refactor --- nym-wallet/src/pages/bond/BondForm.tsx | 13 --- nym-wallet/src/pages/bond/index.tsx | 2 +- nym-wallet/src/pages/bond/validationSchema.ts | 17 +++- nym-wallet/src/utils/index.ts | 21 +++-- nym-wallet/tsconfig.json | 86 ++++--------------- 5 files changed, 39 insertions(+), 100 deletions(-) diff --git a/nym-wallet/src/pages/bond/BondForm.tsx b/nym-wallet/src/pages/bond/BondForm.tsx index 68e1ef443f..def5a39fb3 100644 --- a/nym-wallet/src/pages/bond/BondForm.tsx +++ b/nym-wallet/src/pages/bond/BondForm.tsx @@ -19,7 +19,6 @@ import { bond, majorToMinor } from '../../requests' import { validationSchema } from './validationSchema' import { Coin, Gateway, MixNode } from '../../types' import { ClientContext, MAJOR_CURRENCY } from '../../context/main' -import { checkHasEnoughFunds, checkHasEnoughToUnbond } from '../../utils' type TBondFormFields = { withAdvancedOptions: boolean @@ -91,7 +90,6 @@ export const BondForm = ({ register, handleSubmit, setValue, - setError, watch, formState: { errors, isSubmitting }, } = useForm({ @@ -105,17 +103,6 @@ export const BondForm = ({ const watchAdvancedOptions = watch('withAdvancedOptions', defaultValues.withAdvancedOptions) const onSubmit = async (data: TBondFormFields) => { - const hasEnoughFunds = await checkHasEnoughFunds(data.amount) - const hasEnoughToUnbond = await checkHasEnoughToUnbond(data.amount) - - if (!hasEnoughFunds) { - return setError('amount', { message: 'Not enough funds in wallet' }) - } - - if(!hasEnoughToUnbond) { - return setError('amount', { message: 'you will not have enough funds to unbond this mixnode' }) - } - const formattedData = formatData(data) const pledge = await majorToMinor(data.amount) diff --git a/nym-wallet/src/pages/bond/index.tsx b/nym-wallet/src/pages/bond/index.tsx index ae87acca4f..566295cb37 100644 --- a/nym-wallet/src/pages/bond/index.tsx +++ b/nym-wallet/src/pages/bond/index.tsx @@ -1,6 +1,7 @@ import React, { useContext, useEffect, useState } from 'react' import { Alert, Box, Button, CircularProgress } from '@mui/material' import { BondForm } from './BondForm' +import { SuccessView } from './SuccessView' import { NymCard } from '../../components' import { EnumRequestStatus, RequestStatus } from '../../components/RequestStatus' import { Layout } from '../../layouts' @@ -9,7 +10,6 @@ import { TFee } from '../../types' import { useCheckOwnership } from '../../hooks/useCheckOwnership' import { ClientContext } from '../../context/main' import { Bond as BondIcon } from '../../svg-icons/bond' -import { SuccessView } from './SuccessView' export const Bond = () => { const [status, setStatus] = useState(EnumRequestStatus.initial) diff --git a/nym-wallet/src/pages/bond/validationSchema.ts b/nym-wallet/src/pages/bond/validationSchema.ts index c98f27cd49..01d676af78 100644 --- a/nym-wallet/src/pages/bond/validationSchema.ts +++ b/nym-wallet/src/pages/bond/validationSchema.ts @@ -1,6 +1,7 @@ import * as Yup from 'yup' import { MAJOR_CURRENCY } from '../../context/main' import { + checkHasEnoughFunds, isValidHostname, validateAmount, validateKey, @@ -28,11 +29,19 @@ export const validationSchema = Yup.object().shape({ profitMarginPercent: Yup.number().required('Profit Percentage is required').min(0).max(100), amount: Yup.string() .required('An amount is required') - .test('valid-amount', `A valid amount is required (min 100 ${MAJOR_CURRENCY})`, function (value) { - return validateAmount(value || '', '100000000') - // minimum amount needs to come from the backend - replace when available - }), + .test('valid-amount', `Pledge error`, async function (value) { + const isValid = await validateAmount(value || '', '100000000') + if (!isValid) { + return this.createError({ message: `A valid amount is required (min 100 ${MAJOR_CURRENCY})` }) + } else { + const hasEnough = await checkHasEnoughFunds(value || '') + if (!hasEnough) { + return this.createError({ message: 'Not enough funds in wallet' }) + } + } + return true + }), host: Yup.string() .required('A host is required') .test('valid-host', 'A valid host is required', function (value) { diff --git a/nym-wallet/src/utils/index.ts b/nym-wallet/src/utils/index.ts index ce128605d1..81024f16ff 100644 --- a/nym-wallet/src/utils/index.ts +++ b/nym-wallet/src/utils/index.ts @@ -86,16 +86,15 @@ export const validateRawPort = (rawPort: number): boolean => !isNaN(rawPort) && export const truncate = (text: string, trim: number) => text.substring(0, trim) + '...' -export const checkHasEnoughFunds = async (allocationValue: string) => { - const walletValue = await userBalance() - const minorValue = await majorToMinor(allocationValue) - return !(+walletValue.coin.amount - +minorValue.amount < 0) -} +export const isGreaterThan = (a: number, b: number) => a > b -export const checkHasEnoughToUnbond = async (allocationValue: string) => { - const walletValue = await userBalance() - const minorAllocationValue = await majorToMinor(allocationValue) - const unbondFee = await getGasFee('UnbondMixnode') - const unbondFeeMinor = await majorToMinor(unbondFee.amount) - return !(+walletValue.coin.amount - +minorAllocationValue.amount < +unbondFeeMinor.amount) +export const checkHasEnoughFunds = async (allocationValue: string) => { + 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) + } } diff --git a/nym-wallet/tsconfig.json b/nym-wallet/tsconfig.json index e75fb24bc2..b3aa27c13b 100644 --- a/nym-wallet/tsconfig.json +++ b/nym-wallet/tsconfig.json @@ -1,76 +1,20 @@ { "compilerOptions": { + "target": "es5", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "esModuleInterop": true, "allowSyntheticDefaultImports": true, - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, - "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, - // "lib": [], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - "jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */, - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - // "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - // "outDir": "./", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true /* Enable all strict type-checking options. */, - "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - "typeRoots": [ - "../node_modules/@types", - "src/types", - "./" - ] /* List of folders to include type definitions from. */, - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true /* Skip type checking of declaration files. */, - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + "strict": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": false, + "jsx": "react-jsx", + "sourceMap": true, + "baseUrl": "." }, - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist", "jest.config.js", "webpack.config.js", "webpack.prod.js", "webpack.common.js"] }