ユーザ用ツール

サイト用ツール


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

差分

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

この比較画面へのリンク

両方とも前のリビジョン前のリビジョン
次のリビジョン
前のリビジョン
blockchain:ether.jsを使用したdapps開発 [2022/05/08 21:02] 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 を開発します。
 +
 +完成したスースコードは [[https://github.com/shinoburc/SimpleReactEthereumClient|shinoburc/SimpleReactEthereumClient]] で管理しています。
 +
 +下記手順を実行するか、上記リポジトリを利用してください。
 +
 +===== 前提 =====
 +
 +[[blockchain:truffleを使ったスマートコントラクト開発|Truffleを使ったスマートコントラクト開発]] で作成した Counter スマートコントラクトを使用しますので、先に実施しておいてください。
 +
 +MetaMask を使用しますので、[[blockchain:metamaskの使用|MetaMaskの使用]] を実施しておいてください。
  
 ===== Reactプロジェクトの生成 ===== ===== Reactプロジェクトの生成 =====
行 81: 行 90:
 <code PowerShell> <code PowerShell>
 react-etherjs> npm install --save ethers react-etherjs> npm install --save ethers
-</code> 
- 
-===== Counter.json のコピー ===== 
- 
-[[blockchain:truffleを使ったスマートコントラクト開発|Truffleを使ったスマートコントラクト開発]] で Counter スマートコントラクトを build すると Counter スマートコントラクトの情報(ABIやaddressなど)が truffle_project\build\contracts\Counter.json に保存されています。今回はその Counter.json を react-etherjs\src\contracts\Counter.json にコピーして使用します。 
- 
-:!: 本来は truffle-config.js の設定を変更して、Counter.json を react-etherjs\src\contracts に保存するようにするのが一般的です。 
- 
-<code PowerShell> 
-react-etherjs> mkdir .\src\contracts 
- 
- 
-    ディレクトリ: C:\Users\miyazato\work\ethereum\react-etherjs\src 
- 
- 
-Mode                 LastWriteTime         Length Name 
-----                 -------------         ------ ---- 
-d-----        2022/05/08     20:50                contracts 
- 
- 
-react-etherjs> cp ..\contracts\Counter.sol .\src\contracts\. 
 </code> </code>
  
行 111: 行 99:
  
 <code JavaScript> <code JavaScript>
-import logo from './logo.svg'; 
 import './App.css'; import './App.css';
  
-import React, { useEffect, useState } from "react";+import React, {  useState } from "react";
 import { ethers } from "ethers"; import { ethers } from "ethers";
-import Counter from "./contracts/Counter.json"; 
  
 function App() { function App() {
-  const [count, setCount] = useState(); +  const [provider, setProvider] = useState(null); 
-  const [transactionHash, setTransactionHash] = useState(); +  const [counter, setCounter] = useState(null); 
-  const [transactionInfo, setTransactionInfo] = useState();+  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 (   return (
行 127: 行 220:
       <header className="App-header">       <header className="App-header">
       <div>       <div>
 +        Account: { account }
         <div>         <div>
             Count: { count }             Count: { count }
         </div>         </div>
         <div>         <div>
-            Transaction: { transactionHash }+            TransactionHash: { transactionHash }
         </div>         </div>
-        <input type="button" value="get" onClick="get();"/> +        <input type="button" value="connect" onClick={ connectMetaMask }/> 
-        <input type="button" value="inc" onClick="inc();"/> +        <input type="button" value="get" onClick={ getCount }/> 
-        <input type="button" value="dec" onClick="dec();"/> +        <input type="button" value="inc" onClick={ incCount }/> 
-        <input type="button" value="getTransactionInfo" onClick="getTransactionInfo()"/>+        <input type="button" value="dec" onClick={ decCount }/> 
 +        <input type="button" value="getTransactionInfo" onClick=getTransactionInfo />
       </div>       </div>
       <div>       <div>
-        { transactionInfo }+        <pre> 
 +          { transactionInfo } 
 +        </pre>
       </div>       </div>
       </header>       </header>
行 148: 行 245:
 export default App; export default App;
 </code> </code>
 +
 +===== 実行 =====
 +
 +<code PowerShell>
 +react-etherjs> npm start
 +</code>
 +
 +「connect」をクリックすると MetaMask が立ち上がりますので、使用するアカウントを選択します。
 +
 +アカウントが選択できたら他のボタンをクリックすることで Counter スマートコントラクトの各メソッドが実行できます。
 +
 +{{:blockchain:react-etherjs.png?600|}}
blockchain/ether.jsを使用したdapps開発.1652043736.txt.gz · 最終更新: 2022/05/08 21:02 by dot