Skip to content

Commit

Permalink
Change byte parser (#165)
Browse files Browse the repository at this point in the history
Co-authored-by: Filip Lelek <[email protected]>
  • Loading branch information
Filip-L and filip-neti authored Dec 8, 2024
1 parent ca14bd5 commit ad09248
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 93 deletions.
25 changes: 14 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@
"@types/node": "20.3.1",
"@types/react": "18.2.12",
"@types/react-dom": "18.2.5",
"@wtfcode/byte-converter": "1.7.11",
"@zondax/filecoin-signing-tools": "^0.7.1",
"@zondax/ledger-filecoin": "^0.13.0",
"autoprefixer": "10.4.14",
"axios": "^1.6.8",
"bufferutil": "^4.0.8",
"bytes-iec": "^3.1.1",
"class-variance-authority": "^0.6.1",
"clsx": "^2.0.0",
"encoding": "^0.1.13",
Expand Down
2 changes: 1 addition & 1 deletion src/components/AllocatorBalance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ const AllocatorBalance: React.FC<ComponentProps> = ({ owner, repo }) => {

if (balance === null) return

return <div>Allocator&apos;s DataCap balance: {bytesToiB(balance, true)}</div>
return <div>Allocator&apos;s DataCap balance: {bytesToiB(balance)}</div>
}

export default AllocatorBalance
2 changes: 1 addition & 1 deletion src/components/AppHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const AppHistory: React.FC<ComponentProps> = ({
0,
)

const totalAllocationFormatted = bytesToiB(totalAllocation, true)
const totalAllocationFormatted = bytesToiB(totalAllocation)

return (
<>
Expand Down
13 changes: 4 additions & 9 deletions src/components/cards/AppInfoCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,23 +241,19 @@ const AppInfoCard: React.FC<ComponentProps> = ({
if (allocationAmount === 0) {
setIsProgressBarVisible(true)
setProgress(100)
setAllocationProgressDesc(
`${bytesToiB(0, true)} / ${lastAllocationUnit}`,
)
setAllocationProgressDesc(`${bytesToiB(0)} / ${lastAllocationUnit}`)
return
}

if (allocationAmount < allowance) {
setIsProgressBarVisible(true)
setProgress(0)
setAllocationProgressDesc(
`${bytesToiB(0, true)} / ${lastAllocationUnit}`,
)
setAllocationProgressDesc(`${bytesToiB(0)} / ${lastAllocationUnit}`)
return
}

const usedDatacap = allocationAmount - allowance
const usedDatacapUnit = bytesToiB(usedDatacap, true)
const usedDatacapUnit = bytesToiB(usedDatacap)

const progressPercentage = (usedDatacap / allocationAmount) * 100
setIsProgressBarVisible(true)
Expand Down Expand Up @@ -827,8 +823,7 @@ const AppInfoCard: React.FC<ComponentProps> = ({
return
}

const isBinary = datacapWithoutS.toLowerCase().includes('ib')
const againToText = bytesToiB(bytes, isBinary)
const againToText = bytesToiB(bytes)

return againToText
}
Expand Down
1 change: 0 additions & 1 deletion src/components/ui/progress-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
)
`,
transition: 'width 1s ease-in-out',
width: `${progress}%`,
}}
className="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center w-full"
></div>
Expand Down
4 changes: 1 addition & 3 deletions src/helpers/calculateAmountToRefill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ export default function calculateAmountToRequest(
return retObj
}

const [amount, amountType] = splitString(
bytesToiB(Math.floor(nextRequest), true),
)
const [amount, amountType] = splitString(bytesToiB(Math.floor(nextRequest)))
const matchedAvailableType = Object.values(RefillUnit).find(
(type) => type === amountType,
)
Expand Down
75 changes: 22 additions & 53 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import {
type AllocationRequest,
type Application,
type ByteConverterAutoscaleOptions,
} from '@/type'
import ByteConverter from '@wtfcode/byte-converter'
import { type AllocationRequest, type Application } from '@/type'
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'

import bytes from 'bytes-iec'
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs))
}
Expand All @@ -27,26 +22,21 @@ export const getCurrentDate = (): string => {
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}${nanoseconds} UTC`
}

const byteConverter = new ByteConverter()

/**
* This function is used to convert string formatted bytes to bytes
*
* @param inputDatacap
* @returns number
*/
export function anyToBytes(inputDatacap: string): number {
const formatDc = inputDatacap
.replace(/[t]/g, 'T')
.replace(/[b]/g, 'B')
.replace(/[p]/g, 'P')
.replace(/[I]/g, 'i')
.replace(/\s*/g, '')
const ext = formatDc.replace(/[0-9.]/g, '')
const datacap = formatDc.replace(/[^0-9.]/g, '')
try {
const bytes = byteConverter.convert(parseFloat(datacap), ext, 'B')
return bytes
const parsedBytes = bytes.parse(inputDatacap)
if (parsedBytes) {
return parsedBytes
} else {
console.error(`Failed to parse string ${inputDatacap} into bytes`)
return 0
}
} catch (e) {
console.error(e)
return 0
Expand Down Expand Up @@ -92,47 +82,26 @@ export const shortenUrl = (
* @param inputBytes
* @returns string
*/
export function bytesToiB(inputBytes: number, isBinary: boolean): string {
const options: {
preferByte: boolean
preferBinary: boolean
preferDecimal: boolean
} = {
preferByte: true,
preferBinary: isBinary,
preferDecimal: !isBinary,
}
let autoscale = byteConverter.autoScale(
inputBytes,
'B',
options as ByteConverterAutoscaleOptions,
)
let stringVal = ''
if (autoscale.dataFormat === 'YiB') {
autoscale = byteConverter.autoScale(
inputBytes - 32,
'B',
options as ByteConverterAutoscaleOptions,
)
return `${autoscale.value.toFixed(1)}${autoscale.dataFormat}`
export function bytesToiB(inputBytes: number): string {
try {
const parsedValue = bytes(inputBytes, { mode: 'binary' })
if (parsedValue) {
return parsedValue
} else {
console.error(`Failed to parse bytes ${inputBytes} into string`)
return '0GiB'
}
} catch (e) {
console.error(e)
return '0GiB'
}
stringVal = String(autoscale.value)

const indexOfDot = stringVal.indexOf('.')
return `${stringVal.substring(
0,
indexOfDot > 0 ? indexOfDot : stringVal.length,
)}${indexOfDot > 0 ? stringVal.substring(indexOfDot, indexOfDot + 3) : ''}${
autoscale.dataFormat
}`
}

export const calculateDatacap = (
percentage: string,
totalDatacap: string,
): string => {
const isBinary = totalDatacap.toLowerCase().includes('ib')
const totalBytes = anyToBytes(totalDatacap)
const datacap = totalBytes * (parseFloat(percentage) / 100)
return bytesToiB(datacap, isBinary)
return bytesToiB(datacap)
}
13 changes: 0 additions & 13 deletions src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,19 +207,6 @@ export interface Allocator {
client_contract_address: string | null
}

export interface ByteConverterAutoscaleOptions {
preferByte: boolean
preferBit: boolean
preferBinary: boolean
preferDecimal: boolean
preferSameBase: boolean
preferOppositeBase: boolean
preferSameUnit: boolean
preferOppositeUnit: boolean
// eslint-disable-next-line @typescript-eslint/ban-types
handler: (curDataFormat: string, isUppingDataFormat: boolean) => {}
}

export enum AllocatorTypeEnum {
DIRECT = 'direct',
CONTRACT = 'contract',
Expand Down

0 comments on commit ad09248

Please sign in to comment.