chore: update bee-js to 0.8.1 version (#78)

* chore: upgrade to bee-js 0.8.1

* refactor: removed toString on number types, Token now accepts numbers

* test: removed fromBZZbaseUnit test, makeBigNumber accepts number now

* chore: fix logic error when displaying Cashout button
This commit is contained in:
Vojtech Simetka
2021-04-23 11:43:48 +02:00
committed by GitHub
parent d77e184d6a
commit a0f1d1c50a
16 changed files with 276 additions and 210 deletions
+4 -6
View File
@@ -10,11 +10,10 @@ import { Snackbar, Container, CircularProgress } from '@material-ui/core'
import { beeDebugApi } from '../services/bee'
import EthereumAddress from './EthereumAddress'
import { fromBZZbaseUnit } from '../utils'
interface Props {
peerId: string
uncashedAmount: number
uncashedAmount: string
}
export default function DepositModal({ peerId, uncashedAmount }: Props): ReactElement {
@@ -76,8 +75,7 @@ export default function DepositModal({ peerId, uncashedAmount }: Props): ReactEl
{loadingCashout && (
<>
<span>
Cashing out <strong>{fromBZZbaseUnit(uncashedAmount).toFixed(7)}</strong> from Peer{' '}
<strong>{peerId}</strong>. Please wait...
Cashing out <strong>{uncashedAmount}</strong> from Peer <strong>{peerId}</strong>. Please wait...
</span>
<Container style={{ textAlign: 'center', padding: '50px' }}>
<CircularProgress />
@@ -86,8 +84,8 @@ export default function DepositModal({ peerId, uncashedAmount }: Props): ReactEl
)}
{!loadingCashout && (
<span>
Are you sure you want to cashout <strong>{fromBZZbaseUnit(uncashedAmount).toFixed(7)} BZZ</strong> from
Peer <strong>{peerId}</strong>?
Are you sure you want to cashout <strong>{uncashedAmount} BZZ</strong> from Peer{' '}
<strong>{peerId}</strong>?
</span>
)}
</DialogContentText>
+1 -1
View File
@@ -48,7 +48,7 @@ export default function WithdrawModal({
if (amountToken === null) return
try {
const { transactionHash } = await action(amountToken.toBigInt)
const { transactionHash } = await action(amountToken.toBigInt as bigint)
setOpen(false)
handleToast(`${successMessage} Transaction ${transactionHash}`)
} catch (e) {
+41 -19
View File
@@ -1,17 +1,27 @@
import { LastCashoutActionResponse, PeerBalance, Settlements } from '@ethersphere/bee-js'
import { LastCashoutActionResponse } from '@ethersphere/bee-js'
import { useEffect, useState } from 'react'
import { Token } from '../models/Token'
import { beeDebugApi } from '../services/bee'
import { useApiPeerBalances, useApiSettlements } from './apiHooks'
import { Balance, Settlement, useApiPeerBalances, useApiSettlements } from './apiHooks'
interface UseAccountingHook {
isLoading: boolean
isLoadingUncashed: boolean
error: Error | null
totalsent: number
totalreceived: number
totalsent: Token
totalreceived: Token
accounting: Accounting[] | null
}
export interface Accounting {
peer: string
uncashedAmount: Token
balance: Token
received: Token
sent: Token
total: Token
}
/**
* Merges the balances, settlements and uncashedAmounts arrays into single array which is sorted by uncashed amounts (if any)
*
@@ -22,8 +32,8 @@ interface UseAccountingHook {
* @returns
*/
function mergeAccounting(
balances?: PeerBalance[],
settlements?: Settlements[],
balances: Balance[] | null,
settlements?: Settlement[],
uncashedAmounts?: LastCashoutActionResponse[],
): Accounting[] | null {
// Settlements or balances are still loading or there is an error -> return null
@@ -34,22 +44,38 @@ function mergeAccounting(
balances.forEach(
// Some peers may not have settlement but all have balance (therefore initialize sent, received and uncashed to 0)
({ peer, balance }) =>
(accounting[peer] = { peer, balance, sent: 0, received: 0, uncashedAmount: 0, total: balance }),
(accounting[peer] = {
peer,
balance,
sent: new Token('0'),
received: new Token('0'),
uncashedAmount: new Token('0'),
total: balance,
}),
)
settlements.forEach(
({ peer, sent, received }) =>
(accounting[peer] = { ...accounting[peer], sent, received, total: accounting[peer].balance + received - sent }),
(accounting[peer] = {
...accounting[peer],
sent,
received,
total: new Token(accounting[peer].balance.toBigNumber.plus(received.toBigNumber).minus(sent.toBigNumber)),
}),
)
// If there are no cheques (and hence last cashout actions), we don't need to sort and can return values right away
if (!uncashedAmounts) return Object.values(accounting)
uncashedAmounts?.forEach(
({ peer, cumulativePayout }) => (accounting[peer].uncashedAmount = accounting[peer].received - cumulativePayout),
)
uncashedAmounts?.forEach(({ peer, cumulativePayout }) => {
accounting[peer].uncashedAmount = new Token(
accounting[peer].received.toBigNumber.minus(cumulativePayout.toString()),
)
})
return Object.values(accounting).sort((a, b) => b.uncashedAmount - a.uncashedAmount)
return Object.values(accounting).sort((a, b) =>
b.uncashedAmount.toBigNumber.minus(a.uncashedAmount.toBigNumber).toNumber(),
)
}
export const useAccounting = (): UseAccountingHook => {
@@ -76,18 +102,14 @@ export const useAccounting = (): UseAccountingHook => {
.finally(() => setIsloadingUncashed(false))
}, [settlements, isLoadingUncashed, uncashedAmounts, error])
const accounting = mergeAccounting(
balances.peerBalances?.balances,
settlements.settlements?.settlements,
uncashedAmounts,
)
const accounting = mergeAccounting(balances.peerBalances, settlements.settlements?.settlements, uncashedAmounts)
return {
isLoading: settlements.isLoadingSettlements || balances.isLoadingPeerBalances,
isLoadingUncashed,
error,
accounting,
totalsent: settlements.settlements?.totalsent || 0,
totalreceived: settlements.settlements?.totalreceived || 0,
totalsent: settlements.settlements?.totalsent || new Token('0'),
totalreceived: settlements.settlements?.totalreceived || new Token('0'),
}
}
+58 -19
View File
@@ -3,11 +3,7 @@ import { useState, useEffect } from 'react'
import {
NodeAddresses,
ChequebookAddressResponse,
ChequebookBalanceResponse,
BalanceResponse,
LastChequesResponse,
AllSettlements,
LastCashoutActionResponse,
Health,
Peer,
Topology,
@@ -16,6 +12,7 @@ import {
import { beeDebugApi, beeApi } from '../services/bee'
import axios from 'axios'
import { Token } from '../models/Token'
export interface HealthHook {
health: boolean
@@ -189,14 +186,19 @@ export const useApiNodePeers = (): NodePeersHook => {
return { peers, isLoading, error }
}
export interface ChequebookBalance {
totalBalance: Token
availableBalance: Token
}
export interface ChequebookBalanceHook {
chequebookBalance: ChequebookBalanceResponse | null
chequebookBalance: ChequebookBalance | null
isLoadingChequebookBalance: boolean
error: Error | null
}
export const useApiChequebookBalance = (): ChequebookBalanceHook => {
const [chequebookBalance, setChequebookBalance] = useState<ChequebookBalanceResponse | null>(null)
const [chequebookBalance, setChequebookBalance] = useState<ChequebookBalance | null>(null)
const [isLoadingChequebookBalance, setLoading] = useState<boolean>(true)
const [error, setError] = useState<Error | null>(null)
@@ -204,8 +206,12 @@ export const useApiChequebookBalance = (): ChequebookBalanceHook => {
setLoading(true)
beeDebugApi.chequebook
.balance()
.then(res => {
setChequebookBalance(res)
.then(({ totalBalance, availableBalance }) => {
const balance = {
totalBalance: new Token(totalBalance),
availableBalance: new Token(availableBalance),
}
setChequebookBalance(balance)
})
.catch(error => {
setError(error)
@@ -218,14 +224,19 @@ export const useApiChequebookBalance = (): ChequebookBalanceHook => {
return { chequebookBalance, isLoadingChequebookBalance, error }
}
export interface Balance {
peer: string
balance: Token
}
export interface PeerBalanceHook {
peerBalances: BalanceResponse | null
peerBalances: Balance[] | null
isLoadingPeerBalances: boolean
error: Error | null
}
export const useApiPeerBalances = (): PeerBalanceHook => {
const [peerBalances, setPeerBalances] = useState<BalanceResponse | null>(null)
const [peerBalances, setPeerBalances] = useState<Balance[] | null>(null)
const [isLoadingPeerBalances, setLoading] = useState<boolean>(true)
const [error, setError] = useState<Error | null>(null)
@@ -234,7 +245,9 @@ export const useApiPeerBalances = (): PeerBalanceHook => {
beeDebugApi.balance
.balances()
.then(res => {
setPeerBalances(res)
// for some reason sometimes these are numbers and not BigInts
const balances = res.balances.map(({ peer, balance }) => ({ peer, balance: new Token(balance) }))
setPeerBalances(balances)
})
.catch(error => {
setError(error)
@@ -305,14 +318,26 @@ export const useApiPeerLastCheque = (peerId: string): PeerLastChequesHook => {
return { peerCheque, isLoadingPeerCheque, error }
}
export interface Settlement {
peer: string
received: Token
sent: Token
}
export interface Settlements {
totalreceived: Token
totalsent: Token
settlements: Settlement[]
}
export interface SettlementsHook {
settlements: AllSettlements | null
settlements: Settlements | null
isLoadingSettlements: boolean
error: Error | null
}
export const useApiSettlements = (): SettlementsHook => {
const [settlements, setSettlements] = useState<AllSettlements | null>(null)
const [settlements, setSettlements] = useState<Settlements | null>(null)
const [isLoadingSettlements, setLoading] = useState<boolean>(true)
const [error, setError] = useState<Error | null>(null)
@@ -320,8 +345,17 @@ export const useApiSettlements = (): SettlementsHook => {
setLoading(true)
beeDebugApi.settlements
.getSettlements()
.then(res => {
setSettlements(res)
.then(({ totalreceived, settlements, totalsent }) => {
const set = {
totalreceived: new Token(totalreceived),
totalsent: new Token(totalsent),
settlements: settlements.map(({ peer, received, sent }) => ({
peer,
received: new Token(received),
sent: new Token(sent),
})),
}
setSettlements(set)
})
.catch(error => {
setError(error)
@@ -334,14 +368,19 @@ export const useApiSettlements = (): SettlementsHook => {
return { settlements, isLoadingSettlements, error }
}
export interface LastCashout {
peer: string
cumulativePayout: Token
}
export interface PeerLastCashoutHook {
peerCashout: LastCashoutActionResponse | null
peerCashout: LastCashout | null
isLoadingPeerCashout: boolean
error: Error | null
}
export const useApiPeerLastCashout = (peerId: string): PeerLastCashoutHook => {
const [peerCashout, setPeerCashout] = useState<LastCashoutActionResponse | null>(null)
const [peerCashout, setPeerCashout] = useState<LastCashout | null>(null)
const [isLoadingPeerCashout, setLoading] = useState<boolean>(true)
const [error, setError] = useState<Error | null>(null)
@@ -349,8 +388,8 @@ export const useApiPeerLastCashout = (peerId: string): PeerLastCashoutHook => {
setLoading(true)
beeDebugApi.chequebook
.getPeerLastCashout(peerId)
.then(res => {
setPeerCashout(res)
.then(({ peer, cumulativePayout }) => {
setPeerCashout({ peer, cumulativePayout: new Token(cumulativePayout) })
})
.catch(error => {
setError(error)
+10 -1
View File
@@ -1,4 +1,6 @@
import { ChequebookAddressResponse } from '@ethersphere/bee-js'
import {
ChequebookBalance,
useApiChequebookAddress,
useApiChequebookBalance,
useApiHealth,
@@ -8,6 +10,11 @@ import {
useLatestBeeRelease,
} from './apiHooks'
export interface StatusChequebookHook extends StatusHookCommon {
chequebookBalance: ChequebookBalance | null
chequebookAddress: ChequebookAddressResponse | null
}
export const useStatusNodeVersion = (): StatusNodeVersionHook => {
const { latestBeeRelease, isLoadingLatestBeeRelease } = useLatestBeeRelease()
const { nodeHealth, isLoadingNodeHealth } = useDebugApiHealth()
@@ -66,7 +73,9 @@ export const useStatusChequebook = (): StatusChequebookHook => {
return {
isLoading: isLoadingChequebookAddress || isLoadingChequebookBalance,
isOk:
Boolean(chequebookAddress?.chequebookaddress) && chequebookBalance !== null && chequebookBalance.totalBalance > 0,
Boolean(chequebookAddress?.chequebookaddress) &&
chequebookBalance !== null &&
chequebookBalance?.totalBalance.toBigNumber.isGreaterThan(0),
chequebookBalance,
chequebookAddress,
}
+7 -3
View File
@@ -10,7 +10,7 @@ export class Token {
private amount: BigNumber // Represented in the base units, so it is always an integer value
private readonly decimals: digits
constructor(amount: BigNumber | string | bigint, decimals: digits = BZZ_DECIMALS) {
constructor(amount: BigNumber | string | BigInt, decimals: digits = BZZ_DECIMALS) {
const a = makeBigNumber(amount)
if (!isInteger(a) || !POSSIBLE_DECIMALS.includes(decimals)) throw new TypeError('Not a valid token values')
@@ -29,7 +29,7 @@ export class Token {
*
* @returns new Token
*/
static fromDecimal(amount: BigNumber | string | bigint, decimals: digits = BZZ_DECIMALS): Token | never {
static fromDecimal(amount: BigNumber | string | BigInt, decimals: digits = BZZ_DECIMALS): Token | never {
const a = makeBigNumber(amount)
// No need to do any validation here, it is done when the new token is created
@@ -38,7 +38,7 @@ export class Token {
return new Token(t, decimals)
}
get toBigInt(): bigint {
get toBigInt(): BigInt {
return BigInt(this.amount.toFixed(0))
}
@@ -53,4 +53,8 @@ export class Token {
get toDecimal(): BigNumber {
return this.amount.dividedBy(new BigNumber(10).pow(this.decimals))
}
toFixedDecimal(digits = 7): string {
return this.toDecimal.toFixed(digits)
}
}
+8 -13
View File
@@ -6,9 +6,8 @@ import { Skeleton } from '@material-ui/lab'
import WithdrawModal from '../../containers/WithdrawModal'
import DepositModal from '../../containers/DepositModal'
import { fromBZZbaseUnit } from '../../utils'
import type { ChequebookAddressResponse } from '@ethersphere/bee-js'
import { Token } from '../../models/Token'
const useStyles = makeStyles((theme: Theme) =>
createStyles({
@@ -34,15 +33,15 @@ const useStyles = makeStyles((theme: Theme) =>
)
interface ChequebookBalance {
totalBalance: number
availableBalance: number
totalBalance: Token
availableBalance: Token
}
interface Props {
chequebookAddress: ChequebookAddressResponse | null
chequebookBalance: ChequebookBalance | null
totalsent: number
totalreceived: number
totalsent: Token
totalreceived: Token
isLoading: boolean
}
@@ -66,24 +65,20 @@ function AccountCard({ totalreceived, totalsent, chequebookBalance, isLoading }:
<Typography component="h2" variant="h6" color="primary" gutterBottom>
Total Balance
</Typography>
<Typography variant="h5">
{fromBZZbaseUnit(chequebookBalance?.totalBalance || 0).toFixed(7)} BZZ
</Typography>
<Typography variant="h5">{chequebookBalance?.totalBalance.toFixedDecimal()} BZZ</Typography>
</div>
<div>
<Typography component="h2" variant="h6" color="primary" gutterBottom>
Available Uncommitted Balance
</Typography>
<Typography variant="h5">
{fromBZZbaseUnit(chequebookBalance?.availableBalance || 0).toFixed(7)} BZZ
</Typography>
<Typography variant="h5">{chequebookBalance?.availableBalance.toFixedDecimal()} BZZ</Typography>
</div>
<div>
<Typography component="h2" variant="h6" color="primary" gutterBottom>
Total Sent / Received
</Typography>
<Typography variant="h5">
{fromBZZbaseUnit(totalsent).toFixed(7)} / {fromBZZbaseUnit(totalreceived).toFixed(7)} BZZ
{totalsent.toFixedDecimal()} / {totalreceived.toFixedDecimal()} BZZ
</Typography>
</div>
</CardContent>
+12 -8
View File
@@ -2,10 +2,10 @@ import type { ReactElement } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import { Table, TableBody, TableCell, TableContainer, TableRow, TableHead, Paper } from '@material-ui/core'
import { fromBZZbaseUnit } from '../../utils'
import ClipboardCopy from '../../components/ClipboardCopy'
import CashoutModal from '../../components/CashoutModal'
import PeerDetailDrawer from './PeerDetail'
import { Accounting } from '../../hooks/accounting'
const useStyles = makeStyles({
table: {
@@ -52,32 +52,36 @@ function BalancesTable({ accounting, isLoadingUncashed }: Props): ReactElement |
<TableCell className={classes.values}>
<span
style={{
color: balance > 0 ? '#32c48d' : '#c9201f',
color: balance.toBigNumber.isPositive() ? '#32c48d' : '#c9201f',
}}
>
{fromBZZbaseUnit(balance).toFixed(7).toLocaleString()}
{balance.toFixedDecimal()}
</span>{' '}
BZZ
</TableCell>
<TableCell className={classes.values}>
-{fromBZZbaseUnit(sent).toFixed(7)} / {fromBZZbaseUnit(received).toFixed(7)} BZZ
-{sent.toFixedDecimal()} / {received.toFixedDecimal()} BZZ
</TableCell>
<TableCell className={classes.values}>
<span
style={{
color: total > 0 ? '#32c48d' : '#c9201f',
color: total.toBigNumber.isPositive() ? '#32c48d' : '#c9201f',
}}
>
{fromBZZbaseUnit(total).toFixed(7)}
{total.toFixedDecimal()}
</span>{' '}
BZZ
</TableCell>
<TableCell className={classes.values}>
{isLoadingUncashed && 'loading...'}
{!isLoadingUncashed && <>{uncashedAmount > 0 ? fromBZZbaseUnit(uncashedAmount).toFixed(7) : '0'} BZZ</>}
{!isLoadingUncashed && (
<>{uncashedAmount.toBigNumber.isGreaterThan('0') ? uncashedAmount.toFixedDecimal() : '0'} BZZ</>
)}
</TableCell>
<TableCell className={classes.values}>
{uncashedAmount > 0 && <CashoutModal uncashedAmount={uncashedAmount} peerId={peer} />}
{uncashedAmount.toBigNumber.isGreaterThan('0') && (
<CashoutModal uncashedAmount={uncashedAmount.toFixedDecimal()} peerId={peer} />
)}
</TableCell>
</TableRow>
))}
+1 -1
View File
@@ -63,7 +63,7 @@ export default function Accounting(): ReactElement {
/>
{error && (
<Container style={{ textAlign: 'center', padding: '50px' }}>
Error loading accountin details: {error.message}
Error loading accounting details: {error.message}
</Container>
)}
{!error && <BalancesTable accounting={accounting} isLoadingUncashed={isLoadingUncashed} />}
+1
View File
@@ -9,6 +9,7 @@ import VersionCheck from './SetupSteps/VersionCheck'
import EthereumConnectionCheck from './SetupSteps/EthereumConnectionCheck'
import ChequebookDeployFund from './SetupSteps/ChequebookDeployFund'
import PeerConnection from './SetupSteps/PeerConnection'
import { StatusChequebookHook } from '../../hooks/status'
const useStyles = makeStyles((theme: Theme) =>
createStyles({
@@ -2,6 +2,7 @@ import { Typography } from '@material-ui/core/'
import EthereumAddress from '../../../components/EthereumAddress'
import DepositModal from '../../../containers/DepositModal'
import type { ReactElement } from 'react'
import type { StatusChequebookHook } from '../../../hooks/status'
interface Props extends StatusChequebookHook {
ethereumAddress?: string
@@ -21,7 +22,7 @@ const ChequebookDeployFund = ({
{chequebookAddress?.chequebookaddress && <DepositModal />}
</p>
<div style={{ marginBottom: '10px' }}>
{!(chequebookAddress?.chequebookaddress && chequebookBalance?.totalBalance > 0) && (
{!(chequebookAddress?.chequebookaddress && chequebookBalance?.totalBalance.toBigNumber.isGreaterThan(0)) && (
<div>
<span>
Your chequebook is either not deployed or funded. Join{' '}
-14
View File
@@ -21,17 +21,3 @@ interface StatusEthereumConnectionHook extends StatusHookCommon {
interface StatusTopologyHook extends StatusHookCommon {
topology: Topology | null
}
interface StatusChequebookHook extends StatusHookCommon {
chequebookBalance: ChequebookBalanceResponse | null
chequebookAddress: ChequebookAddressResponse | null
}
interface Accounting {
peer: string
uncashedAmount: number
balance: number
received: number
sent: number
total: number
}
+5 -16
View File
@@ -1,21 +1,7 @@
import BigNumber from 'bignumber.js'
import { fromBZZbaseUnit, isInteger, makeBigNumber } from './index'
import { isInteger, makeBigNumber } from './index'
describe('utils', () => {
describe('fromBZZbaseUnit', () => {
const values = [
{ bzz: 0, baseUnits: 0 },
{ bzz: 0.1, baseUnits: 1e15 },
{ bzz: 0.9, baseUnits: 9e15 },
]
values.forEach(({ bzz, baseUnits }) => {
test(`converting ${bzz} => ${baseUnits}`, () => {
expect(fromBZZbaseUnit(baseUnits)).toBe(bzz)
})
})
})
describe('isInteger', () => {
const correctValues = [
BigInt(0),
@@ -52,8 +38,11 @@ describe('utils', () => {
new BigNumber('1'),
new BigNumber('0'),
new BigNumber('-1'),
0,
1,
-1,
]
const wrongValues = [new Function(), 0, 1]
const wrongValues = [new Function()]
correctValues.forEach(v => {
test(`testing ${v}`, () => {
+5 -19
View File
@@ -1,22 +1,5 @@
import { BigNumber } from 'bignumber.js'
/**
* @deprecated Should be removed in favour of Token class
*/
const BZZ_BASE_UNIT = 1e16
/**
* Convert from base units of BZZ token to BZZ
* @deprecated This should only be used for displaying values, it's unsafe and should be replaced with Token class
*
* @param amount Amount in base units of BZZ token
*
* @returns amount in BZZ
*/
export const fromBZZbaseUnit = (amount: number): number => {
return amount / BZZ_BASE_UNIT
}
/**
* Test if value is an integer
*
@@ -37,12 +20,15 @@ export function isInteger(value: unknown): value is BigNumber | bigint {
*
* @returns BigNumber - but it may still be NaN or Infinite
*/
export function makeBigNumber(value: BigNumber | bigint | string): BigNumber | never {
export function makeBigNumber(value: BigNumber | BigInt | number | string): BigNumber | never {
if (BigNumber.isBigNumber(value)) return value
if (typeof value === 'string') return new BigNumber(value)
if (typeof value === 'bigint') return new BigNumber(value.toString())
throw new TypeError('Not a BigNumber or BigNumber convertible value')
// FIXME: bee-js still returns some values as numbers and even outside of SAFE INTEGER bounds
if (typeof value === 'number' /* && Number.isSafeInteger(value)*/) return new BigNumber(value)
throw new TypeError(`Not a BigNumber or BigNumber convertible value. Type: ${typeof value} value: ${value}`)
}