Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of Dapp developed by SimpleChain

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article is to share with you about SimpleChain development Dapp example analysis, the editor thinks it is very practical, so share it with you to learn, hope you can get something after reading this article, say no more, follow the editor to have a look.

The SimpleChian technology community is preparing to hold a development challenge recently, and many community buddies are eager to develop Dapp applications based on SimpleChain. In view of this situation, in this issue we will talk about how to develop Dapp based on SimpleChain. The following is the detailed process of developing Dapp development, which is sorted out as follows:

Environmental preparation

In addition to Mac computers, you also need to install the relevant environment for SimpleChain development. The environment is as follows:

Nodejs truffle solidity testrpc

In addition, webpack will be used in the tutorials, and there are many installation tutorials online. If you are not familiar with this part, please refer to it and study it yourself.

Write a smart contract

We have installed truffle before, we just need to create a new conference directory under the computer's project directory, enter the directory to execute truffle init, and we can use truffle, the Dapp front-end framework, to initialize our own project. After execution, create the following subdirectories and files:

The directory where contracts/: smart contracts are stored has helped you create Migrations.sol contracts by default. Migrations/: stores the deployment script test/: stores the configuration file of the test script truffle.js: truffle

Modify the truffle.js file to read as follows:

Module.exports = {networks: {development: {host: "localhost", port: 8545, network_id: "*" / / match any network id}

The above is to set the location where we will deploy the smart contract later, otherwise a network error will be reported.

Open a terminal on the computer and type testrpc to run the test node. Testrpc is a complete in-memory blockchain test environment. After starting testrpc, 10 accounts will be created by default. Available Accounts is the list of accounts and Private Keys is the corresponding account key. As shown below:

Enter the contracts directory, which is where the contract code is stored. We can use the programming tool (Viscode) to write test contract code. What I'm posting here is a smart contract for voting.

Pragma solidity ^ 0.4.2 X contract Migrations {address public owner; uint public last_completed_migration; modifier restricted () {if (msg.sender = = owner) _;} function Migrations () {owner = msg.sender;} function setCompleted (uint completed) restricted {last_completed_migration = completed;} function upgrade (address new_address) restricted {Migrations upgraded = Migrations (new_address); upgraded.setCompleted (last_completed_migration);}}

The content of the contract is very simple, it is a strategy for voting on the chain. Users can vote on the chain to ensure the authenticity and objectivity of the vote.

Compile and deploy smart contract

Modify the 1_initial_migration.js file under migrations to read as follows:

/ / var Migrations = artifacts.require (". / Migrations.sol"); var Conference = artifacts.require (". / Voting.sol"); module.exports = function (deployer) {/ / deployer.deploy (Migrations); deployer.deploy (Conference);}

Compile:

$sudo truffle compile--compile-all

Pay attention to whether there is an error report:

Truffle compiles only files that have been modified since the last compilation by default to reduce unnecessary compilation. If you want to compile all files, you can use the-- compile-all option.

Then there will be an extra build directory without any changes to the files in that directory.

Deployment:

$sudo truffle migrate-reset

This command executes all js files in the migrations directory. If you execute the truffle migrate command before and execute it again, only the new js file will be deployed, and if there is no new js file, it will not work. If you use the-- reset parameter, the deployment of all scripts will be re-executed.

Under test, add a conference.js test file to the test directory

Var Conference = artifacts.require (". / Voting.sol"); contract ('Conference', function (accounts) {console.log ("start testing"); / / console.log (accounts); var owner_account = accounts [0]; var sender_account = accounts [1] It ("Initial conference settings should match", function (done) {Conference.new ({from: owner_account}). Then (function (conference) {conference.quota.call (). Then (function (quota) {assert.equal (quota, 100, "Quota doesn't match!") }) .then (function () {return conference.numRegistrants.call ();}) .then (function (num) {assert.equal (num, 0, "Registrants doesn't match!"); return conference.organizer.call () Then (function (organizer) {assert.equal (organizer, owner_account, "Owner doesn't match!"); done ();}) .catch (done);}) .catch (done);})

This is a test case, run truffle test to see the test results.

$truffle testUsing network 'development'.start testing Contract: Conference ✓ Initial conference settings should match (191ms) ✓ Should update quota (174ms) ✓ Should let you buy a ticket (717ms) ✓ Should issue a refund by owner only (714ms) 4 passing (2s) to write web applications

Execute npm init in the conference directory, and then enter all the way to generate a file called package.json. Edit the file, and add two commands to the scripts section. Finally, the following:

{"name": "conference", "version": "1.0.0", "description": "", "main": "truffle-config.js", "directories": {"test": "test"}, "scripts": {"test": "echo" Error: no test specified "& & exit 1", "start": "webpack", "server": "webpack-dev-server-- open"} "author": "," license ":" ISC "}

The package.json file defines the various modules required for the project, as well as the configuration information for the project (such as name, version, license, and so on). The npm command automatically downloads the required modules, that is, the running and development environment required to configure the project, based on this configuration file.

Then create a new app directory under the conference directory and create an index.html file, as follows:

SimpleChain Voting tool SimpleChain Voting tool Contract deployed at: Organizer: Quota: Change Registrants: 0

Then create a new javascripts directory and a styleheets directory under the app directory, and store js script files and css style files, respectively. What really interacts with the contract is the script file.

The script file is named app.js, and part of the code is as follows:

Import ".. / stylesheets/app.css"; import {default as Web3} from 'web3';import {default as contract} from' truffle-contract';import conference_artifacts from'.. /.. / build/contracts/Conference.json'var accounts, sim;var Conference = contract (conference_artifacts); window.addEventListener ('load', function () {/ / alert ("aaaaa") / / Checking if Web3 has been injected by the browser (Mist/MetaMask) if (typeof web3! = = 'undefined') {console.warn ("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask") / / Use Mist/MetaMask's provider window.web3 = new Web3 (web3.currentProvider);} else {console.warn ("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask"); / / fallback-use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail) window.web3 = new Web3 (new Web3.providers.HttpProvider ("http://localhost:8545"));} Conference.setProvider (web3.currentProvider); App.start ()) $("# changeQuota") .click (function () {var newquota = $("# confQuota") .val (); App.changeQuota (newquota);}); / / Wire up the UI elements})

Here is the main use of JS plus wweb3 API to call the contract function. So far, the web part is basically ready, and we just need to package and deploy it with webpack. Webpack packaging also requires a configuration file called webpack.config.js, which tells webpack the rules for packaging and involves the use of webpack, which you can find on your own.

Package deployment of web applications

Packaging deployment requires the installation of webpack and related components, which can be installed in both global and local ways. The so-called partial installation means that the components are installed in the conference/node_modules of the project. What I use here is partial installation. According to the actual situation of our project, the following components need to be installed

Npm install-- save-dev webpack@3.0.0npm install babel-loader-- save-devnpm install babel-core-- save-devnpm install html-loader-- save-devnpm install-- save-dev webpack-dev-server@2.11.0npm install html-webpack-plugin-- save-devnpm install truffle-contract-- save-devnpm install-- save-dev style-loader css-loader environment is ready to pack. $sudo npm run start > conference@1.0.0 start / home/pony/ethereum/conference > webpackHash: ec8b764f75c05b477d9dVersion: webpack 3.0.0Time: 2686ms Asset Size Chunks Chunk Names bundle.js 3.36 MB 0 [emitted] [big] main./index.html 740 bytes [emitted] [10] (webpack) / buildin/global.js 509 bytes {0} [built] [16] (webpack) / buildin/module.js 517 bytes {0} [built] [47]. / app/javascripts/app.js 3.85 kB {0} [built] [48]. / app/stylesheets/app.css 1.08 kB {0} [built] [49]. .1 kB {0} [built] + 170x.html "index.html": [0]. / nodewritten modules bytes bytes built

If you report correctly, if you enter the build directory, you can see two files, bundle.js and index.html, which are the final packaged web page files. Then deploy:

$sudo npm run server > conference@1.0.0 server / home/pony/ethereum/conference > webpack-dev-server-- openProject is running at http://localhost:8080/webpack output is served from / Content not from webpack is served from. / build404s will fallback to / index.htmlHash: ecae3662137376f80de0Version: webpack 3.0.0

This is equivalent to running a small nodejs server, and we can see the effect on the page by typing http://localhost:8080/ in the browser. Clipboard.png can see that the release address of the contract and the meeting organizer address (msg.sender) have been successfully displayed. Click the change button to change the value of quota.

The above is the SimpleChain development Dapp example analysis, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report