Line 1 code: ethereum (3)-use more tools to write and test smart contracts

Source: Internet
Author: User
Tags javascript extension install node git commands
The first line of code: ethereum began to be serialized.

In this article, we have used the remix environment to run and test the first smart contract program written in this book. However, there are many testing methods for writing and testing smart contracts, for example, testing in the testrpc environment; in intellij idea integrated development environment, you can use the solidity language to write smart contracts, test smart contracts in a pure web environment, and test smart contracts using Ajax. This article describes how to write and test smart contracts in detail.

1. Install the local remix environment (Windows, Mac OS X, and Linux)

This section uses the remix environment to run and test the calc smart contract, but uses the online remix environment. For some reason (such as no network or slow network speed), we want to use a local remix environment to run and test smart contracts, so we need to install the remix environment locally. Remix is cross-platform, so the installation method described in this section is applicable to both windows, Mac OS X, and Linux.

No matter what operating system install remix, you must install node. JS, readers can go to the https://nodejs.org to download the latest version of node. js directly installed.

After installing node. JS, you need to use the GIT command to download the remix code library (browser-solidity). The command line is as follows:

Git clone https://github.com/ethereum/browser-solidity

In Mac OS X and Linux, git commands are generally integrated, but in windows, there is no git command by default. Therefore, you need to download the GIT tool for windows on the following page, after the download is complete, install it directly.

Https://git-scm.com/download/win

After using the GIT command to download the remix code base, run the CD command to go to the browser-solidity Directory, which is automatically created in the current directory when downloading the remix code base.

Run the following command in the browser-solidity directory to install browser-solidity.

NPM install

It takes a long time to install browser-solidity. Is the effect of installing the browser-solidity environment in windows.

If browser-Solidity is successfully installed, run the following command to start the remix service.

NPM start

Is the output information after the remix service is started in Mac OS X, and similar information is output in Windows and Linux.

The default port number of the remix service is 8080. If you enter the following URL in the address bar of the browser, you can use the local remix environment to write and test the smart contract.

Http: // localhost: 8080

2. Install testrpc

Unlike geth, testrpc is a real ethereum environment, while testrpc is an ethereum environment simulated locally, which is mainly used for development and debugging. After the smart contract is successfully debugged using testrpc, it can be deployed in the real ethereum environment.
To install testrpc, you still need the node. js environment. Therefore, you should install node. js in advance and then use the following command to install testrpc.
NPM install-G ethereumjs-testrpc

After testrpc is installed, run the testrpc command. Is the effect of starting the testrpc service under Mac OS X.

Is the effect of starting the testrpc service in windows.

We can see that, no matter on which platform the testrpc service is started, 10 accounts and 10 private keys are automatically generated ). These accounts and private keys are used for testing, and each account has an almost infinite amount of ethereum. Therefore, you do not have to worry about the lack of ethereum for some operations.

Testrpc itself is a service. The default port number is 8545, which is used to connect libraries like web3.js and web3.py to ethereum nodes, testrpc is actually equivalent to an ethereum node used for testing.

3. Use testrpc to test smart contracts

This Section deploy the smart contract to the testrpc service, connect to the testrpc service using web3.js, and call the functions in the smart contract. The procedure is as follows:

(1) write smart contracts

Start the local remix environment and enter the following smart contract code in the remix environment.

In this example, a smart contract program named factorial is compiled. In this smart contract, a factorial function is used to calculate the factorial of N.

Pragma solidity ^ 0.4.0; contract factorial {/* calculate the N factorial */function factorial (uint N) returns (uint) {If (n = 0 | n = 1) return 1; else return N * factorial (n-1 );}}

This smart contract is used to calculate the factorial of N.

(2) Deploy the smart contract on the testrpc Node

Go to the "run" page on the right of the remix environment and select "web3 provider" in the "Environment" list, as shown in.

