您好,登录后才能下订单哦!
以太坊区块链如何使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。