Skip to content

Commit

Permalink
CP-8975 Replace BN for bigint (#1455)
Browse files Browse the repository at this point in the history
Co-authored-by: ruijialin <[email protected]>
  • Loading branch information
neven-s and ruijialin-avalabs authored Aug 1, 2024
1 parent 03d7cc8 commit ec59c72
Show file tree
Hide file tree
Showing 41 changed files with 322 additions and 579 deletions.
13 changes: 6 additions & 7 deletions packages/core-mobile/app/components/BNInput.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import React, { useEffect, useState } from 'react'
import InputText, { InputTextProps } from 'components/InputText'
import Big from 'big.js'
import BN from 'bn.js'
import { bigToBN, bnToBig } from '@avalabs/core-utils-sdk'
import { bigintToBig, bigToBigInt } from '@avalabs/core-utils-sdk'

interface BNInputProps extends Omit<InputTextProps, 'text'> {
value?: BN
value?: bigint
denomination: number

onChange?(val: { bn: BN; amount: string }): void
onChange?(val: { bn: bigint; amount: string }): void

onMax?(): void

Expand Down Expand Up @@ -37,7 +36,7 @@ export function BNInput({
..._props
}: BNInputProps): JSX.Element {
const [valueAsString, setValueAsString] = useState('')
const valueBig = value ? bnToBig(value, denomination) : undefined
const valueBig = value ? bigintToBig(value, denomination) : undefined

useEffect(() => {
// When deleting zeros after decimal, all zeros delete without this check.
Expand All @@ -49,7 +48,7 @@ export function BNInput({

const onValueChanged = (rawValue: string): void => {
if (!rawValue) {
onChange?.({ bn: new BN(0), amount: '0' })
onChange?.({ bn: 0n, amount: '0' })
setValueAsString('')
return
}
Expand All @@ -60,7 +59,7 @@ export function BNInput({
*/
const [, endValue] = splitBN(changedValue)
if (!endValue || endValue.length <= denomination) {
const valueToBn = bigToBN(new Big(changedValue), denomination)
const valueToBn = bigToBigInt(new Big(changedValue), denomination)
setValueAsString(changedValue)
onChange?.({
amount: changedValue ? new Big(changedValue).toString() : '0', // used to removing leading & trailing zeros
Expand Down
4 changes: 2 additions & 2 deletions packages/core-mobile/app/components/EditSpendLimit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import AppNavigation from 'navigation/AppNavigation'
import RpcRequestBottomSheet from 'screens/rpc/components/shared/RpcRequestBottomSheet'
import { View, Text, Button } from '@avalabs/k2-mobile'
import { Limit, SpendLimit } from 'hooks/useSpendLimits'
import { hexToBN } from '@avalabs/core-utils-sdk'
import { hexToBigInt } from 'viem'

const EditSpendLimit = (): JSX.Element | null => {
const { spendLimit, onClose, updateSpendLimit, dAppName, editingToken } =
Expand Down Expand Up @@ -70,7 +70,7 @@ const EditSpendLimit = (): JSX.Element | null => {
Default
</Text>
<BNInput
value={hexToBN(editingToken.defaultValue)}
value={hexToBigInt(editingToken.defaultValue)}
denomination={editingToken.decimals}
editable={false}
selectTextOnFocus={false}
Expand Down
10 changes: 6 additions & 4 deletions packages/core-mobile/app/components/UniversalTokenSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React, { FC, useCallback, useMemo } from 'react'
import { Pressable, StyleSheet, View } from 'react-native'
import { AssetBalance } from 'screens/bridge/utils/types'
import BN from 'bn.js'
import { bnToBig } from '@avalabs/core-utils-sdk'
import { bigintToBig } from '@avalabs/core-utils-sdk'
import { useApplicationContext } from 'contexts/ApplicationContext'
import { Row } from 'components/Row'
import AvaText from 'components/AvaText'
Expand All @@ -25,7 +24,7 @@ interface Props {
onTokenChange: (token: TokenWithBalance | AssetBalance) => void
onMax?: () => void
hideInput?: boolean
inputAmount?: BN
inputAmount?: bigint
onAmountChange: (amount: Amount) => void
error?: string
label?: string
Expand Down Expand Up @@ -69,7 +68,10 @@ const UniversalTokenSelector: FC<Props> = ({
if (!inputAmount || !selectedToken?.decimals) {
return ''
}
const bnNumber = bnToBig(inputAmount, selectedToken?.decimals).toNumber()
const bnNumber = bigintToBig(
inputAmount,
selectedToken?.decimals
).toNumber()
return selectedToken.priceInCurrency
? formatLargeCurrency(
currencyFormatter(bnNumber * selectedToken.priceInCurrency),
Expand Down
14 changes: 7 additions & 7 deletions packages/core-mobile/app/contexts/SendTokenContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ import { useSelector } from 'react-redux'
import { selectActiveAccount } from 'store/account'
import sendService from 'services/send/SendService'
import { SendState } from 'services/send/types'
import { bnToLocaleString } from '@avalabs/core-utils-sdk'
import { bigIntToString } from '@avalabs/core-utils-sdk'
import { selectSelectedCurrency } from 'store/settings/currency'
import BN from 'bn.js'
import SentryWrapper from 'services/sentry/SentryWrapper'
import Logger from 'utils/Logger'
import AnalyticsService from 'services/analytics/AnalyticsService'
Expand Down Expand Up @@ -48,7 +47,7 @@ export const SendTokenContext = createContext<SendTokenContextState>(
)

const ZERO_AMOUNT = {
bn: new BN(0),
bn: 0n,
amount: '0'
}

Expand Down Expand Up @@ -208,10 +207,11 @@ export const SendTokenContextProvider = ({
.then(state => {
setGasLimit(state.gasLimit ?? 0)
setMaxAmount({
bn: state.maxAmount ?? new BN(0),
amount: state.maxAmount
? bnToLocaleString(state.maxAmount, sendToken?.decimals)
: ''
bn: state.maxAmount ?? 0n,
amount:
state.maxAmount && sendToken
? bigIntToString(state.maxAmount, sendToken.decimals)
: ''
})
setError(state.error ? state.error.message : undefined)
setCanSubmit(state.canSubmit ?? false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { JsonRpcBatchInternal } from '@avalabs/core-wallets-sdk'
import { TransactionParams } from '@avalabs/evm-module'
import ERC20 from '@openzeppelin/contracts/build/contracts/ERC20.json'
import Big from 'big.js'
import { BN } from 'bn.js'
import { APIError, ETHER_ADDRESS, Transaction } from 'paraswap'
import { OptimalRate } from 'paraswap-core'
import { promiseResolveWithBackoff, resolve } from '@avalabs/core-utils-sdk'
Expand Down Expand Up @@ -182,9 +181,7 @@ export async function performSwap({
// @ts-ignore
gas: bigIntToHex(txBuildData.gas), //gas property is not defined in Transaction@paraswap type but api does return this prop
data: txBuildData.data,
value: isSrcTokenNative
? `0x${new BN(sourceAmount).toString('hex')}`
: undefined // AVAX value needs to be sent with the transaction
value: isSrcTokenNative ? bigIntToHex(BigInt(sourceAmount)) : undefined // AVAX value needs to be sent with the transaction
}
]

Expand Down
22 changes: 13 additions & 9 deletions packages/core-mobile/app/hooks/useSpendLimits.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { bnToLocaleString, hexToBN } from '@avalabs/core-utils-sdk'
import { bigIntToString } from '@avalabs/core-utils-sdk'
import { useCallback, useEffect, useState } from 'react'
import Web3 from 'web3'
import ERC20 from '@openzeppelin/contracts/build/contracts/ERC20.json'
import { MaxUint256 } from 'ethers'
import {
TokenApproval,
TokenType,
TokenApprovals
TokenApprovals,
TokenType
} from '@avalabs/vm-module-types'
import type BN from 'bn.js'
import { hexToBigInt, isHex } from 'viem'

export const useSpendLimits = (
tokenApprovals: TokenApprovals | undefined
Expand All @@ -32,12 +32,14 @@ export const useSpendLimits = (
for (const tokenApproval of tokenApprovals.approvals) {
const token = tokenApproval.token
if (token.type === TokenType.ERC20 && tokenApproval.value) {
const defaultLimitBN = hexToBN(tokenApproval.value)
const defaultLimitBN = isHex(tokenApproval.value)
? hexToBigInt(tokenApproval.value)
: 0n
_spendLimits.push({
limitType: Limit.DEFAULT,
value: {
bn: defaultLimitBN,
amount: bnToLocaleString(defaultLimitBN, token.decimals)
amount: bigIntToString(defaultLimitBN, token.decimals)
},
tokenApproval
})
Expand Down Expand Up @@ -76,14 +78,16 @@ export const useSpendLimits = (
])
limitAmount = `0x${MaxUint256.toString(16)}`
} else if (newSpendData.limitType === Limit.DEFAULT) {
const bn = hexToBN(spendLimit.tokenApproval.value)
const bn = isHex(spendLimit.tokenApproval.value)
? hexToBigInt(spendLimit.tokenApproval.value)
: 0n
setSpendLimits([
{
...spendLimit,
limitType: Limit.DEFAULT,
value: {
bn,
amount: bnToLocaleString(
amount: bigIntToString(
bn,
spendLimit.tokenApproval.token.decimals
)
Expand Down Expand Up @@ -132,7 +136,7 @@ export enum Limit {
export interface SpendLimit {
limitType: Limit
value?: {
bn: BN
bn: bigint
amount: string
}
tokenApproval: TokenApproval
Expand Down
3 changes: 2 additions & 1 deletion packages/core-mobile/app/navigation/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { DrawerScreenProps as RNDrawerScreenProps } from '@react-navigation/draw
import {
Alert,
DisplayData,
Hex,
SigningData,
TokenWithBalance
} from '@avalabs/vm-module-types'
Expand Down Expand Up @@ -95,7 +96,7 @@ export type EditSpendLimitParams = {
onClose(): void
spendLimit: SpendLimit
editingToken: {
defaultValue: string
defaultValue: Hex
decimals: number
}
dAppName?: string
Expand Down
13 changes: 6 additions & 7 deletions packages/core-mobile/app/screens/bridge/Bridge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ import { BridgeScreenProps } from 'navigation/types'
import { usePosthogContext } from 'contexts/PosthogContext'
import { setActive, TokenSymbol } from 'store/network'
import {
bigToBN,
bigintToBig,
bigToBigInt,
bigToLocaleString,
bnToBig,
resolve
} from '@avalabs/core-utils-sdk'
import Big from 'big.js'
Expand All @@ -43,7 +43,6 @@ import {
isUnifiedBridgeAsset
} from 'screens/bridge/utils/bridgeUtils'
import { BNInput } from 'components/BNInput'
import BN from 'bn.js'
import { useDispatch, useSelector } from 'react-redux'
import { selectBridgeCriticalConfig } from 'store/bridge'
import AnalyticsService from 'services/analytics/AnalyticsService'
Expand Down Expand Up @@ -146,7 +145,7 @@ const Bridge: FC = () => {
amount &&
!amount.eq(BIG_ZERO) &&
networkFee &&
bnToBig(nativeTokenBalance, activeNetwork.networkToken.decimals).lt(
bigintToBig(nativeTokenBalance, activeNetwork.networkToken.decimals).lt(
networkFee
)
)
Expand Down Expand Up @@ -269,8 +268,8 @@ const Bridge: FC = () => {
}

const handleAmountChanged = useCallback(
(value: { bn: BN; amount: string }) => {
const bigValue = bnToBig(value.bn, denomination)
(value: { bn: bigint; amount: string }) => {
const bigValue = bigintToBig(value.bn, denomination)
if (bridgeError) {
setBridgeError('')
}
Expand Down Expand Up @@ -538,7 +537,7 @@ const Bridge: FC = () => {
return
}
handleAmountChanged({
bn: bigToBN(maximum, denomination),
bn: bigToBigInt(maximum, denomination),
amount: bigToLocaleString(maximum, 4)
})
}, [denomination, handleAmountChanged, maximum])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from '@avalabs/core-bridge-sdk'
import { BridgeAsset } from '@avalabs/bridge-unified'
import { AssetBalance } from 'screens/bridge/utils/types'
import { bnToBig } from '@avalabs/core-utils-sdk'
import { bigintToBig } from '@avalabs/core-utils-sdk'
import { TokenType, TokenWithBalance } from '@avalabs/vm-module-types'
import { isUnifiedBridgeAsset } from '../utils/bridgeUtils'

Expand Down Expand Up @@ -43,7 +43,7 @@ export function getEVMAssetBalances(
erc20TokensByAddress[asset.nativeContractAddress?.toLowerCase()]

const balance =
(token && bnToBig(token.balance, token.decimals)) || BIG_ZERO
(token && bigintToBig(token.balance, token.decimals)) || BIG_ZERO
return { symbol, asset, balance }
})
}
7 changes: 3 additions & 4 deletions packages/core-mobile/app/screens/bridge/hooks/useBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ import Big from 'big.js'
import { useSelector } from 'react-redux'
import { selectSelectedCurrency } from 'store/settings/currency'
import { selectActiveAccount } from 'store/account'
import { BIG_ZERO, bigToBN } from '@avalabs/core-utils-sdk'
import { BIG_ZERO, bigToBigInt } from '@avalabs/core-utils-sdk'
import Logger from 'utils/Logger'
import BN from 'bn.js'
import BridgeService from 'services/bridge/BridgeService'
import { selectIsDeveloperMode } from 'store/settings/advanced'
import { selectBridgeAppConfig } from 'store/bridge'
Expand Down Expand Up @@ -60,7 +59,7 @@ interface Bridge extends BridgeAdapter {
provider: BridgeProvider
bridgeFee: Big
denomination: number
amountBN: BN
amountBN: bigint
}

// eslint-disable-next-line sonarjs/cognitive-complexity
Expand Down Expand Up @@ -130,7 +129,7 @@ export default function useBridge(selectedAsset?: AssetBalance): Bridge {
}, [sourceBalance])

const amountBN = useMemo(
() => bigToBN(amount, denomination),
() => bigToBigInt(amount, denomination),
[amount, denomination]
)

Expand Down
4 changes: 2 additions & 2 deletions packages/core-mobile/app/screens/bridge/hooks/useBtcBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export function useBtcBridge({
setBtcBalance({
symbol: btcAsset.symbol,
asset: btcAsset,
balance: satoshiToBtc(token.balance.toNumber()),
balance: satoshiToBtc(Number(token.balance)),
logoUri: token.logoUri,
priceInCurrency: token.priceInCurrency
})
Expand All @@ -117,7 +117,7 @@ export function useBtcBridge({
setBtcBalanceAvalanche({
symbol: btcAsset.symbol,
asset: btcAsset,
balance: satoshiToBtc(btcAvalancheBalance?.balance?.toNumber() ?? 0),
balance: satoshiToBtc(Number(btcAvalancheBalance?.balance ?? 0)),
logoUri: btcAvalancheBalance?.logoUri,
priceInCurrency: btcAvalancheBalance?.priceInCurrency
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,12 @@ import {
import { LocalTokenId, LocalTokenWithBalance } from 'store/balance/types'
import { useDispatch, useSelector } from 'react-redux'
import { selectTokenBlacklist } from 'store/portfolio'
import BN from 'bn.js'
import { useNetworkContractTokens } from 'hooks/networks/useNetworkContractTokens'
import { useNetworks } from 'hooks/networks/useNetworks'
import { getLocalTokenId } from 'store/balance/utils'

const bnZero = new BN(0)

const isGreaterThanZero = (token: LocalTokenWithBalance): boolean =>
token.balance?.gt(bnZero)
token.balance > 0n

const isNotBlacklisted =
(tokenBlacklist: string[]) => (token: LocalTokenWithBalance) =>
Expand Down Expand Up @@ -50,7 +47,7 @@ export function useSearchableTokenList(
return {
...token,
localId: getLocalTokenId(token),
balance: new BN(0),
balance: 0n,
balanceInCurrency: 0,
balanceDisplayValue: '0',
balanceCurrencyDisplayValue: '0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import OvalTagBg from 'components/OvalTagBg'
import Avatar from 'components/Avatar'
import GlobeSVG from 'components/svg/GlobeSVG'
import { useSpendLimits } from 'hooks/useSpendLimits'
import { isHex } from 'viem'
import RpcRequestBottomSheet from '../shared/RpcRequestBottomSheet'
import BalanceChange from './BalanceChange'
import { SpendLimits } from './SpendLimits'
Expand Down Expand Up @@ -250,7 +251,9 @@ const ApprovalPopup = (): JSX.Element => {
updateSpendLimit,
dAppName: request.dappInfo.name,
editingToken: {
defaultValue: spendLimit.tokenApproval.value,
defaultValue: isHex(spendLimit.tokenApproval.value)
? spendLimit.tokenApproval.value
: '0x',
decimals: spendLimit.tokenApproval.token.decimals
}
})
Expand Down
Loading

0 comments on commit ec59c72

Please sign in to comment.