Editor’s note: this department The etheric fang evangelist Wang Shijun lecturer, sponsored by the nuggets technology community, etheric lane community foundation, fang lovers and ConsenSys co-host of the etheric fang “developers start guide | Jeth – the first phase of the Beijing games” sharing activities. Jeth’s series of offline activities centered on the theme of Ethereum technology development. Every issue of Jeth will invite excellent technical teams and engineers in the field of Taifang development to share technical dry goods offline. It aims to provide offline technology exchange and interaction opportunities for developers to help them grow.

Teacher Wang Shijun sharing video playback (Station B)

Share sort the portal

Intelligent contract full stack introduction – Howard | Jeth first issue

Explanation ERC20 tokens, and the raise – Xiong Libing | Jeth first issue

Shijun Wang is the author of gold nuggets column and gold nuggets pamphlet. His book “Introduction to Blockchain Development: Building ICO DApp Based on Ethereum Smart Contract from 0 to 1” has sold nearly 1000 copies. The wechat public account he founded and maintained, front-end Weekly, currently has more than 2,600 subscribers. In addition, he is the author of high quality technology video tutorials async/await, Styled – Components.

First, LET me introduce my background. I started to learn blockchain in May last year. Some of you may have been studying blockchain longer than me, so I am on the same starting line with you. I come from the front end and am very familiar with JavaScript and the code in today’s share is all JS except Solidity. If you have been doing this for a long time you will see that the languages aren’t really that different. People say Solidity is similar to JS but Solidity was actually created using Golang, Python and Javascript for idity. I have to introduce the content of the etheric lane is in my contact and development of this period of time, accumulated, and how to put the string together all the block chain point make a can use the application of the present may see a lot of data, but the real to construct objects may have little, then I will begin my share.

Before getting into the specifics, let’s take a look at what blockchain looks like in computer science, or the stack of blockchain technology. The bottom layer of blockchain relies on OS, followed by the infrastructure layer, which includes TCP/IP and cryptography. From 2017 to 2018, the explosion is the layer of blockchain protocol, including distributed and consensus algorithm, among which consensus algorithm is now engaged in very many people, but in fact, there has been very mature research in the distributed. The most successful application layer right now is ethereum, which introduced the concept of smart contracts and DApps. The top layer is the presentation layer, which is what all Internet products have now. For example, if you make a website, an H5 page, or even an APP, or even some API or command line interface for developers. Based on my own observation of the industry, I think not only front-end engineers, all application engineers can be involved in the application layer and the performance layer, but front-end engineers have a natural advantage in the performance layer.

Here’s what I’m going to share:

  1. The minimum necessary knowledge you need to build a complete blockchain DApp;
  2. How to prepare the development environment and what necessary conditions the development environment needs to have;
  3. How to integrate smart contracts into a familiar development environment;
  4. How to make a simple DApp and let it online for people to use.

Minimum necessary knowledge

I believe that everyone has heard of account, wallet, block, block chain and other words, but how to string these things together, really thinking, research may not be many people. First, let’s review the block shared by Howard and the structure of the block chain. Every block chain platform inside account mechanism, one of the most successful application block chain you should all know, called the currency, the currency can be thought of as decentralized bank, that there will be a transfer between different account transactions, within a period of time all transfer transactions come together to form a block, block of data structure also has introduced above, I don’t speak.

As time goes by a number of different blocks connected by some particular way, it formed a chain blocks, each block chain block can be thought of as number, the number is high, it needed to produce a different chain blocks of time is different, this time is a piece of time, now the currency will be about ten minutes, Ethereum takes more than 10 seconds.

As to the etheric, its essence is a distributed network, deployment, all messages including transfer, contracts and contract interface calls to a node, the node receives the message and then give his radio to all the nodes in the network, and then after the transaction is packaged block will also be broadcast to all nodes of the network.

So how do you interact with ethereum’s network? Take the micro channel applets we are familiar with now for example. Developers can create applets through the specific framework provided by the micro channel applets and the management background of the applets. Ordinary users can use the applets in the micro channel APP. Tencent’s server itself is centralized, only Tencent itself to maintain; In the Ethereum network, the community provides developers with many tools, such as web3.js, web3j, web3.swift, and etherScan. These tools or language packages interact with the Ethereum network through a node as an entry point. Users interact with the network by browsing a DApp or wallet.