In the web3 provider environment, remix can directly deploy the smart contract to the testrpc service. Before entering the web3 provider, a dialog box is displayed, asking whether to connect to the ethereum node, and clicking "OK". The dialog box shown in is displayed. The dialog box contains a text box. The default value is http: // localhost: 8545. To connect to a local testrpc node or ethereum node, click "OK. If the testrpc node has been started, the local environment of remix will be successfully connected to the testrpc node.

Click the "deploy" button on the "run" page to deploy the factorial smart contract to testrpc. After the deployment is successful, the "factorial" button appears at the bottom of the "run" page, as shown in. Enter the value of N to calculate the factorial in the text box on the right of the button, and click this button to execute the factorial function in the ethereum test environment (testrpc, however, after clicking the "details" button in the log area, the output result of the factorial function is not displayed, because the factoria function runs directly in the ethereum network, all data is stored in the ethereum network and will not be directly returned to the ethereum client.

At the top of the "factorial" button is the address of the factorial smart contract. If you want to access this smart contract on the client, you need to use this address.

(3) install the solidity Compiler

The solidity compiler is used to compile the solidity source code file (. Sol file). You can compile the solidity source code file into multiple target files. Use the following command line to install the solidity compiler.

NPM install-G Solc

(4) Compile the solidity source code file

Create a factorial. Sol file in the current directory and copy the code in example 3.2 to the factorial. Sol file. Next, compile the factorial. Sol file using the solidity compiler installed in the previous step. Note that although Solc is installed, the compiler command line tool is solcjs. This tool can compile the solidity source code file into multiple target files. For this example, you only need the ABI file, which is an interface file of smart contract. That is to say, to use web3.js to call a smart contract, you must use the ABI file to call the function in the smart contract.

Use the following command to compile the factorial. Sol file to generate an ABI file. -- Abi is a command line parameter, indicating that the type of the generated target file is Abi.

Solcjs -- Abi factorial. Sol

After the preceding command is executed, a factorial_sol_factorial.abi file is generated in the current directory, which is the ABI file corresponding to factorial. Sol.

(5) install web3.js

Before using web3.js, you must install web3.js. web3.js is a module of node. js. Therefore, you need to install it using the following command.

NPM install web3

Use the above command to install the latest version of web3. If you are not familiar with the latest version of web3, you can use the following command to install the specified version.

NPM install [email protected]

(6) Use web3.js to connect to the testrpc Node

Now, run the node command to enter the repl environment (command line interaction environment) of node. JS, and then execute the following command in the node repl environment. Note that before executing these commands, you must start the testrpc node and deploy the smart contract in example 3.2 to the testrpc node using the remix environment.

> var Web3 = require("web3");> var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); undefined> var eth = web3.ethundefined> var abi = JSON.parse(fs.readFileSync("Factorial_sol_Factorial.abi").toString());undefined> var contract = eth.contract(abi);undefined> var instance = contract.at(‘0x371f45db1a077bbcbeb50d2a21bc85e4e18c1f1f‘)undefined> instance.factorial.call(3){ [String: ‘6‘] s: 1, e: 0, c: [ 6 ] }> instance.factorial(10, {from:eth.accounts[0]})‘0xbb291fec53c4c5aefc87e2d7e8475c4abd4c54d03ef06e857665a10db0c1a3ff‘

In the above content, ">" indicates the command prompt, followed by the input code. below is the output value, and undefined is the output by node, indicates that the current statement has no output (the Javascript statement defining the variable will not output anything ). From these lines of code, you can understand the core steps for connecting to the testrpc node through web3.js (the same steps as connecting to the ethereum node) as follows.

(1) import the web3 module with the following code:
var Web3 = require("web3");
(2) create a web3 class instance and specify the URL (IP address and port number) of the testrpc node by using the constructor parameters of this class. The Code is as follows:
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
(3) read the content of the factorial_sol_factorial.abi file and convert the content of the file to a JSON object. The Code is as follows:
var abi = JSON.parse(fs.readFileSync("Factorial_sol_Factorial.abi").toString());
(4) use Abi to create a smart contract object. The Code is as follows:
var contract = eth.contract(abi);
(5) bind the smart contract with the smart contract deployed in testrpc. The Code is as follows:
var instance = contract.at(‘0x371f45db1a077bbcbeb50d2a21bc85e4e18c1f1f‘)

