Let's do local development smart contract

Maca 2021-04-01 22:00:04 阅读数:326

let local development smart contract


Last article We sent a coin , Some people complain about online (remix) It's not nice to write code , ok , Let's take a look at how to develop smart contracts locally ?

One 、 Installation development environment

1. install Node,Node v8.9.4 Or later

I installed :


2. Integrated development framework truffle

that Truffle( Official website :https://www.trufflesuite.com/truffle) What is it? ,Truffle It's a world-class development environment , The test framework , The resource management channel of Ethereum , Committed to making development on Ethereum easy :

  • Built in smart contract compilation , link , Deployment and binary Management .
  • Automated contract testing , It can develop rapidly .
  • Scriptable , Scalable deployment and migration framework .
  • Network management for deployment to any number of public and private networks .
  • Package management and EthPM&NPM, Use ERC190 standard .
  • Interactive console for direct contract communication .
  • Configurable pipeline , Support tight integration .
  • External scripts run programs , stay Truffle Executing scripts in the environment .
$ npm install truffle -g

notes :-g Global installation

After installation , see truffle edition

$ truffle version

give the result as follows , We can see truffle、solidity、node and web3.js Version of , there solidity yes 0.5.16, We'll use this version later .

Truffle v5.1.52 (core: 5.1.52)
Solidity v0.5.16 (solc-js)
Node v10.15.3
Web3.js v1.2.9

3. download ganache

that ganache What is it? ? We use ganache To open a private chain for development testing , The default will be 7545 Run a development chain on the port .

Download address :https://www.trufflesuite.com/ganache , The suffix of the downloaded file is appx, It will take a little time to install , After the first installation , You can start it directly later , Starting is still a click Download the appx Installation package , Then click Start , Stupid, I didn't know how to start it at first , I've been looking for the installation directory .


Ganache After it's started, it's like this :


On the first line we can see that there is an account 、 block 、 transaction 、 contract 、 event 、 journal .

  • Account : By default there will be 10 Accounts , There were 100 individual ETH;
  • block : There is only one block , The genesis block ;
  • transaction 、 contract 、 event : Just started is empty ;

4. download IDE

Here we use VSCode, After downloading, we need to give VSCode Install several plug-ins ,solidity、solidity-windows、vscode-icons、local history.

Of course vscode-icons、local history You don't have to install it ,vscode-icons Just show the directory as a folder with icons , It seems more convenient .local history It's just that every time you change and save a file , It will be in the root directory .history The directory generates a modification log file , It's just a historical record , Easy code retrieval .

The necessary plug-ins are solidity、solidity-windows


good , We have finished the above preparatory work , Let's develop smart contracts together ,Just do it

Two 、 Create a Truffle project

For us beginners , We use the Truffle Boxes, They are sample applications and project templates .

1. Create a directory


2. download metacoin

Switch to the directory you just created , download metacoin, perform :

$ truffle unbox metacoin

If your machine is like me windows Words , You can run into this problem ,

$ truffle unbox metacoin

Starting unbox...

- Preparing to download box
√ Preparing to download box
- Downloading
× Downloading
Unbox failed!
RequestError: Error: getaddrinfo ENOENT raw.githubusercontent.com raw.githubusercontent.com:443
    at new RequestError (D:\Program Files\nodejs\node_global\node_modules\truffle\build\webpack:\node_modules\request-promise-core\lib\errors.js:14:1)
    at Request.plumbing.callback (D:\Program Files\nodejs\node_global\node_modules\truffle\build\webpack:\node_modules\request-promise-core\lib\plumbing.js:87:1)
    at Request.RP$callback [as _callback] (D:\Program Files\nodejs\node_global\node_modules\truffle\build\webpack:\node_modules\request-promise-core\lib\plumbing.js:46:1)
    at self.callback (D:\Program Files\nodejs\node_global\node_modules\truffle\build\webpack:\node_modules\request\request.js:185:1)
    at Request.emit (events.js:189:13)
    at Request.onRequestError (D:\Program Files\nodejs\node_global\node_modules\truffle\build\webpack:\node_modules\request\request.js:881:1)
    at ClientRequest.emit (events.js:189:13)
    at TLSSocket.socketErrorListener (_http_client.js:392:9)
    at TLSSocket.emit (events.js:189:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Truffle v5.1.52 (core: 5.1.52)
Node v10.15.3

resolvent :

 adopt https://www.ipaddress.com Inquire about raw.githubusercontent.com The address of .
To configure host file   C:\Windows\System32\drivers\etc\host    Add address  raw.githubusercontent.com

Linux Is to enter /etc/hosts  Add  raw.githubusercontent.com

And then redo the download metacoin The order of .

3. Use VSCode open

Use VSCode open D:\workspace\solidity\test Catalog


You can see that there are three directories ,contracts、migrations、test,

  • contracts/ Smart contract folder , All the smart contract files are placed here , It contains an important contract Migrations.sol( Later on )
  • migrations/ To handle deployment ( transfer ) Intelligent contract , Migration is an extra special contract to hold changes to the contract .( Be careful : Every migration The document has a serial number in front of it , This serial number means migration Execution order of documents )
  • test/ Smart contract test case folder
  • truffle.js/ The configuration file , Configure different networks

Other code can be left alone for the time being .

in addition , We see .sol In the document solidity Version is not the version we installed , therefore , Change to the version we just installed , Change to ^0.5.16,


stay truffle.js in , We need to get rid of networks Notes , Here you can define the development environment 、 Test environment 、 Production environment host、port、network_id


Code understanding is relatively simple , I've almost annotated it , I won't go into that , Code download address :https://github.com/joeBeckham/test.git


3、 ... and 、 Compile deployment

open VSCode The command line :

1. compile

$ truffle compile

I *, An error again :

PS D:\workspace\solidity\metacoin> truffle compile

truffle :  Unable to load file D:\Program Files\nodejs\node_global\truffle.ps1, Because scripts are not allowed to run on this system . For more information , see also https:/go.microsoft.com/fwlink/?LinkI
D=135170  Medium about_Execution_Policies.
The position of   That's ok :1  character : 1
+ truffle compile
+ ~~~~~~~
    + CategoryInfo          : SecurityError: (:) [],PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

reason :

It's starting on the computer Windows PowerShell when , The execution strategy is Restricted( default setting ).

Restricted Execution policy does not allow any scripts to run .

AllSigned and RemoteSigned Execution strategies prevent Windows PowerShell Run a script without a digital signature .

resolvent :

View active execution policies on your computer ,get-executionpolicy;

Open as Administrator PowerShell Input set-executionpolicy remotesigned, Set execution strategy

PS D:\workspace\solidity\metacoin> get-executionpolicy
PS D:\workspace\solidity\metacoin> set-executionpolicy remotesigned

Re execute the compile command :


After compilation , We'll see in the project build Folder , There will be abi、bytecode、network.


2. Deploy

truffle migration

In particular , stay migrations There is already one under the folder 1_initial_migration.js Deployment scripts , Used for deployment Migrations.sol contract .Migrations.sol To ensure that the same contract is not deployed .

And our main deployment script is in 2_deploy_contracts.js in , This script is for deployment MetaCoin contract , It will execute the script in the previous step in order .

A simple deployment contract script can be implemented in three lines :

//  Import contract 
const TestContract = artifacts.require("TestContract");

module.exports = function(deployer) {
  //  Deployment contract

2_deploy_contracts.js The content in is just imported again ConvertLib, And the ConvertLib Deploy ,ConvertLib After deployment ConvertLib Related to MetaCoin contract , And then deploy MetaCoin contract .


that , We execute the deployment order :truffle migration

The results of deployment are relatively long , I only post a part of :


We can see that there are deals hash、 Packed blocks 、 Number of blocks produced 、 Contract address 、 Account address 、 The account balance 、gas fee 、 The total cost ETH.

We're going to look at Ganache in , Account 0x16664D3d037d041183ff998Cb218602457Aff012 The balance after two decimal places is really 99.99,


Blocks do produce 4 individual :


It also produced 5 transaction :


They all showed it clearly .

3. test

truffle test

The contract is deployed , How do we test for correctness , You can't go directly , Money circle is not all a lot of projects are online collapse . There is one in the project directory test Folder , There are two files in the folder , One is metacoin.js, The other is TestMetaCoin.sol.metacoin.js It's through javascript test ,TestMetaCoin.sol adopt solidity To test . Here we use The second way TestMetaCoin.sol, So delete metacoin.js.TestMetaCoin.sol The code in is relatively simple :

 picture All test contracts must be in the form of Test start , Use uppercase T . This naming distinguishes the test contract from the normal contract , Let the test runner know which contract represents the test suite .

Similar to a test contract , All the testing methods , All have to be in lowercase words test start . Each test method is treated as a separate transaction , Execute according to the order defined in the test file .

that , Let's execute the test command :truffle test


We see two test All passed , The balance in the account of deployment contract is 10000.

Come here , Our whole process has run through , development environment 、 Coding tools 、 Local chain 、 The code to compile 、 Deploy 、 Test all ok 了 . Let's talk more about smart contracts .

in addition , If you don't like black backgrounds as much as I do , So let's switch the background color ,ctrl+k, ctrl+t, Choose the color we like .



版权声明:本文为[Maca]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2021/03/20210330185811153N.html