Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: resolve exponential number #111

Merged
1 commit merged into from
Nov 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions src/utils/web3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,27 @@ export function getContract(
*
*/

export function parseEther(ether: string) {
// See: node_modules/@ethersproject/bignumber/src.ts/fixednumber.ts
const WEI_UNIT = 18;
let zeros = '0';
while (zeros.length < WEI_UNIT) {
zeros += zeros;
}
// Returns a string "1" followed by decimal "0"s
function getMultiplier(decimals: ethers.BigNumberish): string {
if (typeof decimals !== 'number') {
try {
decimals = BigNumber.from(decimals).toNumber();
} catch (e) {}
}

if (typeof decimals !== 'number' || decimals < 0 || decimals > WEI_UNIT)
return '1';

return '1' + zeros.substring(0, decimals);
}

export function parseEther(ether: string): BigNumber {
if (ether.includes('e')) {
// Parse
const integerPart = ether.match(/^([0-9])+e/);
Expand All @@ -75,12 +95,16 @@ export function parseEther(ether: string) {
return BigNumber.from(0);
}

// resolve exponential number
const pow = !isNegative
? 18 + Number(exponentialPart[1])
: 18 - Number(exponentialPart[1]);
return BigNumber.from(integerPart[1]).pow(pow);
// Resolve exponential number
// Plus 18 to convert ETH to WEI
const pow = getMultiplier(
!isNegative
? Number(exponentialPart[1]) + 18
: -Number(exponentialPart[1]) + 18
);
return BigNumber.from(integerPart[1]).mul(pow);
}

return ethers.utils.parseEther(ether);
}

Expand Down