7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

web3.jsでMetamaskに保有しているETHの情報を取得する

Posted at

最近仕事でweb3.jsを触る機会があり、Metamaskにアクセスして保有ETHの情報を取得する方法をまとめました

サンプル

Metamskのアカウント情報(複数ある場合は最初のアカウント)を取得し、保有ETH情報を表示するサンプルです。
※Chrome拡張のMetamaskをインストールしないと起動しませんのでご注意ください

See the Pen metamask web3.js by Kurokiri (@kurokiri) on CodePen.

処理説明

await window.ethereum.request({ method: 'eth_requestAccounts' });

ここでMetamaskで作成したアカウント情報を取得します。Metamaskではアカウントは複数作成できますが現在選択しているアカウントが取得されます。

const ownedWei = await web3.eth.getBalance(account[0]);

web3.jsのweb3.eth.getBalanceを用いて保有ETHを取得しています。
ここで取得される値の単位はWeiと言ってETHの最小単位で
1Wei = 0.000000000000000001ETH
となります。

const ownedEth = web3.utils.fromWei(ownedWei, 'ether');

値の単位がWeiからETHになるよう変換しています。これでMetamsk上に表示される保有ETHと同じ値になります。

まとめ

今回テストネットは考えずにイーサリアムメインネット前提でサンプルを実装しましたが、ChainIDで処理を分ければテストネット毎の制御は可能です。
web3.js自体あまり触る機会はないかもしれませんが、試すと面白いので興味を持った方は是非触ってみてください!

リファレンス

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?