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

How to build a DAPP application of Truffle framework from scratch

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail how to build a Truffle framework DAPP application from scratch. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Requirement description

We want to implement a user name and age input and presentation page that can update the user name and age on the smart contract. Re-enter the user name and age, and click the button to update the information of these two variables of the smart contract.

Operation steps

3.1 create a directory and download the framework

First, create a directory and download the code framework for the pet store.

Duncanwang@ubuntu:~/work$ mkdir name-ageduncanwang@ubuntu:~/work$ cd name-ageduncanwang@ubuntu:~/work/name-age$ truffle unbox pet-shopDownloading...Unpacking...Setting up...Unbox successful. Sweet!Commands: Compile: truffle compile Migrate: truffle migrate Test contracts: truffle test Run dev server: npm run devduncanwang@ubuntu:~/work/name-age$

3.2 create a smart contract code

Create a new InfoContract.sol smart contract file and update it to the. / contracts directory.

Pragma solidity ^ 0.4.24 position contract InfoContract {string name; uint age; event Instructor (string name, uint age); function setInfo (string _ name, uint _ age) public {name = _ name; age = _ age; emit Instructor (name, age);} function getInfo () public view returns (string, uint) {return (name, age);}}

3.3 increase contract-related deployment and test code

1) increase contract deployment testing

The file 2_info_contract.js goes to the. / migrations directory, and the code is as follows, indicating the contract InfoContract contract deployment.

Var MyContract = artifacts.require (". / InfoContract.sol"); module.exports = function (deployer) {/ / deployment steps deployer.deploy (MyContract);}

2) add test files

Pragma solidity ^ 0.4.24: import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import ".. / contracts/InfoContract.sol"; contract TestInfoContract {InfoContract info = InfoContract (DeployedAddresses.InfoContract ()); string name; uint age; function testInfo () {info.setInfo ("ABC", 10); (name, age) = info.getInfo (); Assert.equal (name, "ABC", "setting name error") Assert.equal (age, 10, "error setting age");}}

3) modify the configuration file

Because the default ganache-cli port is 8545, you need to change the port number of the truffle.js from 7545 to 8545.

Module.exports = {/ / See / / for more about customizing your Truffle configuration! Networks: {development: {host: "127.0.0.1", port: 8545, network_id: "*" / / Match any network id}

Otherwise, the client will not be found during the test.

Duncanwang@ubuntu:~/work/name-age$ truffle testCould not connect to your Ethereum client. Please check that your Ethereum client:-is running-is accepting RPC connections (i.e., "--rpc" option is used in geth)-is accessible over the network-is properly configured in your Truffle configuration file (truffle.js)

3.4 acceptance Test Intelligent contract

1) refer to the pet store article code and launch a ganache-cli wallet in a window.

Duncanwang@ubuntu:~/work/name-age$ cd.. duncanwang@ubuntu:~/work$ ganache-cli > > trace.log

2) compile the smart contract

Then start another window command line and enter the command.

Duncanwang@ubuntu:~/work/name-age$ truffle compileCompiling. / contracts/InfoContract.sol...Compiling. / contracts/Migrations.sol...Writing artifacts to. / build/contracts

3) Intelligent contract acceptance order.

Tips for successful test:

Duncanwang@ubuntu:~/work/name-age$ truffle testUsing network 'development'.Compiling. / contracts/InfoContract.sol...Compiling. / test/TestInfoContract.sol...Compiling truffle/Assert.sol...Compiling truffle/DeployedAddresses.sol...Compilation warnings encountered:/home/duncanwang/work/name-age/test/TestInfoContract.sol:12:4: Warning: No visibility specified. Defaulting to "public". Function testInfo () {^ (Relevant source part starts here and spans across multiple lines). TestInfoContract ✓ testInfo (838ms) 1 passing (5s)

3.5 complete the front page

Complete the modification, update and upload of the following 2 files.

1) index.html

Delete the index.html code of the pet store and replace it with the framework code required for this article.

First Truffle DApp Demo First Truffle DApp Demo

Name: age: update

2) app.js

Then modify the app.js code to complete the execution and invocation of the intelligent contract.

