您好,登錄后才能下訂單哦!
以太坊區塊鏈如何使用web3開發自己第一個DApp,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
在學習了最基礎的一些以太坊知識以及開發框架搭建完成之后,可以嘗試開發自己的第一個DApp,此處使用Truffle開發框架,Remix編譯環境,Genache測試客戶端,具體操作如下。
此處參照MetaCoin創建自己的模擬轉賬Dapp 名稱為RuoliCoin
創建RuoliCoin目錄,在此目錄下打開命令行 執行 Truffle 初始化命令,如下:
truffle unbox webpack
即可創建基礎Truffle框架。
在RuoliCoin/contracts 目錄下刪除原有的 ConvertLib.sol、MetaCoin.sol兩個文件,新建RuoliCoin.sol文件,使用Web版本的Remix打開此文件,進行智能合約的編寫操作,最后編寫好的智能合約內容如下:
pragma solidity ^0.4.23; contract RuoliCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); constructor() public { balances[msg.sender] = 10000; } function sendCoin(address receiver, uint amount) public returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; emit Transfer(msg.sender, receiver, amount); return true; } function getBalance(address addr) public view returns(uint) { return balances[addr]; } }
修改truffle.js 文件,指定本地 RCP Server 地址(啟動Ganache后主界面有顯示),內容如下:
module.exports = { networks: { development: { host: 'localhost', port: '7545', network_id: '*' // Match any network id } } };
migrations 目錄下 1_initial_migration.js 、2_deploy_contracts.js 兩個文件 非常重要切勿刪除,在此目錄下將 2_deploy_contracts.js 進行修改 內容如下:
var RuoliCoin = artifacts.require("./RuoliCoin.sol"); module.exports = function(deployer) { deployer.deploy(RuoliCoin); };
在RuoliCoin目錄下使用命令行編譯并部署智能合約文件,如下:
PS C:\Workspace\Ruoli-Code\Truffle\RuoliCoin> truffle compile PS C:\Workspace\Ruoli-Code\Truffle\RuoliCoin> truffle deploy Using network 'development'. Running migration: 1_initial_migration.js Deploying Migrations... ... 0x73e55a0f780c6780039abc3feb8b5e1243744135096e441668e8ab55579e51db Migrations: 0xb81237dd01159a36a5ac3c760d227bbafe3341ea Saving successful migration to network... ... 0xc5be542ec02f5513ec21e441c54bd31f0c86221da26ed518a2da25c190faa24b Saving artifacts... Running migration: 2_deploy_contracts.js Deploying RuoliCoin... ... 0xd4c85531d5d83c61f79485c43e6e4146d51b909c8b73bf5d88b60aa990cf1d08 RuoliCoin: 0x6ba286f3115994baf1fed1159e81f77c9e1cd4fa Saving successful migration to network... ... 0xc8d5533c11181c87e6b60d4863cdebb450a2404134aea03a573ce6886905a00b Saving artifacts... PS C:\Workspace\Ruoli-Code\Truffle\RuoliCoin>
此時查看 Ganache界面中 第一個賬戶的 ETH 余額已減少,說明部署成功。
在 app 目錄下刪除所有文件,新建index.html、javascripts/app.js 兩個文件,文件內容如下:
index.html 如下:
<!DOCTYPE html> <html> <head> <title>RuoliCoin - Truffle Demo </title> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" > <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="./app.js"></script> </head> <body> <div class="container" > <div class="form-group"> <input type="text" class="form-control" id="transfer-addr" placeholder="轉入賬戶"> </div> <div class="form-group"> <input type="text" class="form-control" id="transfer-money" placeholder="注入金額"> </div> <div class="alert" role="alert" id="message-box"></div> <button type="submit" id="transfer-confirm-btn" class="btn btn-success">轉賬</button> <button type="button" id="transfer-clear-btn" class="btn btn-default">重置</button> <hr/> <div class="form-group"> <input type="text" class="form-control" id="balance-addr" placeholder="查詢余額賬戶"> </div> <button type="submit" id="balance-select" class="btn btn-success">余額查詢</button> </div> </body> <script> $(document).ready(function(){ $('#transfer-confirm-btn').on('click', function(){ var transferAddr = $('#transfer-addr').val(); var transferMoney = $('#transfer-money').val(); if(transferAddr==''){ showTips('alert-danger','轉入賬戶不能為空'); }else { //調用App的say()方法 window.App.transfer(transferAddr,transferMoney, function (err, result) { if(err){ showTips('alert-danger',err); }else { showTips('alert-danger',result); } }); } }); $('#balance-select').on('click', function(){ var balanceAddr = $('#balance-addr').val(); if(balanceAddr==''){ showTips('alert-danger','查詢余額賬不能為空'); }else { //調用App的say()方法 window.App.getBalance(balanceAddr, function (err, result) { if(err){ showTips('alert-danger',err); }else { showTips('alert-danger','賬戶余額:'+result); } }); } }); $('#cancel').on('click', function(){ $('#username').val(''); $('#message-box').hide(); $('#message-box').html(''); }); }); function showTips(classType,tipsText){ $('#message-box').addClass(classType).html(tipsText+''); $('#message-box').fadeIn(800); } </script> </html>
javascripts/app.js內容如下:
//導入CSS //import "../stylesheets/app.css"; //導入web3和truffle-contract庫 import { default as Web3} from 'web3'; import { default as contract } from 'truffle-contract' //導入Hello合約的ABI文件 import RuoliCoin_artifacts from '../../build/contracts/RuoliCoin.json' //獲取Hello合約對象 var RuoliCoinContract = contract(RuoliCoin_artifacts); var ruoliCoinInstance = null; var accounts; var account; window.App = { init: function() { //設置web3連接 RuoliCoinContract.setProvider(web3.currentProvider); // Get the initial account balance so it can be displayed. web3.eth.getAccounts(function(err, accs) { if (err != null) { alert("There was an error fetching your accounts."); return; } if (accs.length == 0) { alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly."); return; } accounts = accs; account = accounts[0]; }); //instance為Hello合約部署實例 RuoliCoinContract.deployed().then(function(instance){ ruoliCoinInstance=instance; var event=ruoliCoinInstance.Transfer(); event.watch(function(error,result){ alert(error); console.log(result); }); }).catch(function(e){ console.log(e, null); }); }, //封裝合約中的say()方法調用過程,供javascript調用 transfer: function(transferAddr,amount, callback){ //調用Hello合約中的say()方法,并傳入參數name ruoliCoinInstance.sendCoin(transferAddr,amount,{from: account}).then(function(result){ //將返回結果傳入回調函數 callback(null, result); }); }, getBalance:function(balanceAddr,callback){ //調用Hello合約中的say()方法,并傳入參數name ruoliCoinInstance.getBalance.call(balanceAddr,{from: account}).then(function(result){ //將返回結果傳入回調函數 callback(null, result); }); } }; window.addEventListener('load', function() { //設置web3連接 http://127.0.0.1:7545 為Ganache提供的節點鏈接 window.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545")); App.init(); });
運行界面如下:
在RuoliCoin 根目錄 執行啟動命令 npm run dev ,如下:
PS C:\Workspace\Ruoli-Code\Truffle\Metacoin> npm run dev > truffle-init-webpack@0.0.2 dev C:\Workspace\Ruoli-Code\Truffle\Metacoin > webpack-dev-server Project is running at http://localhost:8081/ webpack output is served from / Hash: 8b5b7df27e0385bf011d Version: webpack 2.7.0 Time: 3239ms Asset Size Chunks Chunk Names app.js 1.68 MB 0 [emitted] [big] main index.html 925 bytes [emitted] chunk {0} app.js (main) 1.66 MB [entry] [rendered] [71] ./app/javascripts/app.js 3.64 kB {0} [built] [72] (webpack)-dev-server/client?http://localhost:8081 7.93 kB {0} [built] [73] ./build/contracts/MetaCoin.json 47.8 kB {0} [built] [111] ./~/loglevel/lib/loglevel.js 7.86 kB {0} [built] [117] ./~/querystring-es3/index.js 127 bytes {0} [built] [119] ./~/strip-ansi/index.js 161 bytes {0} [built] [122] ./app/stylesheets/app.css 905 bytes {0} [built] [163] ./~/truffle-contract/index.js 2.64 kB {0} [built] [197] ./~/url/url.js 23.3 kB {0} [built] [199] ./~/web3/index.js 193 bytes {0} [built] [233] (webpack)-dev-server/client/overlay.js 3.67 kB {0} [built] [234] (webpack)-dev-server/client/socket.js 1.08 kB {0} [built] [235] (webpack)/hot nonrecursive ^\.\/log$ 160 bytes {0} [built] [236] (webpack)/hot/emitter.js 77 bytes {0} [built] [237] multi (webpack)-dev-server/client?http://localhost:8081 ./app/javascripts/app.js 40 bytes {0} [built] + 223 hidden modules webpack: Compiled successfully.
訪問 上面提示的鏈接地址:http://localhost:8081/
即可訪問到頁面,輸入轉入地址和金額即可進行代幣轉賬操作,輸入查詢余額地址即可進行查詢余額操作。
關于以太坊區塊鏈如何使用web3開發自己第一個DApp問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。