Step by step to teach you to develop and deploy your first de-centralized application (Dapp)-Pet Shop

Source: Internet
Author: User
Tags install node

Today we are going to write a complete de-centric (blockchain) application (Dapps), this article can be combined with the writing of smart contracts to see.

Write in front

Before reading this article, you should know something about Ethereum and smart contracts, and if you don't know it, it's recommended that you look at Ethereum first.
Besides, you'd better get some knowledge of HTML and JavaScript.

This article through the example teaches everybody to develop the central application, the application effect

From this article, you can learn to:

    • Building an intelligent contract development environment
    • Create a truffle project
    • Write a smart contract
    • Compiling and deploying smart contracts to blockchain
    • How to interact with WEB3 and smart contracts
    • Use of Metamask
Project background

Pete has a pet shop with 16 pets, and he wants to develop a hub-and-go app that lets people adopt pets.
In truffle box, the code for the Pet-shop site section has been provided, and we only need to write the contract and the interactive part.

Environment construction
    1. Install node
    2. Install Truffle:npm install -g truffle
    3. Installing ganache

The ganache (or ganache CLI) has replaced the TESTRPC.

Create a project
    1. Set up the project directory and enter
      > mkdir pet-shop-tutorial> cd pet-shop-tutorial
    2. Create a project using truffle unbox
      > truffle unbox pet-shopDownloading...Unpacking...Setting up...Unbox successful. Sweet!


Compile:truffle Compile
Migrate:truffle Migrate
Test contracts:truffle Test
Run Dev server:npm Run dev

这一步需要等待一会> 也可以使用truffle init 来创建一个全新的项目。## 项目目录结构`contracts/`  智能合约的文件夹,所有的智能合约文件都放置在这里,里面包含一个重要的合约Migrations.sol(稍后再讲)`migrations/` 用来处理部署(迁移)智能合约 ,迁移是一个额外特别的合约用来保存合约的变化。`test/` 智能合约测试用例文件夹`truffle.js/` 配置文件其他代码可以暂时不用管## 编写智能合约智能合约承担着分布式应用的后台逻辑和存储。智能合约使用solidity编写,可阅读[solidity系列文章](在contracts目录下,添加合约文件Adoption.sol```jspragma solidity ^0.4.17;contract Adoption {  address[16] public adopters;  // 保存领养者的地址    // 领养宠物  function adopt(uint petId) public returns (uint) {    require(petId >= 0 && petId <= 15);  // 确保id在数组长度内    adopters[petId] = msg.sender;        // 保存调用这地址     return petId;  }  // 返回领养者  function getAdopters() public view returns (address[16]) {    return adopters;  }}
Compiling and deploying smart contracts

The truffle integrates a developer console that can be used to generate a development chain for testing and deploying smart contracts.


Solidity is a compiled language and requires that the readable solidity code be compiled into an EVM bytecode to run.
Dapp the root directory pet-shop-tutorial,

> truffle compile


Compiling ./contracts/Adoption.sol...Writing artifacts to ./build/contracts

Once compiled, it can be deployed to the blockchain.
There is already a 1_initial_migration.js deployment script under the Migrations folder to deploy the Migrations.sol contract.
Migrations.sol is used to ensure that the same contract is not deployed.

Now let's create a deployment script of our own2_deploy_contracts.js

var Adoption = artifacts.require("Adoption");module.exports = function(deployer) {  deployer.deploy(Adoption);};

Before you perform the deployment, you need to ensure that a blockchain is running and you can use
Ganache to open a private chain for development testing, the default is to run a development chain on port 7545.
This is the case when ganache is started:

Next, execute the deployment command:

> truffle  migrate

After execution, there is a similar output,

Using network ‘develop‘.Running migration: 1_initial_migration.js  Deploying Migrations...  ... 0x3076b7dac65afc44ec51508bf6f2b6894f833f0f9560ecad2d6d41ed98a4679f  Migrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0Saving successful migration to network...  ... 0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956Saving artifacts...Running migration: 2_deploy_contracts.js  Deploying Adoption...  ... 0x2c6ab4471c225b5473f2079ee42ca1356007e51d5bb57eb80bfeb406acc35cd4  Adoption: 0x345ca3e014aaf5dca488057592ee47305d9b3e10Saving successful migration to network...  ... 0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0Saving artifacts...

In the open ganache you can see changes in the blockchain state, which now produces 4 blocks.

This means that the smart contract has been deployed.


Now let's test the smart contract, the test case can be written in JavaScript or solidity, where solidity is used.

testcreate a new one in the directory TestAdoption.sol , write a test contract