App = {web3Provider: null, contracts: {}, init: function () {return App.initWeb3 ();}, / * load web3*/ initWeb3: function () {if (typeof web3! = = 'undefined') {App.web3Provider = web3.currentProvider web3 = new Web3 (App.web3Provider) } else {App.web3Provider = new Web3.providers.HttpProvider ("http://localhost:9545") web3 = new Web3 (App.web3Provider);} return App.initContract ();}, / * initialize the contract and obtain the contract without using at () Display contract name and age information * / initContract: function () {$.getJSON ('InfoContract.json', function (data) {App.contracts.InfoContract = TruffleContract (data); App.contracts.InfoContract.setProvider (App.web3Provider); App.getInfo (); App.watchChanged ();}); App.bindEvents () }, getInfo: function () {App.contracts.InfoContract.deployed (). Then (function (instance) {return instance.getInfo.call ();}). Then (function (result) {$("# loader"). Hide (); $("# info") .html (result [0] +'('+ result [1] + 'years old)'); console.log (result) ) .catch (function (err) {console.error (err);});}, / * Click the button to update the name and age, you need to update to the smart contract * / bindEvents: function () {$("# button") .click (function () {$("# loader"). Show () App.contracts.InfoContract.deployed () .then (function (instance) {return instance.setInfo ($("# name"). Val (), $("# age") .val (), {gas: 500000});}) .then (function (result) {return App.getInfo ();}) .catch (function (err) {console.error (err);});}) }, watchChanged: function () {App.contracts.InfoContract.deployed (). Then (function (instance) {var infoEvent = instance.Instructor (); return infoEvent.watch (function (err, result) {$("# loader"). Hide (); $("# info") .html (result.args.name +'('+ result.args.age + 'years old)');});}) } $(function () {$(window) .load (function () {App.init ();});})

3.6 Test acceptance front end and contract interaction code

1) deployment contract

The contract was successfully deployed.

Duncanwang@ubuntu:~/work/name-age$ truffle migrateUsing network 'development'.Running migration: 1_initial_migration.js Deploying Migrations... ... 0x5b3cd41a7fa7c58361172ac797412469a10edfbe721d8d81988f19282c9cb6e4 Migrations: 0x92b6ecd23aa98fad36926c12ec701f9aaa0933f4Saving successful migration to network... ... 0x826fcd5b72b48435bf4f9941305727e52b0b7290631ba7b39f642027b1ee6947Saving artifacts...Running migration: 2_info_contract.js Deploying InfoContract... ... 0x9943dd7b90207bd9fd1e85524d1d0227f18a92269d73f5a2141cb71c22dda1e9 InfoContract: 0x191391c710e1b632e40b4f2267dbc0f3bdb2bed4Saving successful migration to network... ... 0x7e11f6e32585524e338e73439e4026c7c766625e5d23d56a4c90f8a11e5001edSaving artifacts...

2) install and start lite-server

1] install lite-server

[definition] lite-server is lightweight, only suitable for node servers for development, and only supports web app. It can open a browser for you, when your html or JavaScript file changes, it will recognize and automatically help you refresh the browser, it can also use sockets to automatically inject changed CSS, when the route is not found, it will automatically back the page.

Reference: how to build the ethernet development environment (https://www.jianshu.com/p/683ea7d62a39) under the WINDOWS environment, and complete the installation of MetaMask and liteServer.

Duncanwang@ubuntu:~/work/name-age$ npm install lite-server-save-dev

The output of a successful installation is as follows:

Npm WARN pet-shop@1.0.0 No descriptionnpm WARN pet-shop@1.0.0 No repository field.npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os": "darwin", "arch": "any"} (current: {"os": "linux" "arch": "ia32"}) + lite-server@2.4.0added 342 packages from 273 contributors in 56.82s**2] completes the launch of lite-server in a new window. * * duncanwang@ubuntu:~/work/name-age$ npm run dev > pet-shop@1.0.0 dev / home/duncanwang/work/name-age > lite-server** browser-sync config * * {injectChanges: false, files: ['. / * * / *. {html,htm,css,js}'], watchOptions: {ignored: 'node_modules'}, server: {baseDir: [. / src','. / build/contracts'] Middleware: [[Function] [Function]]} [Browsersync] Access URLs:-- Local: http://localhost:3000 External: http://10.225.18.149:3000-- -UI: http://localhost:3001 UI External: http://localhost:3001-- [Browsersync] Serving files from:. / src [Browsersync] Serving files from:. / build/contracts [Browsersync] Watching files...

3) Open the home page

Enter the home address of the lite-server prompt: http://10.225.18.149:3000

You can see the page output information.

4) update name and age

Enter name and age in the input box: Wang Denghui, 18, click the update button, the transaction prompt of MEATMASK will pop up to confirm the transaction.

Name and age information will be updated after confirming the transaction.

On how to build a Truffle framework from scratch to share the DAPP application here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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