From 5b9d08467e0b9de602efebf219933ab3e87fbba8 Mon Sep 17 00:00:00 2001 From: Pivi Lartisant Date: Thu, 23 May 2024 14:31:06 +0200 Subject: [PATCH] add handle percent (#446) --- src/lib/util/handlePercent.test.ts | 58 ++++++++++++++++++++++++++++++ src/lib/util/handlePercent.ts | 25 +++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 src/lib/util/handlePercent.test.ts create mode 100644 src/lib/util/handlePercent.ts diff --git a/src/lib/util/handlePercent.test.ts b/src/lib/util/handlePercent.test.ts new file mode 100644 index 00000000..05ab6c74 --- /dev/null +++ b/src/lib/util/handlePercent.test.ts @@ -0,0 +1,58 @@ +import { fromMAS } from '@massalabs/web3-utils'; +import { massaToken } from '../massa-react/const'; +import { handlePercent } from './handlePercent'; + +describe('handlePercent', () => { + it('should return correctly formatted amount when no conditions are met', () => { + const result = handlePercent( + 1000000000000000000n, + 25n, + 0n, + 2000000000000000000n, + 18, + 'ETH', + ); + expect(result).toBe('0.250000000000000000'); + }); + + it('should return correctly formatted amount when symbol is massaToken and newAmount is within balance', () => { + const result = handlePercent( + 1000000000n, + 50n, + fromMAS(0.1), + 1000000000000n, + 9, + massaToken, + ); + expect(result).toBe('0.500000000'); + }); + + it('should return 0 when balance minus fees is less than 0', () => { + const result = handlePercent( + 1000000000n, + 100n, + fromMAS(30000), + 2000n, + 9, + massaToken, + ); + expect(result).toBe('0.000000000'); + }); + + it('should return balance minus fees when newAmount exceeds balance', () => { + const result = handlePercent( + 1000000000n, + 100n, + fromMAS(0.1), + 1000000000n, + 9, + massaToken, + ); + expect(result).toBe('0.900000000'); + }); + + it('should handle zero amount correctly', () => { + const result = handlePercent(0n, 10n, 0n, 1000n, 9, massaToken); + expect(result).toBe('0.000000000'); + }); +}); diff --git a/src/lib/util/handlePercent.ts b/src/lib/util/handlePercent.ts new file mode 100644 index 00000000..88704ed1 --- /dev/null +++ b/src/lib/util/handlePercent.ts @@ -0,0 +1,25 @@ +import { massaToken } from '../massa-react/const'; +import { formatAmount } from './parseAmount'; + +export function handlePercent( + amount = 0n, + percent: bigint, + fees: bigint, + balance: bigint, + decimals: number, + symbol: string, +): string { + let newAmount = (amount * percent) / 100n; + + if (symbol === massaToken) { + if (newAmount > balance - fees) { + if (balance - fees < 0) { + newAmount = 0n; + } else { + newAmount = balance - fees; + } + } + } + + return formatAmount(newAmount.toString(), decimals).amountFormattedFull; +}