The basic structure of an Ethereum account is very similar to that of a Bitcoin account, consisting of three elements: a private key, a public key, and an address. In addition to the main network, Ethereum also has three test networks. The main network can be understood as the online environment in the traditional software development environment. Rinkeby, Kovan and Ropsten are the three test networks.

After account, another familiar concept is blockchain wallet, which is like imToken or Bitpie, and Metamask, which we will introduce later. What is the relationship between wallet and account? We use this we know now the inside of the financial system to analogy the wallet and account, just say, I am in China merchants bank and construction bank opened two or three account, that I have a money on the surface of the package in my pocket, I actually hold 5 CARDS, for chain blocks inside than I installed a special purse, This wallet has ethereum accounts and bitcoin accounts, and I can have multiple Ethereum accounts and multiple Bitcoin accounts.

A smart contract is essentially a code-controlled account. The account itself is the same as the account you have in your wallet. The difference is that the private key of the account you have is in your hand, while the smart contract is in the hands of the contract deployer. An analogy for smart contracts can be drawn from familiar object-oriented concepts: I wrote a Class Class where I can generate many instances, and then in the blockchain world I have a smart contract source code that can be deployed to the several Ethereum networks described above. Each deployment produces a different contract instance, a completely different account. This should be the puzzle for many DApp developers, and the reason why smart contracts can’t be upgraded. Now there are also some “Trick” methods to complete the hot update of the contract, students who are just interested in it can search for it by themselves.

Smart contracts of the source code is written in a Solidity in most cases, the relationship between the contract account and general account with the above picture explain, developers through the network to the etheric fang send a contract to create instance, to get the contract instance address, with contract instance address after ordinary users can interact with the contract. For example, when it comes to EOS crowdfunding, it actually releases a smart contract on Ethereum. People participate in it every day, and when they participate in it, they take back the token and change the corresponding contract. Contracts can also interact with each other. A contract account is called an internal account, while a regular user account is usually called an external account.

Preparing for development Environment

Next comes the second topic, preparation for the development environment. What does it take to develop on the Ethereum blockchain to get started? There are only two key points: because it’s a P2P network, transactions, contract deployment all require nodes, meaning you need a node, and then any activity requires an account, even if you’re transferring a contract method that doesn’t cost money.

Specifically, the first requirement is to test network nodes. There are many kinds of methods, the first to run a node, called it private chain may not be accurate, the method of implementation or understanding of the cost of students do not do the bottom a little higher, do not recommend the application layer of students to use; This is highly recommended if you want to take control in your own hands.

Local development debugging can use Ganache, which makes it easy to pick up a node locally to process transactions, and Remix, which provides a JavaScript test network inside the browser. The Ganache and Remix Javascript VM are built with unlocked accounts, so you don’t need to worry about the account’s private key or mnemonic.

We can also use the shared test network, the Rinkeby, Ropsten, and Kovan nodes mentioned earlier, as the entry points to the network, so we don’t have to run the nodes ourselves. Infura. IO is a block link service for developers, but using it requires us to have our own registration, wallet and account management.

These two requirements are account and balance, since any operation on Ethereum requires an account to initiate, we need to create wallets and accounts. The DApp we develop runs in the browser, and for the PC side, the wallet should be seamlessly integrated with the browser. A good option in the community right now is Metamask, which is actually a browser plugin, but there was a security incident in Metamask history, someone sent a fake Metamask, and some users fell for it, so make sure you look for the fox icon when installing it.

In addition, many transactions on Ethereum are charged, which is the biggest pain point of ethereum. Some blockchain projects are trying to solve this problem, and there is no way to bypass it at present. When doing DApp test, we do not need to spend real money. We can use faucet provided by different test networks to recharge the test network account, that is, to charge ETH into Metamask wallet. These are the two necessary conditions to prepare your development environment, and the ones you need to do are Metamask, recharge, and register infura.io.

Smart Contract Workflow

