1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-11-13 16:54:53 +01:00

use decimal.js for price comparison

This commit is contained in:
Matthias Kretschmann 2020-08-11 09:30:17 +02:00
parent e7b17a9d65
commit 5ce00c9ddc
Signed by: m
GPG Key ID: 606EEEF3C479A91F
3 changed files with 16 additions and 22 deletions

View File

@ -34,6 +34,7 @@
"axios": "^0.19.2",
"classnames": "^2.2.6",
"date-fns": "^2.15.0",
"decimal.js": "^10.2.0",
"dotenv": "^8.2.0",
"ethereum-blockies": "github:MyEtherWallet/blockies",
"filesize": "^6.1.0",

View File

@ -6,7 +6,7 @@ import { MetadataMarket } from '../../../@types/Metadata'
import { DDO } from '@oceanprotocol/lib'
import Tabs from '../../atoms/Tabs'
import { useOcean } from '@oceanprotocol/react'
import compareAsBN, { Comparison } from '../../../utils/compareAsBN'
import compareAsBN from '../../../utils/compareAsBN'
export default function AssetActions({
metadata,
@ -26,9 +26,7 @@ export default function AssetActions({
if (!price || !balance || !balance.ocean) return
const isFree = price === '0'
setIsBalanceSufficient(
isFree ? true : compareAsBN(balance.ocean, price, Comparison.gte)
)
setIsBalanceSufficient(isFree ? true : compareAsBN(balance.ocean, price))
return () => {
setIsBalanceSufficient(false)

View File

@ -1,21 +1,16 @@
import BN from 'bn.js'
import { Decimal } from 'decimal.js'
export enum Comparison {
'lt' = 'lt',
'lte' = 'lte',
'gt' = 'gt',
'gte' = 'gte',
'eq' = 'eq'
}
// Run decimal.js comparison
// http://mikemcl.github.io/decimal.js/#cmp
export default function compareAsBN(balance: string, price: string): boolean {
const aBN = new Decimal(balance)
const bBN = new Decimal(price)
const compare = aBN.comparedTo(bBN)
// Run the corresponding bn.js comparison:
// https://github.com/indutny/bn.js/#utilities
export default function compareAsBN(
a: string,
b: string,
comparison: Comparison
): boolean {
const aBN = new BN(a)
const bBN = new BN(b)
return aBN[comparison](bBN)
switch (compare) {
case 1 || 0: // balance is greater or equal to price
return true
default:
return false
}
}