The parameter value of the at method is the smart contract address above the factorial method shown in Figure 3-12. It is also the only identifier in ethereum that can locate a specific smart contract. Click the button on the right of the address to copy the address to the clipboard.

(6) Call the factorial function in the smart contract locally. The Code is as follows:
instance.factorial.call(3)

Local smart contract calls do not affect the ethereum network. When a function in the smart contract is called locally, the return value of the function is directly output. If the function returns a value type, it returns a value of the bignumber type. This is a javascript extension that allows JavaScript to operate on any value, the bignumber type will be explained in detail in later chapters.

Execute the above Code and output the following content. Obviously, the factorial of 3 is 6.

[String: ‘6‘] s: 1, e: 0, c: [ 6 ] }
(7) call a smart contract on ethereum. The Code is as follows:
instance.factorial(10, {from:eth.accounts[0]})

The function that calls the smart contract on ethereum network does not directly obtain the function return value on the client, but obtains the following transaction address.

Bytes

Any operation on the ethereum network is considered as a transaction. Since there is a transaction, a transaction address is required. You can use the corresponding API to query the transaction status based on the transaction address. There are many types of addresses in ethereum networks, such as miner addresses, smart contract addresses, and transaction addresses. Each type of address is composed of several hexadecimal numbers, but the numbers of different types of addresses may be different.