Next is how to make a complete application. In contrast to traditional application development, there’s a back end and then there’s a front end, and we’ll start with the back end. The backend on Ethereum can be roughly replaced with smart contracts. All data in complex applications should not be stored on the Ethereum blockchain, and some data is stored in the traditional database. Here we simplify the setting that all data is stored on the chain.

There are two ways to do smart contract development. The first is through the Remix online IDE, which works reasonably well. The other way, for the front end, is to do it with an editor you’re familiar with plus a language you’re familiar with.

Remix is suitable for us to quickly verify concepts and prototypes. In Remix, we can quickly write contract code and then call its contract interface to test its behavior. In addition, we can also test existing contract instances. Contracts can also be deployed to any Ethereum network through Remix. Remix can also be used for single step debugging when you find strange problems with some interface of the contract. Remix, however, has an obvious drawback. In traditional software development workflows, there is usually version management, which is not possible in Remix, but is possible in our own workflows. We can use Git for version management and save the results of the contract compilation and deployment. The most important thing is to automate everything that can be automated, because you’re much less likely to make mistakes. This Remix and automated workflow are often used in combination, switching back and forth, in the actual work or learning process.

Then there is the very simple smart contract used in the actual DApp. You can think of it as a gambling prototype. The code is very simple, and the contract has two attributes: the manager of the contract, and who participates in the gambling activity. Constructor function is to set the contract administrator, and then participate in lucky draw/bet interface, then the random number function, in the etheric fang block chain is not very good random number method, contract to deploy on the etheric fang random number code after the others can see, it is able to know how your seed, and then it is easy to be manipulated. PickWinner is a lottery interface that calls a random number function and transfers the entire pool of money to the winner. The contract itself does not charge any fees, but only when the interface is called. The modifier is a security restriction that the lottery interface can only be invoked by the administrator of the contract. Security and permissions are also key issues to be considered in smart contracts. In the last two months, there are a lot of contract vulnerabilities, some of which are security restrictions and some of which are overflow, which deserve our attention.

In Remix, select JavaScript VM. It is a test network provided by Remix that runs in the browser memory. Its response speed is very fast. After selecting JavaScript VM, there are several default accounts. Click “Deploy” to Deploy the contract. You can see that soon you have an instance of the contract. In the instance interface, the contract interface is in red and the contract attributes are in blue. And then how do we bet?

You can see that there is no need to provide parameters for the bet, the amount of the bet needs to be filled in at the place where the transaction is initiated, bet once with the contract manager, now the player has one person, next to change the account, the next bet is to simulate two people, here becomes two people. When to adjust the lottery interface directly with the second account error, it is because our contract code inside force must be an administrator can call, examples of failure is no one to get the prize pool of money inside, cut the account back to the interface, you can see the first man got the prize pool inside all of the money, This is a very simple Remix contract workflow demo.

So how do you automate what you’re doing in this Remix? Next I’ll show you how to do the smart contract workflow in Node.js. I’ll start with two tools. The first is to compile the source code of the smart contract, which produces ByteCode, which is used for deployment to the test network. As well as the interface declaration ABI, the actual business code of the ABI tells you exactly which interfaces the contract exposes, and the type and number of parameters each interface receives.

The next thing you do in the workflow is build around this diagram, and you can see that web3.js is used, which can be thought of as a bridge between the application layer code and the Ethereum network. The way it works as a bridge is it can use a lot of different plug-ins. In Web3 it’s called a Provider, and when I run it in the browser, Metamask also provides a plug-in; Locally, Ganache-cli provides a plugin; If you only want to invoke the entry node provided by infura. IO, you can do so through an HTTP Provider.

Our first step is to turn the source code of the smart contract into a ByteCode that can be deployed to the Ethereum network and an ABI that can be used by our application-layer code. Compile the script code is also very simple, we can read the file, prepare a result save directory, and then call solc compile, then will deal with errors in the compile structure, and finally compile the result to the file system.

How do I test the contract on Web3 once it’s built? Just use Ganache- CLI directly. Before testing the contract code, we need to initialize the web3 instance and use Ganache’s Provider plug-in directly. In testing, we first create an isolated test environment, that is, each time we run the test, we redeploy the contract, then call the method on the new contract, or try to modify its state, and finally make assertions about its state.

