Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting toWei function using window.ethereum

I am simply trying to access a toWei utils function on a front end website in javascript.

"Since we removed our window.web3, MetaMask no longer automatically reloads the page on chain/network changes."
https://docs.metamask.io/guide/provider-migration.html#summary-of-breaking-changes

So I am using window.ethereum which has been fine so far. But I can’t find, even with considerable googling, a direct example of using window.ethereum to access a .toWei(..) function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example, I’d want something like:

var weiVal = window.ethereum.toWei(String(eth_float), 'ether');

But this particular function call doesn’t exist. Can someone quickly show me how to do this? Thanks!

>Solution :

The toWei() function was a part of the removed web3 module, and is not part of the MetaMask browser extension anymore.

Currently 0 results in code: https://github.com/MetaMask/metamask-extension/search?q=toWei


However, you can import the web3 JS package to your frontend and use the function from here.

<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
<script>
    const web3 = new Web3();
    const weiAmount = web3.utils.toWei("1", "ether");
    console.log(weiAmount);
</script>

Source of the minified package: the official web3.js repo – https://github.com/ChainSafe/web3.js

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading