Skip to content

Commit

Permalink
add handle percent (#446)
Browse files Browse the repository at this point in the history
  • Loading branch information
pivilartisant authored May 23, 2024
1 parent 43f4e99 commit 5b9d084
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
58 changes: 58 additions & 0 deletions src/lib/util/handlePercent.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
25 changes: 25 additions & 0 deletions src/lib/util/handlePercent.ts
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit 5b9d084

Please sign in to comment.