0
0

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.

デプロイしたコントラクトのメソッドをethers.jsで呼び出す

Posted at

やりたかったこと

ethers.jsを使ってデプロイ済みのコントラクト(MetaCoin)のcallメソッドを呼び出してあるアドレスのMetaCoinの所有数を取得すること。

前提

大まかな手順

  1. ethersをインポートしておく
  2. コントラクトのインスタンスを作る
  3. HexからDecに変換する
const { ethers } = require('ethers')

/**
 * get user' balance
 * @return {Object} user
 */
module.exports = async () => {
  // local で Ganache を走らせている
  const url = 'http://localhost:7545'
  const provider = new ethers.providers.JsonRpcProvider(url)
  // コントラクトインスタンスを作成する
  const metaCoinAddress = '0x0eF0b8157aE5E19bEb6A3e285Dcc9115CfFCC5D3'
  const metaCoinAbi = [{ inputs: [], payable: false, stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, inputs: [{ indexed: true, internalType: 'address', name: '_from', type: 'address' }, { indexed: true, internalType: 'address', name: '_to', type: 'address' }, { indexed: false, internalType: 'uint256', name: '_value', type: 'uint256' }], name: 'Transfer', type: 'event' }, { constant: false, inputs: [{ internalType: 'address', name: 'receiver', type: 'address' }, { internalType: 'uint256', name: 'amount', type: 'uint256' }], name: 'sendCoin', outputs: [{ internalType: 'bool', name: 'sufficient', type: 'bool' }], payable: false, stateMutability: 'nonpayable', type: 'function' }, { constant: true, inputs: [{ internalType: 'address', name: 'addr', type: 'address' }], name: 'getBalanceInEth', outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }], payable: false, stateMutability: 'view', type: 'function' }, { constant: true, inputs: [{ internalType: 'address', name: 'addr', type: 'address' }], name: 'getBalance', outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }], payable: false, stateMutability: 'view', type: 'function' }]
  const contract = new ethers.Contract(metaCoinAddress, metaCoinAbi, provider)
  // getBalance で、accounts[0]のMetaCoinのbalanceのバランスを取得
  const { getBalance } = contract.functions
  const accounts = await provider.listAccounts()
  const providerCoinBalance = await getBalance(accounts[0])
  // Hexadecimal to Decimal
  return parseInt(providerCoinBalance[0]._hex, 16)
}

どなたかの参考になれば幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?