In the real ethereum network, any transaction must be processed by miners for mining. At the same time, each fair will be rewarded to the miners who have completed their work, that is, the miner's mining income. However, in the testrpc node, because it is simulating the ethereum network and mining, the operations on the ethereum network are directly executed without mining. Therefore, if the client is connected to the testrpc node, the transaction will be executed immediately after the transaction is initiated. In addition, to call a smart contract on the ethereum network, you need to specify who initiated the transaction (one representing the user's address), because in the actual ethereum network, the corresponding etherecoin will be deducted from this address to the miner. This example uses the address specified by ETH. Accounts [0. Eth. Accounts can obtain the addresses of the 10 test accounts generated when the testrpc node starts. eth. Accounts [0] is the address of the first test account.

From the case in this section, the client accesses the ethereum network in two steps: Connecting the ethereum node and initiating a transaction. Of course, the ethereum network must process the transaction, the miner needs to mine (compete for the right to handle the transaction and get a return.
3.2.4 intellij idea solidity plugin
Neither remix, Windows notepad, or other text editors are used to develop complex smart contracts. First, the interface is unfriendly, and second, there is no necessary smart notification function, in addition, if the amount of smart contract code is large, the remix may die. Therefore, the tool described above is only used to test smart contracts, and is not used to develop actual smart contract projects. If you want to develop large-scale smart contract projects, you usually use local ides, such as intellij idea. This IDE was initially launched for Java development. However, since intellij idea supports third-party plug-ins, in theory, intellij idea can support any programming language.

Many readers may not be familiar with intellij idea. In fact, this IDE is launched by the famous jetbrains company. If you do not know jetbrains and its products, therefore, Android studio, Android development tools released by Android and Google, must be familiar. Android studio is developed on the basis of intellij idea community edition. Jetbrains also developed the well-known kotlin language, which has now become an official recommendation programming language for Android apps.

You can download the free version of intellij idea (Community version) on the following page ).
Https://www.jetbrains.com/idea/download

The solidity language also provides the intellij idea plug-in. We recommend that you install intellij idea online. For intellij idea of Mac OSX, click the preferences menu in the upper-left corner, as shown in.

For intellij idea in windows, click the settings menu item in the File menu. Click this menu item. The preference (setting) window is displayed, as shown in.

The list in the middle of the preferences window lists all plug-ins installed by intellij idea. Click the Browse repositories button in the lower part of the window. The Browse repositories window is displayed. In the text box in the upper left corner of the window, enter "solidity" to search for related plug-ins online, as shown in. If yes, the details of the selected plug-in are displayed on the right. If the plug-in is not installed, the Install button is displayed on the right. Click the Install button to install the plug-in.

After installing the plug-in, create a Java or other project in intellij idea (the solidity plug-in does not provide the solidity project), and then right-click the new menu item in the project menu, the sub-menu shown in is displayed. A smart contract menu item is found on the sub-menu.

Click the smart contract menu item. The new solidity file window, as shown in, is displayed. From the kind list box, you can select the solidity file type (smart contract or solidity library). In this example, select smart contract.

Enter the name of the solidity file in the name text box, and click OK to create the solidity file. Double-click the created solidity file in the engineering tree on the left side of intellij idea. The code editing area is displayed on the right side, and enter the solidity code shown in.

Although you can write the solidity code in intellij idea and support code highlighting and smart prompts, compiling the solidity source code file still needs to be switched to the terminal and compiled using the solcjs command, which is very troublesome, in the next section, we will teach you how to integrate solcjs commands into intellij idea. You can compile the solidity source code file without switching to the terminal.

5. Integrate the solidity compilation tool with intellij idea

Intellij idea has an extended tool function that can integrate executable programs with intellij idea. That is to say, these programs can be executed without switching to a terminal.

Open the Preference window (in windows, the setting window), find the tools> external tools node in the left-side Navigation Pane, and click the node. The list of Integrated extended tools is displayed on the right, the default value is null. Click the "+" button at the bottom of the region to bring up a create tool window. In this window, you must enter the following four fields.

  • Name: solidity
  • Program: solcjs
  • Parameters: -- Abi -- bin $ filename $-o $ outputpath $
  • Working directory: $ filedir $

The effect is shown in. Click OK to create the extension tool.

You should understand the following points when creating an extension tool.

  • The name is only the name of the extension tool used for display. It can be specified at Will or even be the same as an existing extension tool.
  • The solcjs command specified by program can be directly executed on the terminal; otherwise, an error occurs that cannot be executed. Therefore, before creating an extension tool, use the NPM install-G Solc command to install solcjs.
  • Parameters indicates the command line parameters of solcjs, where -- Abi indicates compiling the solidity source code file into an interface file (. abi file), -- bin indicates to compile the solidity source code file into a binary file (. binfile), used to publish smart contracts. Although these two types of files are not required at any time, you can generate them together to save trouble.
  • -O indicates the path of the generated target file (. Abi and. binfile.
  • $ Filename $, $ outputpath $, and $ filedir $ are environment variables provided by intellij idea. $ filename $ indicates the selected file name, and $ outputpath $ indicates the output directory of the file, $ filedir $ indicates the directory of the selected file.

In Mac OS X, $ outputpath $ points to the out sub-directory of the project directory, where all generated files related to the project are stored. The directory structure is the same as that of the src directory. Figure 3-20 shows the structure of the out directory. Note that the directory structure on the reader machine may be different, but the. Abi and. binfiles are both in the out/production directory or their subdirectories.

If the solcjs file cannot be executed in windows, because it is used in Mac OS X and Linux, and solcjs. CMD in Windows, you need to change program to solcjs. cmd. In Windows, intellij idea does not have the built-in $ outputpath $ variable. Therefore, you can change this variable to another value, such as $ filedir $. the sol file is generated in the same directory. abi and. binfile. Therefore, intellij idea for Windows needs to set the extension tool according to the following content.

  • Name: solidity
  • Program: solcjs. cmd
  • Parameters: -- Abi -- bin $ filename $-o $ filedir $
  • Working directory: $ filedir $

After setting the extension tool in the preceding way, select one. sol file (assuming the file name is mycalc. sol, in which the smart contract name is calc), a solidity menu item appears in tools> external tools of intellij idea, as shown in 3-21, click this menu item, it will call solcjs to compile mycalc. and generate the mycalc_sol_calc.abi and mycalc_sol_calc.bin files in the corresponding directory.

In fact, you can find the external tools> solidity menu item in the right-click menu of the project, as shown in. Click this menu item, and the effect is the same.

Line 1 code: ethereum (3)-use more tools to write and test smart contracts

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.