Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

(Source: 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.

For example, I'd want something like:

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

But this particular function call doesn't exist. How can I do this?

like image 210
JDS Avatar asked Nov 19 '25 19:11

JDS


1 Answers

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

like image 198
Petr Hejda Avatar answered Nov 21 '25 10:11

Petr Hejda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!