pragma solidity ^0.4.17;import "Truffle/assert.sol"; The imported assertion import "Truffle/deployedaddresses.sol"; Used to obtain the address of the contract being tested import ". /contracts/adoption.sol "; Tested contract Contract Testadoption {Adoption Adoption = adoption (deployedaddresses.adoption ()); Adoption test Case function Testusercanadoptpet () public {uint Returnedid = adoption.adopt (8); UINT expected = 8; Assert.equal (Returnedid, expected, "adoption of pet ID 8 should be recorded."); }//pet owner test Case Function Testgetadopteraddressbypetid () public {//expect the address of the adopter to be the address of this contract, since the transaction is initiated by a test contract, address expecte D = this; Address adopter = adoption.adopters (8); Assert.equal (adopter, expected, "Owner of pet ID 8 should be recorded."); }//Test all adopters function Testgetadopteraddressbypetidinarray () public {//the address of the adopter is this contract address expected = this; ADDRESS[16] Memory adopters = adoption.getadopters (); Assert.equal (Adopters[8], expected, "Owner of pet ID 8 should be recorded."); }}

Assert.sol and Deployedaddresses.sol are provided by the truffle framework and do not provide a truffle directory under the test directory.

Add adopt test Cases to the Testadoption contract

Run test Cases

In the terminal, perform the

truffle test

If the test passes, the terminal outputs:

Using network ‘develop‘.Compiling ./contracts/Adoption.sol...Compiling ./test/TestAdoption.sol...Compiling truffle/Assert.sol...Compiling truffle/DeployedAddresses.sol...  TestAdoption    ? testUserCanAdoptPet (62ms)    ? testGetAdopterAddressByPetId (53ms)    ? testGetAdopterAddressByPetIdInArray (73ms)  3 passing (554ms)
Create user interface and smart contract interactions

We have written and deployed and tested our contracts, and then we write the UI for the contract so that the contracts can actually be used.

In truffle box pet-shop , the front-end code for the app is included, and the code is in the src/ folder.

Open in Editorsrc/js/app.js
You can see the app object used to manage the entire app, and the init function loads the pet information and initializes the WEB3.
WEB3 is a library that implements communication with the Ethereum node, and we use WEB3 to interact with the contract.

Initialize WEB3

Next, let's edit app.js to modify the INITWEB3 ():
Delete the comment and modify it to:

  initWeb3: function() {    // Is there an injected web3 instance?    if (typeof web3 !== ‘undefined‘) {      App.web3Provider = web3.currentProvider;    } else {      // If no injected web3 instance is detected, fall back to Ganache      App.web3Provider = new Web3.providers.HttpProvider(‘http://localhost:7545‘);    }    web3 = new Web3(App.web3Provider);    return App.initContract();  }

The code takes precedence over the WEB3 instance provided by mist or metamask, and if not, creates one from the local environment.

Instantiate a contract

Using Truffle-contract will help us save the contract deployment information, we do not need to manually modify the contract address, modify the Initcontract () code as follows:

initContract: function() {  // 加载Adoption.json,保存了Adoption的ABI(接口说明)信息及部署后的网络(地址)信息,它在编译合约的时候生成ABI,在部署的时候追加网络信息  $.getJSON(‘Adoption.json‘, function(data) {    // 用Adoption.json数据创建一个可交互的TruffleContract合约实例。    var AdoptionArtifact = data;    App.contracts.Adoption = TruffleContract(AdoptionArtifact);    // Set the provider for our contract    App.contracts.Adoption.setProvider(App.web3Provider);    // Use our contract to retrieve and mark the adopted pets    return App.markAdopted();  });  return App.bindEvents();}
Handling adoptions

Modify the markadopted () code:

  markAdopted: function(adopters, account) {    var adoptionInstance;    App.contracts.Adoption.deployed().then(function(instance) {      adoptionInstance = instance;      // 调用合约的getAdopters(), 用call读取信息不用消耗gas      return;    }).then(function(adopters) {      for (i = 0; i < adopters.length; i++) {        if (adopters[i] !== ‘0x0000000000000000000000000000000000000000‘) {          $(‘.panel-pet‘).eq(i).find(‘button‘).text(‘Success‘).attr(‘disabled‘, true);        }      }    }).catch(function(err) {      console.log(err.message);    });  }

Modify the Handleadopt () code:

  handleAdopt: function(event) {    event.preventDefault();    var petId = parseInt($(‘id‘));    var adoptionInstance;    // 获取用户账号    web3.eth.getAccounts(function(error, accounts) {      if (error) {        console.log(error);      }      var account = accounts[0];      App.contracts.Adoption.deployed().then(function(instance) {        adoptionInstance = instance;        // 发送交易领养宠物        return adoptionInstance.adopt(petId, {from: account});      }).then(function(result) {        return App.markAdopted();      }).catch(function(err) {        console.log(err.message);      });    });  }
Run the installation metamask in the browser

Metamask is a plug-in form of the Ethereum light client, the development process using Metamask and our Dapp to interact is a good choice, through this link installation, after installation, the browser toolbar will display a small Fox icon.

Configure Wallets

After accepting the privacy statement, the following page appears:

Here we create a good wallet for us by restoring a ganache as our development test wallet. Click Import Existing DENin the page to enter the mnemonic words ganache display.

candy maple cake sugar pudding cream honey rich smooth crumble sweet treat

Then you want the password, click OK.

Connecting the block chain network of development zone

The default connection is the Ethereum main network (upper left corner display), select Custom RPC, add a network:, after the point is returned, the following is displayed:

This is shown in the upper left corner as Private Network, the account is the default first account in ganache.

As of this metamask installation, the configuration is complete.

Installing and configuring Lite-server

Next requires a local Web server to provide access to the service, truffle box pet-shop provides a lite-server that can be used directly, and we'll see how it works.
Bs-config.json indicates the working directory of the Lite-server.

{  "server": {    "baseDir": ["./src", "./build/contracts"]  }}

./SRC is the Web site file directory
./build/contracts is the contract output directory

At the same time, the dev command is added to the scripts of the Package.json file:

"scripts": {  "dev": "lite-server",  "test": "echo \"Error: no test specified\" && exit 1"},

When running NPM run Dev, the Lite-server is started

Start the service
> npm run dev

will automatically open the browser to display our Dapp, such as the first picture of this article.
Now adoption has been pet look, when we click adopt , Metamask will prompt us to confirm the transaction,

After clicking on the submit confirmation, you can see that the pet was adopted successfully.

In Metamask, you can also see a list of transactions:

Well, congratulations, you've become a solid step towards becoming a hub-and-go application developer.

Reference documents
    • Truffle Handbook

In-depth blockchain-the system learns blockchain to create the best blockchain technology blog.

Step by step to teach you to develop and deploy your first de-centralized application (Dapp)-Pet Shop

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.