In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Taifang Block chain how to use web3 to develop its first DApp, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
After learning some of the most basic knowledge of Ethernet Square and the completion of the development framework, you can try to develop your first DApp, here using the Truffle development framework, Remix compilation environment, Genache test client, the specific operations are as follows.
Create your own simulated money transfer Dapp named RuoliCoin with reference to MetaCoin here
1. Create a working directory
Create the RuoliCoin directory, and open the command line to execute the Truffle initialization command in this directory, as follows:
Truffle unbox webpack
You can create a basic Truffle framework.
2. Create Solidity intelligent contract file
Delete the original ConvertLib.sol and MetaCoin.sol files under the RuoliCoin/contracts directory, create a new RuoliCoin.sol file, and use the Web version of Remix to open the file to write the intelligent contract. Finally, the content of the intelligent contract is as follows:
Pragma solidity ^ 0.4.23 position 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]; }}3、部署至测试环境 修改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 compilePS C:\ Workspace\ Ruoli-Code\ Truffle\ RuoliCoin > truffle deployUsing network 'development'.Running migration: 1_initial_migration.js Deploying Migrations... ... 0x73e55a0f780c6780039abc3feb8b5e1243744135096e441668e8ab55579e51db Migrations: 0xb81237dd01159a36a5ac3c760d227bbafe3341eaSaving successful migration to network... ... 0xc5be542ec02f5513ec21e441c54bd31f0c86221da26ed518a2da25c190faa24bSaving artifacts...Running migration: 2_deploy_contracts.js Deploying RuoliCoin... ... 0xd4c85531d5d83c61f79485c43e6e4146d51b909c8b73bf5d88b60aa990cf1d08 RuoliCoin: 0x6ba286f3115994baf1fed1159e81f77c9e1cd4faSaving successful migration to network... .. 0xc8d5533c11181c87e6b60d4863cdebb450a2404134aea03a573ce6886905a00bSaving artifacts...PS C:\ Workspace\ Ruoli-Code\ Truffle\ RuoliCoin >
At this point, you can see that the ETH balance of the first account in the Ganache interface has decreased, indicating that the deployment is successful.
4. Write a page file
Delete all files in the app directory, and create two new files, index.html and javascripts/app.js, with the following contents:
Index.html is as follows:
RuoliCoin-Truffle Demo transfer reset balance query $(document) .ready (function () {$('# transfer-confirm-btn'). On ('click', function () {var transferAddr = $(' # transfer-addr'). Val (); var transferMoney = $('# transfer-money'). Val () If (transferAddr=='') {showTips ('alert-danger',' transfer to account cannot be empty');} else {/ / call App's say () method 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',' query balance account cannot be empty');} else {/ / call App's say () method window.App.getBalance (balanceAddr, function (err, result) {if (err) {showTips ('alert-danger',err) } else {showTips ('alert-danger',' account balance:' + 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);}
The javascripts/app.js content is as follows:
/ / Import CSS//import ".. / stylesheets/app.css"; / / Import web3 and truffle-contract libraries import {default as Web3} from 'web3';import {default as contract} from' truffle-contract'// import ABI file import RuoliCoin_artifacts from'.. /.. / build/contracts/RuoliCoin.json'// of Hello contract to get Hello contract object var RuoliCoinContract = contract (RuoliCoin_artifacts); var ruoliCoinInstance = null;var accounts;var account Window.App = {init: function () {/ / set web3 connection 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 for Hello contract deployment instance 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);}) }, / / encapsulates the say () method call procedure in the contract for javascript to call transfer: function (transferAddr,amount, callback) {/ / call the say () method in the Hello contract and pass in the parameter name ruoliCoinInstance.sendCoin (transferAddr,amount, {from: account}) .then (function (result) {/ / pass the return result into the callback function callback (null, result);}) }, getBalance:function (balanceAddr,callback) {/ / call the say () method in the Hello contract, passing in the parameter name ruoliCoinInstance.getBalance.call (balanceAddr, {from: account}). Then (function (result) {/ / pass the returned result into the callback function callback (null, result);});} Window.addEventListener ('load', function () {/ / sets the node link provided by the web3 connection http://127.0.0.1:7545 for Ganache window.web3 = new Web3 ("http://127.0.0.1:7545")); App.init ();})
The running interface is as follows:
5. Running and testing
Execute the startup command npm run dev in the RuoliCoin root directory as follows:
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-serverProject is running at http://localhost:8081/webpack output is served from / Hash: 8b5b7df27e0385bf011dVersion: webpack 2.7.0Time: 3239ms Asset Size Chunks Chunk Names app.js 1.68 MB 0 [emitted] [big] mainindex.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] ]. / ~ / 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 moduleswebpack: Compiled successfully.
Visit the link address prompted above: http://localhost:8081/
You can access the page, enter the transfer address and amount to carry out token transfer operation, and enter the query balance address to query the balance operation.
This is the answer to the first DApp question about how to use web3 to develop your own block chain. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.