Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
refactor: code reviews from #383 (#387)
Browse files Browse the repository at this point in the history
refact: code reviews from #383
  • Loading branch information
luizstacio committed Sep 21, 2022
1 parent 32ffdd2 commit 9425e4b
Show file tree
Hide file tree
Showing 28 changed files with 105 additions and 111 deletions.
3 changes: 0 additions & 3 deletions packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@
"xstate:typegen:watch": "xstate typegen 'src/**/*.ts?(x)' --watch"
},
"dependencies": {
"@ethersproject/bignumber": "^5.6.2",
"@ethersproject/random": "^5.6.1",
"@ethersproject/units": "^5.6.1",
"@fontsource/inter": "^4.5.11",
"@fontsource/raleway": "^4.5.9",
"@fuel-ui/css": "^0.7.0",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ export const FIXED_UNITS = 3;
export const GAS_PRICE = 1;
/** Base block explorer url */
export const BLOCK_EXPLORER_URL = 'https://fuellabs.github.io/block-explorer-v2';
/** Is production env */
export const IS_DEVELOPMENT = process.env.NODE_ENV !== 'production';
4 changes: 2 additions & 2 deletions packages/app/src/systems/Core/components/CoinBalance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useMemo } from "react";

import type { CoinBalanceProps } from "../hooks";
import { useBalances } from "../hooks";
import { format, isZero, safeBigInt } from "../utils";
import { format, isZero, safeBN } from "../utils";

import { Button, Tooltip } from "~/systems/UI";

Expand All @@ -19,7 +19,7 @@ export const CoinBalance = ({

const balance = useMemo(() => {
const coinBalance = balances?.find((i) => i.assetId === coin?.assetId);
return safeBigInt(coinBalance?.amount);
return safeBN(coinBalance?.amount);
}, [balances, coin?.assetId]);

const maxButtonText = isZero(gasFee)
Expand Down
5 changes: 3 additions & 2 deletions packages/app/src/systems/Core/hooks/useAssets.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { BN, CoinQuantity } from 'fuels';
import { bn } from 'fuels';
import { useQuery } from 'react-query';

import { TOKENS, ASSET_404, toBigInt } from '../utils';
import { TOKENS, ASSET_404 } from '../utils';

import { useWallet } from './useWallet';

Expand All @@ -19,7 +20,7 @@ const mergeCoinsWithMetadata = (coins: CoinQuantity[] = []): Array<AssetAmount>
img: coinMetadata?.img || ASSET_404.img,
pairOf: coinMetadata?.pairOf,
assetId: coin.assetId,
amount: toBigInt(coin.amount || 0),
amount: bn(coin.amount || 0),
};
});

Expand Down
16 changes: 8 additions & 8 deletions packages/app/src/systems/Core/hooks/useCoinInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { ReactNode } from 'react';
import { useMemo, useEffect, useState } from 'react';
import type { NumberFormatValues } from 'react-number-format';

import { formatUnits, isCoinEth, parseInputValueBigInt, safeBigInt, ZERO } from '../utils';
import { formatUnits, isCoinEth, parseInputValueBN, safeBN, ZERO } from '../utils';

import { useBalances } from './useBalances';

