ユーザ用ツール

サイト用ツール


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

差分

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

この比較画面へのリンク

両方とも前のリビジョン前のリビジョン
次のリビジョン
前のリビジョン
blockchain:ether.jsを使用したdapps開発 [2022/05/09 07:40] 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 [account, setAccount] = useState(); +  const [provider, setProvider] = useState(null); 
-  const [count, setCount] = useState(); +  const [counter, setCounter] = useState(null); 
-  const [transactionHash, setTransactionHash] = useState(); +  const [account, setAccount] = useState(null); 
-  const [transactionInfo, setTransactionInfo] = useState(); +  const [count, setCount] = useState(null); 
-  //const provider = new ethers.providers.Web3Provider(window.ethereum);+  const [transactionHash, setTransactionHash] = useState(null); 
 +  const [transactionInfo, setTransactionInfo] = useState(null);
  
-  //const provider = new ethers.providers.JsonRpcProvider("http://localhost:7545"); +  // counterAddress と counterAbi は環境によって書き換える必要があります。 
-  const counterAddress = "0x791C2E0e40B2b96f3aE2F5D3F3661478f73fB49D";+  // Counater.json を読み込んで利用するとよりスマート。 
 +  const counterAddress = "0x5E5A16AaFb816F04E09a05d1C03d98D7b1ee56C2";
   const counterAbi = [   const counterAbi = [
         {         {
行 177: 行 165:
         }         }
     ];     ];
-    //const Counter = new ethers.Contract(counterAddress, counterAbi, provider); 
  
-        //メタマスクの接続+    //メタマスクの接続
     const connectMetaMask= () => {     const connectMetaMask= () => {
         if (window.ethereum && window.ethereum.isMetaMask) {         if (window.ethereum && window.ethereum.isMetaMask) {
             window.ethereum             window.ethereum
                 .request({ method: "eth_requestAccounts" })                 .request({ method: "eth_requestAccounts" })
-                .then((result) => { +                .then((accounts) => { 
-                    setAccount(result[0]);+                    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) => {                 .catch((error) => {
-                    console.log("MetaMask error")+                    console.log("MetaMask error" + error)
                 });                 });
         } else {         } else {
行 195: 行 186:
     };     };
  
-  const  getCoinbase =  async () => { +  // Counter.get でカウントの値取得る関数
-    //const accounts = await provider.listAccounts(); +
-    // 先頭のアカウントを coinbase とみな +
-    //let coinbase = accounts[0]; +
-    //return coinbase; +
-  }; +
   const  getCount =  async () => {   const  getCount =  async () => {
-    //const a = await Counter.get(); +    let count = await counter.get(); 
-    //console.log("getCount");+    setCount(count.toNumber());
   };   };
  
-  const  incCount =  () => {+  // Counter.inc を呼び出す関数 
 +  const  incCount =  async () => { 
 +    let transaction = await counter.inc(); 
 +    // トランザクションが処理されるのを待つ 
 +    await transaction.wait(); 
 +    setTransactionHash(transaction.hash); 
 +    getCount();
   };   };
  
-  const  decCount =  () => {+  // Counterdec を呼び出す関数 
 +  const  decCount =  async () => { 
 +    let transaction = await counter.dec(); 
 +    // トランザクションが処理されるのを待つ 
 +    await transaction.wait(); 
 +    setTransactionHash(transaction.hash); 
 +    getCount();
   };   };
  
-  const getTransactionInfo =  () => {+  // transactionHash からトランザクション情報を取得する関数 
 +  const getTransactionInfo =  async () => { 
 +    let transactionInfo = await provider.getTransaction(transactionHash); 
 +    setTransactionInfo(JSON.stringify(transactionInfo, null, 2));
   };   };
  
行 225: 行 225:
         </div>         </div>
         <div>         <div>
-            Transaction: { transactionHash }+            TransactionHash: { transactionHash }
         </div>         </div>
         <input type="button" value="connect" onClick={ connectMetaMask }/>         <input type="button" value="connect" onClick={ connectMetaMask }/>
行 234: 行 234:
       </div>       </div>
       <div>       <div>
-        { transactionInfo }+        <pre> 
 +          { transactionInfo } 
 +        </pre>
       </div>       </div>
       </header>       </header>
行 243: 行 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開発.1652082054.txt.gz · 最終更新: 2022/05/09 07:40 by dot