Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

web3.utils.toWei(amount, ether) fix required when decimals in input are overflown. #7044

Closed
hammersharkfish opened this issue May 16, 2024 · 2 comments
Labels
4.x 4.0 related Bug Addressing a bug

Comments

@hammersharkfish
Copy link

MRE :

x = "1.123456789123456789123"
const amountInWei = web3.utils.toWei(x, 'ether')

console.log(amountInWei, typeof(amountInWei))

Output: 1123456789123456789123 string .
This output is equivalent to 1123.456789123456789123 ether while we provided 1.123456789123456789123 as input .

@hammersharkfish
Copy link
Author

hammersharkfish commented May 16, 2024

converter.ts

	// if value is decimal e.g. 24.56 extract `integer` and `fraction` part
	// to avoid `fraction` to be null use `concat` with empty string
	const [integer, fraction] = String(
		typeof number === 'string' && !isHexStrict(number) ? number : toNumber(number),
	)
		.split('.')
		.concat('');

	// join the value removing `.` from
	// 24.56 -> 2456
	const value = BigInt(`${integer}${fraction}`);

	// multiply value with denomination
	// 2456 * 1000000 -> 2456000000
	const updatedValue = value * denomination;

const value = BigInt(`${integer}${fraction}`);
This part is concatenating the integer and fraction together resulting in digits after the 18th decimal place from fraction side also joining the integer side . The user can provide >18 decimal places string input either mistakenly or by design thinking that the method will approximate it for him .

@jdevcs jdevcs changed the title web3.utils.toWei(amount, ether) giving incorrect and dangerously large value when decimals in input are overflown. web3.utils.toWei(amount, ether) fix required when decimals in input are overflown. May 17, 2024
gordon-to added a commit to gordon-to/web3.js that referenced this issue May 17, 2024
@mconnelly8 mconnelly8 added Bug Addressing a bug 4.x 4.0 related labels May 17, 2024
@mconnelly8
Copy link

Thanks @hammersharkfish. We are currently working on this.

gordon-to added a commit to gordon-to/web3.js that referenced this issue May 21, 2024
luu-alex pushed a commit that referenced this issue May 21, 2024
* fix(#7044): fix too many decimals passed to toWei

* add test case

* add tests and fix fromWei

* add changelog and update tests

* update test

---------

Co-authored-by: Alex Luu <alex.luu@mail.utoronto.ca>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
4.x 4.0 related Bug Addressing a bug
Projects
None yet
Development

No branches or pull requests

3 participants