ユーザ用ツール

サイト用ツール


blockchain:ether.jsを使用したdapps開発

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

次のリビジョン
前のリビジョン
blockchain:ether.jsを使用したdapps開発 [2022/05/08 11:31] – 作成 dotblockchain:ether.jsを使用したdapps開発 [2022/08/04 08:56] (現在) dot
行 1: 行 1:
- 
 ====== ether.jsを使用したDApps開発 ====== ====== ether.jsを使用したDApps開発 ======
  
 ether.js と React を使用して DApps を開発します。 ether.js と React を使用して DApps を開発します。
  
-===== Reactプロジェクトの生成 =====+したスースコードは [[https://github.com/shinoburc/SimpleReactEthereumClient|shinoburc/SimpleReactEthereumClient]] で管理しています。
  
 +下記手順を実行するか、上記リポジトリを利用してください。
 +
 +===== 前提 =====
 +
 +[[blockchain:truffleを使ったスマートコントラクト開発|Truffleを使ったスマートコントラクト開発]] で作成した Counter スマートコントラクトを使用しますので、先に実施しておいてください。
 +
 +MetaMask を使用しますので、[[blockchain:metamaskの使用|MetaMaskの使用]] を実施しておいてください。
 +
 +===== Reactプロジェクトの生成 =====
  
-<coce PowerShell>+<code PowerShell>
 > npx create-react-app react-etherjs > npx create-react-app react-etherjs
 Need to install the following packages: Need to install the following packages:
行 75: 行 83:
 > cd react-etherjs > cd react-etherjs
 </code> </code>
 +
 +===== ether.js のインストール =====
 +
 +ether.js の npm パッケージ名は ethers なので、それをインストールします。
 +
 +<code PowerShell>
 +react-etherjs> npm install --save ethers
 +</code>
 +
 +===== フロントエンドの実装 =====
 +
 +<code PowerShell>
 +react-etherjs> code .\src\App.js
 +</code>
 +
 +<code JavaScript>
 +import './App.css';
 +
 +import React, {  useState } from "react";
 +import { ethers } from "ethers";
 +
 +function App() {
 +  const [provider, setProvider] = useState(null);
 +  const [counter, setCounter] = useState(null);
 +  const [account, setAccount] = useState(null);
 +  const [count, setCount] = useState(null);
 +  const [transactionHash, setTransactionHash] = useState(null);
 +  const [transactionInfo, setTransactionInfo] = useState(null);
 +
 +  // counterAddress と counterAbi は環境によって書き換える必要があります。
 +  // Counater.json を読み込んで利用するとよりスマート。
 +  const counterAddress = "0x5E5A16AaFb816F04E09a05d1C03d98D7b1ee56C2";
 +  const counterAbi = [
 +        {
 +        "constant": true,
 +        "inputs": [],
 +        "name": "count",
 +        "outputs": [
 +            {
 +            "internalType": "uint256",
 +            "name": "",
 +            "type": "uint256"
 +            }
 +        ],
 +        "payable": false,
 +        "stateMutability": "view",
 +        "type": "function"
 +        },
 +        {
 +        "constant": true,
 +        "inputs": [],
 +        "name": "get",
 +        "outputs": [
 +            {
 +            "internalType": "uint256",
 +            "name": "",
 +            "type": "uint256"
 +            }
 +        ],
 +        "payable": false,
 +        "stateMutability": "view",
 +        "type": "function"
 +        },
 +        {
 +        "constant": false,
 +        "inputs": [],
 +        "name": "inc",
 +        "outputs": [],
 +        "payable": false,
 +        "stateMutability": "nonpayable",
 +        "type": "function"
 +        },
 +        {
 +        "constant": false,
 +        "inputs": [],
 +        "name": "dec",
 +        "outputs": [],
 +        "payable": false,
 +        "stateMutability": "nonpayable",
 +        "type": "function"
 +        }
 +    ];
 +
 +    //メタマスクの接続
 +    const connectMetaMask= () => {
 +        if (window.ethereum && window.ethereum.isMetaMask) {
 +            window.ethereum
 +                .request({ method: "eth_requestAccounts" })
 +                .then((accounts) => {
 +                    setAccount(accounts[0]);
 +                    let provider = new ethers.providers.Web3Provider(window.ethereum);
 +                    setProvider(provider);
 +                    let signer = provider.getSigner(0);
 +                    setCounter(new ethers.Contract(counterAddress, counterAbi, signer));
 +                })
 +                .catch((error) => {
 +                    console.log("MetaMask error" + error)
 +                });
 +        } else {
 +            console.log("Need to install MetaMask");
 +        }
 +    };
 +
 +  // Counter.get でカウントの値を取得する関数
 +  const  getCount =  async () => {
 +    let count = await counter.get();
 +    setCount(count.toNumber());
 +  };
 +
 +  // Counter.inc を呼び出す関数
 +  const  incCount =  async () => {
 +    let transaction = await counter.inc();
 +    // トランザクションが処理されるのを待つ
 +    await transaction.wait();
 +    setTransactionHash(transaction.hash);
 +    getCount();
 +  };
 +
 +  // Counterdec を呼び出す関数
 +  const  decCount =  async () => {
 +    let transaction = await counter.dec();
 +    // トランザクションが処理されるのを待つ
 +    await transaction.wait();
 +    setTransactionHash(transaction.hash);
 +    getCount();
 +  };
 +
 +  // transactionHash からトランザクション情報を取得する関数
 +  const getTransactionInfo =  async () => {
 +    let transactionInfo = await provider.getTransaction(transactionHash);
 +    setTransactionInfo(JSON.stringify(transactionInfo, null, 2));
 +  };
 +
 +  return (
 +    <div className="App">
 +      <header className="App-header">
 +      <div>
 +        Account: { account }
 +        <div>
 +            Count: { count }
 +        </div>
 +        <div>
 +            TransactionHash: { transactionHash }
 +        </div>
 +        <input type="button" value="connect" onClick={ connectMetaMask }/>
 +        <input type="button" value="get" onClick={ getCount }/>
 +        <input type="button" value="inc" onClick={ incCount }/>
 +        <input type="button" value="dec" onClick={ decCount }/>
 +        <input type="button" value="getTransactionInfo" onClick={ getTransactionInfo } />
 +      </div>
 +      <div>
 +        <pre>
 +          { transactionInfo }
 +        </pre>
 +      </div>
 +      </header>
 +    </div>
 +  );
 +}
 +
 +export default App;
 +</code>
 +
 +===== 実行 =====
 +
 +<code PowerShell>
 +react-etherjs> npm start
 +</code>
 +
 +「connect」をクリックすると MetaMask が立ち上がりますので、使用するアカウントを選択します。
 +
 +アカウントが選択できたら他のボタンをクリックすることで Counter スマートコントラクトの各メソッドが実行できます。
 +
 +{{:blockchain:react-etherjs.png?600|}}
blockchain/ether.jsを使用したdapps開発.1652009518.txt.gz · 最終更新: 2022/05/08 11:31 by dot