LoginSignup
7
4

More than 5 years have passed since last update.

Web3.js で ERC20 トークンの残高を取得

Last updated at Posted at 2018-05-21
  • この記事のサンプルで使用している Web3.js のバージョンは 0.20.6 です。

Contract を扱うための ABI を用意

  • ABI は、スマートコントラクトがどのような関数や状態変数を持っているかといった情報をもったインタフェースです。
  • Web3.js のプログラムからスマートコントラクトを扱う際は、このABIの情報に基づいて関数を読んだりや状態変数の値を読みます。
  • 通常、ABI にはあるスマートコントラクトが持っているすべての関数や状態変数の情報が記載されますが、ERC20 トークンの残高を取得するには、getBalance という関数と decimals という状態変数の値を読むことができればいいので、この記事ではその2つのみを ABI に記載します。

getBalance と decimals の情報のみを持つABI

let minABI = [
       // balanceOf
       {
         "constant":true,
         "inputs":[{"name":"_owner","type":"address"}],
         "name":"balanceOf",
         "outputs":[{"name":"balance","type":"uint256"}],
         "type":"function"
       },
       // decimals
       {
         "constant":true,
         "inputs":[],
         "name":"decimals",
         "outputs":[{"name":"","type":"uint8"}],
         "type":"function"
       }
     ];

サンプルコード

  • 任意のERC20トークンのアドレスと、そのERC20トークンの残高を知りたいウォレットアドレスから、ERC20トークンの残高を取得するサンプルコードです。
let tokenAddress = "REPLACE_WITH_ERC20_TOKEN_ADDRESS";
let walletAddress = "REPLACE_WITH_WALLET_ADDRESS";

// ERC20 トークンの残高を取得するための最小限のABI
let minABI = [
  // balanceOf
  {
    "constant":true,
    "inputs":[{"name":"_owner","type":"address"}],
    "name":"balanceOf",
    "outputs":[{"name":"balance","type":"uint256"}],
    "type":"function"
  },
  // decimals
  {
    "constant":true,
    "inputs":[],
    "name":"decimals",
    "outputs":[{"name":"","type":"uint8"}],
    "type":"function"
  }
];

//  ABI とコントラクト(ERC20トークン)のアドレスから、コントラクトのインスタンスを取得 
let contract = web3.eth.contract(minABI).at(tokenAddress);

// 引数にウォレットのアドレスを渡して、balanceOf 関数を呼ぶ
contract.balanceOf(walletAddress, (error, balance) => {
  // ERC20トークンの decimals を取得
  contract.decimals((error, decimals) => {
    // 残高を計算
    balance = balance.div(10**decimals);
    console.log(balance.toString());
  });
});

デモ

Note

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