Expand Down Expand Up @@ -86,23 +86,23 @@ export function useCoinInput({
...params
}: UseCoinParams): UseCoinInput {
const [amount, setAmount] = useState<Maybe<BN>>(null);
const [gasFee, setGasFee] = useState<Maybe<BN>>(safeBigInt(initialGasFee));
const [gasFee, setGasFee] = useState<Maybe<BN>>(safeBN(initialGasFee));
const { data: balances } = useBalances();
const coinBalance = balances?.find((item) => item.assetId === coin?.assetId);
const isEth = useMemo(() => isCoinEth(coin), [coin?.assetId]);

// TODO: consider real gas fee, replacing GAS_FEE variable.
// For now we need to keep 1 unit in the wallet(it's not spent) in order to complete "create pool" transaction.
function getSafeMaxBalance() {
const next = safeBigInt(coinBalance?.amount);
const value = next > ZERO ? next.sub(safeBigInt(gasFee)) : next;
const next = safeBN(coinBalance?.amount);
const value = next > ZERO ? next.sub(safeBN(gasFee)) : next;
if (value < ZERO) return ZERO;
return value;
}

function handleInputPropsChange(val: string) {
if (isReadOnly) return;
const next = val !== '' ? parseInputValueBigInt(val) : null;
const next = val !== '' ? parseInputValueBN(val) : null;
if (typeof onChange === 'function') {
onChange(next);
} else {
Expand All @@ -112,7 +112,7 @@ export function useCoinInput({

function isAllowed({ value }: NumberFormatValues) {
const max = params.max ? params.max : bn(Number.MAX_SAFE_INTEGER);
return parseInputValueBigInt(value).lt(max);
return parseInputValueBN(value).lt(max);
}

function getInputProps() {
Expand All @@ -122,7 +122,7 @@ export function useCoinInput({
displayType: (isReadOnly ? 'text' : 'input') as DisplayType,
onInput,
onChange: handleInputPropsChange,
balance: formatValue(safeBigInt(coinBalance?.amount)),
balance: formatValue(safeBN(coinBalance?.amount)),
isAllowed,
} as CoinInputProps;
}
Expand Down Expand Up @@ -172,6 +172,6 @@ export function useCoinInput({
getCoinSelectorProps,
getCoinBalanceProps,
formatted: formatValue(amount),
hasEnoughBalance: getSafeMaxBalance().gte(safeBigInt(amount)),
hasEnoughBalance: getSafeMaxBalance().gte(safeBN(amount)),
};
}
4 changes: 1 addition & 3 deletions packages/app/src/systems/Core/utils/chain.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import type { BigNumberish, Contract } from 'fuels';

import { toBigInt } from './math';

import { DEADLINE } from '~/config';

export async function getDeadline(contract: Contract, deadline?: BigNumberish) {
const blockHeight = await contract.wallet!.provider.getBlockNumber();
const nexDeadline = blockHeight.add(deadline || toBigInt(DEADLINE));
const nexDeadline = blockHeight.add(deadline || DEADLINE);
return nexDeadline;
}
10 changes: 5 additions & 5 deletions packages/app/src/systems/Core/utils/gas.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { ReceiptType } from 'fuels';
import type {
BN,
CallResult,
FunctionInvocationScope,
MultiCallInvocationScope,
TxParams,
} from 'fuels';
import { ReceiptType } from 'fuels';

import { safeBigInt, toBigInt, ZERO } from './math';
import { multiply, safeBN, ZERO } from './math';

import { GAS_PRICE } from '~/config';

Expand Down Expand Up @@ -62,7 +62,7 @@ export async function getTransactionCost(
fundTransaction: true,
});
return {
total: toBigInt(txCost.gasUsed.toNumber() * 1.3),
total: multiply(txCost.gasUsed, 1.3),
fee: txCost.fee,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -72,10 +72,10 @@ export async function getTransactionCost(
}

export function getOverrides(overrides?: TxParams): TxParams {
const gasLimit = safeBigInt(overrides?.gasLimit);
const gasLimit = safeBN(overrides?.gasLimit);
const ret = {
gasPrice: GAS_PRICE,
gasLimit: gasLimit.gt(0) ? gasLimit : 100_000_000,
gasLimit: !gasLimit.isZero() ? gasLimit : 100_000_000,
...overrides,
};
return ret;
Expand Down
13 changes: 10 additions & 3 deletions packages/app/src/systems/Core/utils/math.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ describe('Math utilities', () => {
expect(math.parseUnits('0.00002').toHex()).toEqual(bn('20000').toHex());
expect(math.parseUnits('100.00002').toHex()).toEqual(bn('100000020000').toHex());
expect(math.parseUnits('100,100.00002').toHex()).toEqual(bn('100100000020000').toHex());
expect(math.parseUnits('100,100.00002', 5).toHex()).toEqual(bn('10010000002').toHex());
expect(() => {
math.parseUnits('100,100.000002', 5);
}).toThrow("Decimal can't be bigger than the precision");
});
it('Math.formatUnits', () => {
expect(math.formatUnits(bn('1000000000'))).toEqual('1.000000000');
Expand All @@ -34,10 +38,13 @@ describe('Math utilities', () => {
expect(math.isZero(bn(0))).toBeTruthy();
});

it('Math.divideBy', () => {
it('Math.multiply', () => {
expect(math.multiply(bn(100), 1.2).toHex()).toEqual(bn(120).toHex());
expect(math.multiply(bn(2), 0.5).toHex()).toEqual(bn(1).toHex());
expect(math.multiply(bn('100000020000'), 0.5).toHex()).toEqual(bn('50000010000').toHex());
});

it('Math.divide', () => {
expect(math.divide(bn(4), bn(2)).toHex()).toEqual(bn(2).toHex());
expect(math.divide(bn(1), 0.5).toHex()).toEqual(bn(2).toHex());
expect(math.divide(bn('100000020000'), 0.5).toHex()).toEqual(bn('200000040000').toHex());
Expand All @@ -51,8 +58,8 @@ describe('Math utilities', () => {
expect(math.maxAmount(bn(1), bn(2)).toHex()).toEqual(bn(2).toHex());
});

it('Math.safeBigInt', () => {
expect(math.safeBigInt().toHex()).toEqual(math.ZERO.toHex());
it('Math.safeBN', () => {
expect(math.safeBN().toHex()).toEqual(math.ZERO.toHex());
});

it('Math.isValidNumber', () => {
Expand Down
13 changes: 4 additions & 9 deletions packages/app/src/systems/Core/utils/math.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// import * as ethers from '@ethersproject/units';
import { Decimal } from 'decimal.js';
import { bn } from 'fuels';
import type { BigNumberish, BN } from 'fuels';
Expand Down Expand Up @@ -58,7 +57,7 @@ export function parseUnits(value: string, precision: number = DECIMAL_UNITS): BN
const length = valueDecimals.length;

if (length > precision) {
throw new Error('Decimal can not be bigger than the precision');
throw new Error("Decimal can't be bigger than the precision");
}

const decimals = Array.from({ length: precision }).fill('0');
Expand All @@ -67,18 +66,14 @@ export function parseUnits(value: string, precision: number = DECIMAL_UNITS): BN
return bn(amount);
}

export function parseInputValueBigInt(value: string): BN {
export function parseInputValueBN(value: string): BN {
if (value !== '') {
const nextValue = value === '.' ? '0.' : value;
return toBigInt(parseUnits(nextValue));
return bn(parseUnits(nextValue));
}
return ZERO;
}

export function toBigInt(number: BigNumberish) {
return bn(number);
}

export function getNumberOrHex(value: Maybe<BigNumberish>): number | string {
if (typeof value === 'number') {
return value;
Expand All @@ -102,7 +97,7 @@ export function maxAmount(value: BigNumberish, max: BigNumberish): BN {
return bn(max).lt(value) ? bn(value) : bn(max);
}

export function safeBigInt(value?: Maybe<BigNumberish>, defaultValue?: BigNumberish): BN {
export function safeBN(value?: Maybe<BigNumberish>, defaultValue?: BigNumberish): BN {
return bn(value || defaultValue || 0);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/systems/Faucet/hooks/useFaucet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useMutation, useQuery } from 'react-query';

import { FUEL_FAUCET_URL } from '~/config';
import { useBalances, useWallet } from '~/systems/Core';
import { format, safeBigInt } from '~/systems/Core/utils/math';
import { format, safeBN } from '~/systems/Core/utils/math';
import type { Maybe } from '~/types';
import { Queries } from '~/types';

Expand Down Expand Up @@ -62,7 +62,7 @@ export function useFaucet(opts: UseFaucetOpts = {}) {
}

const faucetAmount = useMemo(() => {
const amount = safeBigInt(query.data?.amount);
const amount = safeBN(query.data?.amount);
return format(amount);
}, [query.status]);

Expand Down
6 changes: 3 additions & 3 deletions packages/app/src/systems/Mint/hooks/useMint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useMutation, useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';

import { TOKEN_ID } from '~/config';
import { useTokenMethods, useBalances, safeBigInt } from '~/systems/Core';
import { useTokenMethods, useBalances, safeBN } from '~/systems/Core';
import { useTransactionCost } from '~/systems/Core/hooks/useTransactionCost';
import { txFeedback } from '~/systems/Core/utils/feedback';
import { Pages } from '~/types';
Expand All @@ -20,7 +20,7 @@ export function useMint(opts: UseMintOpts = {}) {

const mutation = useMutation(
async () => {
if (txCost.total.eq(0)) return;
if (txCost.total.isZero()) return;
return methods.mint(txCost.total);
},
{ onSuccess: txFeedback('Token received successfully!', handleSuccess) }
Expand All @@ -40,6 +40,6 @@ export function useMint(opts: UseMintOpts = {}) {
...mutation,
txCost,
handleMint,
mintAmount: safeBigInt(mintAmount),
mintAmount: safeBN(mintAmount),
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
PreviewItem,
TokenIcon,
compareStates,
safeBigInt,
safeBN,
format,
} from "~/systems/Core";

Expand Down Expand Up @@ -39,7 +39,7 @@ export const PoolCurrentReserves = () => {
{coinFrom?.name}
</div>
}
value={format(safeBigInt(poolInfo?.eth_reserve))}
value={format(safeBN(poolInfo?.eth_reserve))}
/>
<PreviewItem
loading={isLoading}
Expand All @@ -49,7 +49,7 @@ export const PoolCurrentReserves = () => {
{coinTo?.name}
</div>
}
value={format(safeBigInt(poolInfo?.token_reserve))}
value={format(safeBN(poolInfo?.token_reserve))}
/>
</PreviewTable>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
useCoinMetadata,
ETH_DAI,
NetworkFeePreviewItem,
safeBigInt,
safeBN,
} from "~/systems/Core";
import type { Maybe } from "~/types";

Expand All @@ -31,7 +31,7 @@ export const RemoveLiquidityPreview = ({
formattedPooledETH,
formattedNextPoolTokens,
formattedNextPoolShare,
} = usePreviewRemoveLiquidity(safeBigInt(amount));
} = usePreviewRemoveLiquidity(safeBN(amount));

if (!amount) return null;

Expand Down
6 changes: 3 additions & 3 deletions packages/app/src/systems/Pool/hooks/useAddLiquidity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import { addLiquidityMachine } from "../machines/addLiquidityMachine";
import type { AddLiquidityMachineContext } from "../types";
import { liquidityPreviewEmpty } from "../types";

import { IS_DEVELOPMENT } from "~/config";
import { TOKENS, useContract, useSubscriber } from "~/systems/Core";
import { AppEvents } from "~/types";

const serviceMap = new Map();
const isProd = process.env.NODE_ENV === "production";

export const AddLiquidityContext = createContext<AddLiquidityMachineService>(
{} as AddLiquidityMachineService
Expand All @@ -28,7 +28,7 @@ function useAddLiquidityService() {
* Need this because of React.context that updates for null on each refresh
* Causing an error in useActor. But it's on development
*/
if (!service && !isProd) {
if (!service && IS_DEVELOPMENT) {
service = serviceMap.get("service");
}

Expand Down Expand Up @@ -68,7 +68,7 @@ export function AddLiquidityProvider({ children }: { children: ReactNode }) {
context,
});

if (!isProd) {
if (IS_DEVELOPMENT) {
serviceMap.set("service", service);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
format,
getCoin,
isZero,
safeBigInt,
safeBN,
toFixed,
useBalances,
ZERO,
Expand All @@ -29,7 +29,7 @@ export function usePreviewRemoveLiquidity(amount: Maybe<BN>): PreviewRemoveLiqui
const { data: balances } = useBalances();
const poolTokens = useMemo(() => {
const lpTokenAmount = getCoin(balances || [], CONTRACT_ID)?.amount;
const poolTokensNum = safeBigInt(lpTokenAmount);
const poolTokensNum = safeBN(lpTokenAmount);
return poolTokensNum;
}, [balances]);
const { data: info } = usePositionInfo(amount || ZERO);
Expand Down
Loading

0 comments on commit 9425e4b

Please sign in to comment.