The next step is to Deploy the Contract. When we create the Contract we need to pass in the ABI, and when we Deploy we need to pass in its ByteCode. As you can see, we need to have an account for everything we do. There are two parameters for gas, one is gas limited and the other is gas pressed. Students who are interested can study it by themselves.

Let’s look at a complete process test of the lottery contract. First, call the betting interface and unlock the first one in the account. Then, take out the player of the contract and confirm that the player is the one we bet. This is where the lottery interface is called. After the lottery, an assertion is made about the balance of the account of the deployment contract. Finally, after each lottery in our assertion, the players in the contract will be emptied.

What you need to do for contract deployment is a lot like what you would do for contract automation testing, but instead of the local network provided by Ganache-CLI, you deploy the Rinkaby test network, using a plug-in that provides a wallet mnemonic and a node for the network entry. It sends messages to nodes over HTTP for transactions. What you do next is similar to each time you isolate the test environment, unlock the account, and then deploy the contract. Since we were deployed on a real test network, this process usually took a long time. After each deployment we have a contract account address from which we can interact with the contract.

Finally, there is the process of stringing the whole process together, recompiling before deployment, and ensuring that all unit tests are fully passable on the latest contract.

DAPP building and deployment

After the contract is deployed, we already have a back end on the Ethereum blockchain that we can interact with directly. Then we need to write the code of this application layer to interact with the back end, and add the interface to the DApp.

The essence of this DApp from a technical perspective, and we’re not talking about business or anything else, is that a DApp can be understood as an interface that a white user can use to interact with and read front-end data. It can be a variety of forms, can be Web, App, can also be desktop software. If it’s a very simple DApp you can make a single page app with a blockchain back end.

Next we’ll do a very simple lottery or betting DApp, using create-React-app to make our tech stack very simple. There is also web3.js, which is used more in contract workflow, and web3.js is used in DApp to deal with ABI. If developed, the directory structure of the entire contract plus the DApp is similar to the one shown above, with the compile deployment script and test script placed under the corresponding directory.

We can map the interface to the source code of the contract. Now the prize pool has one ETH and one person is involved. However, the Balance attribute was not mentioned in the previous contract code. There is a balance in any one account. There is a total of one person participating in the lottery. There are two buttons. PickWinner = pickWinner = pickWinner

Let’s take a look at some of the key code implementations. The first is to use Web3 to build our bridge, and we’re going to assume that the people who use this DApp have Metamask installed. The second key thing is that when we create this contract, unlike deploying and compiling a script, we pass in an address. This is not a completely new contract instance. I’m going to load in this contract from this address.

The key interaction between DApp and smart contract is reading contract data and submitting data. So you can see here we have three properties on the interface, one is the administrator, one is the number of players and one is the amount of the prize pool in the contract, which is the account balance of the contract instance. The three interfaces in this interface are all asynchronous.

Render contract data because React syntax is relatively simple, students of DApp development must pay attention to conversion between units, we show the user ETH.

Modifying the contract data has a trigger point down here, attach onClick to this button, and what it does is actually call up the contract method and make some changes to the component state. When we submit the transaction, we will set loading state on the component. In loading state, the button cannot be clicked again, and then call participate. If Metamask is installed, the value passed to the contract should be filled in. The contract data state is reloaded.

To really make a user-friendly DApp, a lot of things need to be done on this basis. For example, after clicking the button and installing the Metamask, a Metamask transaction confirmation interface will pop up on the user’s screen immediately, which will make the user confused. I am clearly using your website to produce something I have never seen before. When the Metamask transaction confirmation box pops up, I need to give some hints to the user so that the user will not feel surprised.

Lottery DAPP DEMO

I have deployed the lottery DApp process on one of my machines in Aliyun. The deployment process is similar to that of traditional WEB applications. Before deployment, the code needs to be built, which uses the create-React-app built-in build script. We then use Express to start the minimalist HTTP service, the management service process uses PM2, and the deployment and build process can also be strung together using NPM script.

conclusion

This is the end of what I want to share. Although the blockchain field has been in existence for 9 years, it has been flooded with developers in the last one or two years. There are many concepts and good practices in this field.