Ethereum practice arrangement (IV) truffle smart contract development framework

zhutianxiang 2021-09-15 11:29:38 阅读数:843

ethereum practice arrangement iv truffle

comparison Remix Lightweight smart contract development ,Truffle It's world-class DApp Development framework , Use Truffle Development has the following advantages :

  • Built in smart contract compiler , link , Deployment and binary ( file ) management .
  • Rapid development of automated smart contract testing framework .
  • Scriptable 、 Scalable deployment and migration framework .
  • Manage multiple different Ethereum networks , It can be deployed to any number of public and private networks .
  • Use ERC190 standard , Use EthPM and NPM Carry out packaging management .
  • It supports direct interaction with smart contracts through the command console .
  • Configurable pipeline , Support tight integration .
  • Support in Truffle Execute scripts using an external script runner in the environment .

Truffle We are required to have a running Ethereum client , It supports the standard JSON RPC API Interface . There are many optional clients , For local development, it is recommended to use Ganache This private chain artifact works with .

Ganache client

The development cost of Ethereum main chain is too high , Testing the network to confirm the transaction also needs to wait for the miner to pack the block , Therefore, we need to build a private chain that is most suitable for local development .

Ganache The predecessor was TestRPC,Ganache It can help us quickly start an Ethereum private chain for development and testing 、 Carry out orders 、 Detect blockchain status, etc .Ganache It simulates the blockchain in memory , It returns... In real time when executing a transaction , Instead of waiting for the default block out time , So we can quickly verify the code . It is also a powerful client that supports automated testing .

Ganache Support the installation and use of command line and graphical user interface .

ganache Graphical user interface installation and use

visit Download and install Ganache

open Ganache, This process has helped you create a private chain and connect it , By default 10 A standby account :

Ganache Interface .png

The graphical user interface is very intuitive , Take a few minutes after starting to see what it roughly provides for us .

ganache-cli Command to install

Ganache Yes, it is JS Coded , The government also provided ganache-cli Tools , We can go straight through npm install ganache-cli:

npm install -g ganache-cli

After installed , Execute the following command to create a private chain :


Output 10 A default account address and private key 、 Wallet mnemonics and paths , as well as Gas Price、Gas Limit、Call Gas Limit、JSON-RPC Listening address and port :

Last login: Thu Sep 9 12:47:51 on console
The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit
MacBook:~ zhutx$ sudo npm install -g ganache-cli
changed 6 packages in 4s
2 packages are looking for funding
run `npm fund` for details
MacBook:~ zhutx$ ganache-cli
Ganache CLI v6.12.2 (ganache-core: 2.13.2)
Available Accounts
(0) 0x46C4deA8cF817d89cc4dFC98e8FA845F6BC3D57C (100 ETH)
(1) 0x4592e162Cc5B160B7671AD92e853f4Ba9657384f (100 ETH)
(2) 0x1b8eb1f19B9a4E2CC0D47dfFfb310b03Fe505F6B (100 ETH)
(3) 0x93721e2617B0A430a720Ac185A27A756177e395A (100 ETH)
(4) 0x4c5ce9257DEc2DFA845918DE53192E3994D097B9 (100 ETH)
(5) 0xa51d1dd429a4b19e1d83c1F50A659F5F0b0B957e (100 ETH)
(6) 0xa0937d9D62b0e6CD669C96FaCfd41C1cdBBa515D (100 ETH)
(7) 0x9399B1479DD232128ba739FBDD10AFa240a4108B (100 ETH)
(8) 0xe5dffcF3725e4641300a57F279A147F7f29131c6 (100 ETH)
(9) 0x256B285A933913cadC01B20bc71295852e15FE83 (100 ETH)
Private Keys
(0) 0x8764de67a305cf1c9ac9d3c20e6e77cd0f5e5cb46effa547f03faeea4da180a6
(1) 0x0812e9862a6628f74aa1f67885109a3896e6decdc7df7760700de1b693bb020f
(2) 0xf982a9613fcc1f2ea9f0f65b243f04802cabf9a6022e2f944b1b061f5902146c
(3) 0x7a81f3b4e206cb943db75a3b6d3c6a30a0f64677f5258d6f1349d7d84ae7b957
(4) 0x1d1dd875579563dcf0356db8c586f2eb8a76e7b2e6358f1b98dcd2b72c99a3ab
(5) 0xd0d4081c6d1e1a06304d2609d18a8e3955f0e66c433ed3253d52580b7887691e
(6) 0x57cbc15723faef1126a773bcf5d6e7fdbfc7db57459e8ce96a4b0bc6d33956f0
(7) 0xa8abb8b9f22c3cb2d3dd3cea473e0a88208a9c0f76415559a6f0e92cc208c322
(8) 0x53a19198bd00eb82d1d983c5d4df7d6e40a1ca7141cf7c14bc060ce525b9c220
(9) 0xdbcdd369f196e7ec281af5f5ab73975bf22bc692565ab3c534a7aaa0cd123b13
HD Wallet
Mnemonic: cry junk pretty grace shadow chalk load snow satisfy shield multiply emerge
Base HD Path: m/44'/60'/0'/0/{account_index}
Gas Price
Gas Limit
Call Gas Limit
Listening on

Ganache Common command parameters

Adjust the mining time (Ganache The default is mining when the transaction occurs ):

// 10 Second generates a block
ganache-cli -b 10

Specify the host port and network ID:

// Appoint IP, Port and network ID
ganache-cli -h -p 8545 -i 8888

Set up gas Price and gas ceiling :

ganache-cli -g 20000000
ganache-cli -l 10000000

Output RPC Call the request body :

ganache-cli -v

-v No version abbreviation , It is verbose It means ,RPC By default, only the method name is output , Such as eth_getBlockByNumber, While using -v The request body will be output , for example :

"id": 5156508106328661,
"jsonrpc": "2.0",
"params": [
"method": "eth_getBlockByNumber"

Specify the Ethernet currency of the default generated account :

ganache-cli -e 1000

Specify the number of accounts generated by default :

ganache-cli -a 50

Mnemonic words are related to :

ganache-cli -d
ganache-cli -m "boil razor arrest first space chicken social explain leader soon unique upset"
ganache-cli -s "hello"

-d: Give Way Ganache Use fixed predefined mnemonics when starting nodes , So other connections Ganache You don't have to import mnemonics every time .
-m: Mnemonics can be specified , Using the same mnemonic will generate the same HD wallet ;
-s: Specify a seed to use to generate mnemonics , Then use mnemonics to generate HD wallet , The same seed will produce the same mnemonic words , To generate the same HD wallet .

Designated account :

ganache-cli --account="<privatekey>,balance" [--account="<privatekey>,balance"]

Lock and unlock accounts :

// Use --secure --unlock
ganache-cli --secure --unlock "0x67a3119994f3fc7b384e086e443bf7a73a96a45c06eae3d1b163586ebc8e6f22" --unlock "0xac0603889ccee85ff0075de364d4fc92d383cec57c2a2c3465404c8296feab15"
// Or use -n -u
ganache-cli -n -u 0 -u 1

To quote in a project Ganache Of Provider

Ganache Is essentially a use JavaScript Implementation of the Ethereum client .Ganache Graphic interface and ganache-cli It's all about Ganache Did some encapsulation , And then in Node.js Just running , So in addition to using encapsulated graphical interfaces and ganache-cli Command line , You can also use JavaScript Use it directly Ganache Related functions .

Many light wallets or other tools are basically used web3.js,web3.js It is a library related to Ethereum , It has no Ethereum data , Therefore, you need to connect the Ethereum node , And provided through the Ethereum node JSON-RPC API To get the corresponding data .Provider Namely web3.js Modules that handle node connections .

Let's create a folder at will , Then execute the command under the folder :

npm init --yes
npm i web3
npm i ganache-cli

The above command is to initialize a project , Then install web3 and ganache-cli rely on . We build a account.js file , The contents are as follows :

// introduce web3.js rely on
const Web3 = require("web3");
// introduce ganache-cli rely on
const ganache = require("ganache-cli");
// Use Ganache Create a provider to web3.js Use
var web3 = new Web3(ganache.provider());
// getAccounts Get account information , Back to a Promise, Successful execution then, Failed execution catch

Use the above method in the development process Ganache, You can avoid using every time Ganache Start a node with a graphical interface or command line .

Start... In the project Ganache Of Server

Ganache In addition to directly providing Provider outside , It can also be used as a HTTP Server, In this way, some other services or applications can pass HTTP Call the corresponding interface . Very simple to use , We use the project established above , But add a dependency CircularJSON, Execute the following command to install :

npm i circular-json -S

Then create a... Under the project directory server.js file , The contents are as follows :

// introduce fs modular , For reading and writing files
const fs = require('fs');
// introduce ganache-cli Used to provide test services
const ganache = require("ganache-cli");
// introduce circular-json Used to format the output object
const CircularJSON = require('circular-json');
var server = ganache.server();
// monitor 8545 port
server.listen(8545, function(err, blockchain) {
// console.log(blockchain)
// fs.writeFileSync('blockchain.txt', CircularJSON.stringify(blockchain));
// Output ganache-cli Middle block chain data structure and content blockchain In file
fs.writeFileSync('blockchain.txt', CircularJSON.stringify(blockchain, null, '\t'));
// Print Wallet mnemonics

Starting the server does not require web3.js, But you need documents , So the introduction of Node.js Of fs Module and circular-json Convert objects to strings , Because there are circular references in the object , So you can't use JSON, It USES CircularJSON.

The listening port is set above 8545, In the callback function, we print blockchain Mnemonics for , Of course, you can also print other blockchain Data in .blockchain There's a lot of data , So I didn't use it directly console Output , But write blockchain.txt In file , Reading this file is helpful to understand the data structure of Ethereum blockchain .

Because there's a lot of data , Not one by one here blockchain The data of the , If you are interested, you can try it yourself , And let's see blockchain The data in the file .

Configuration project depends on Ganache

Ganache The configuration that the project depends on is basically the same as the command parameters used on the command line , The following is a Ganache Projects rely on common configurations :

Parameters explain
accounts And the command line --accounts identical
logger Realized log Object of method , for example console, Used to output logs
mnemonic character string , Set mnemonics
port Integers , Set port
seed character string , Set seeds
total_accounts Numeric type , Number of accounts
default_balance_ether Each generated account , The default number of ethereums
network_id Integers , The Internet ID
blocked boolean value , Whether to lock the account
unlocked_accounts Array , Don't lock the account 、 Address or index value
db_path Block data storage location
verbose Output object and return object

Let's modify the above example :

// introduce fs modular , For reading and writing files
const fs = require('fs');
// introduce ganache-cli Used to provide test services
const ganache = require("ganache-cli");
// introduce circular-json Used to format the output object
const CircularJSON = require('circular-json');
let logOptions = {
flags: 'a',
encoding: 'utf8'
// Configure output options
let stdout = fs.createWriteStream('./stdout.log', logOptions);
// Configure the output log
let logger = new console.Console(stdout);
let options = {
// Set the log exporter
"logger": logger,
// Set mnemonics
"mnemonic": "film bind rail critic diamond tourist aim audit master odor major rabbit",
// Set the number of accounts
"total_accounts": 20,
// Set the etheric currency for each account
"default_balance_ether": 200,
// Set the database path
"db_path": "./db",
"verbose": true
// Start the service with the specified configuration
var server = ganache.server(options);
// monitor 8545 port
server.listen(8545, function(err, blockchain) {
// console.log(blockchain)
// fs.writeFileSync('blockchain.txt', CircularJSON.stringify(blockchain));
// Output ganache-cli Middle block chain data structure and content blockchain In file
fs.writeFileSync('blockchain.txt', CircularJSON.stringify(blockchain, null, '\t'));
// Print Wallet mnemonics

In the above example, we added a options, It's configured with a logger Let the log output to a file , Appoint mnimonic To generate accounts , The number of generated accounts is specified as 20 individual , The balance of each account is specified as 200Ether, Specify the blockchain data storage location as the current directory db, The output of the log is the request object and the return object .

about Provider It's the same thing , You can create :


Ganache Transaction related RPC Method

Ethereum use JSON-RPC The protocol is used to provide RPC service , The current version is JSON-RPC 2.0,Ganache This protocol is also implemented . We usually use web3.js Code base to call Ethereum RPC Interface , We'll talk about that separately web3.js Use , So here Ganache Packaged RPC I won't introduce the method .


Just beginning to use Ganache Words , Just install and start the graphical interface ,Ganache When ready , Let me start Truffle.

install truffle

npm install -g truffle

establish truffle engineering

You can create an empty project template , But for new contacts Truffle Classmate , Recommended Truffle Boxes, It provides sample application code and project templates . We will use MetaCoin box As a case study , It creates a that can be transferred between accounts Token( Tokens, )

mkdir MetaCoin
cd MetaCoin

download (“unbox”) MetaCoin box:

truffle unbox metacoin
If you want to create an empty project without a contract , have access to truffle init

If appear Unbox failed Because you can't access overseas domain names , The modified /etc/hosts Then execute again :

# GitHub Start
# GitHub End

After the operation , There is such a project directory structure :

truffle Directory structure .png

You can modify truffle-config.js Of networks.development To configure truffle Connect the corresponding network .

truffle The project is connected locally by default 7545 Port private chain , We see the Ganache Set up -SERVER, See that the private chain port is 7545, Therefore, there is no need to modify the network .

MetaCoin.sol It's the core code , All other files serve this file , Files in other directories are used to cooperate with the file test 、 Compile and upload the blockchain platform .


stay truffle Implementation under the project directory :

truffle test ./test/TestMetaCoin.sol


truffle compile

After successful compilation , Project directory will add build Catalog . The files produced in this directory can deploy the smart contract to the private chain through the deployment interface .


keep Ganache On state , Execute the following command :

truffle migrate

Deployment success , here Ganache The account number and transaction data have changed accordingly .


Interact with the private chain environment through the command line , Put the account 0 Of MetaCoin Token transfer to account 1 Next :

// Get into truffle Of JS Command line environment
MacBook:MetaCoin zhutx$ truffle console
// Get contract instance
truffle(ganache)> let instance = await MetaCoin.deployed()
// Get all accounts
truffle(ganache)> let accounts = await web3.eth.getAccounts()
// View all accounts
truffle(ganache)> web3.eth.getAccounts()
// View account 0 Next MetaCoin Token balance
truffle(ganache)> (await web3.eth.getAccounts())[0]
truffle(ganache)> let balance = await instance.getBalance(accounts[0])
truffle(ganache)> balance.toNumber()
// Give the account 1 Transfer 500 individual MetaCoin Tokens,
truffle(ganache)> instance.sendCoin(accounts[1], 500)
tx: '0x2117baf16bf016885f9081b5f3a2ebf9681af0c60df8ae8b2b84caa94a77fed9',
receipt: {
transactionHash: '0x2117baf16bf016885f9081b5f3a2ebf9681af0c60df8ae8b2b84caa94a77fed9',
transactionIndex: 0,
blockHash: '0x4eb868c2dbde65c5c9ea1c7d2530fb32ed5b737257b71a22066a80f29601a99d',
blockNumber: 6,
from: '0xa8d9cfeb347d866dba06f057bab791c575d60ab4',
to: '0x2068728d1ca0b5f174a660131ceccccb16560305',
gasUsed: 51520,
cumulativeGasUsed: 51520,
contractAddress: null,
logs: [ [Object] ],
status: true,
logsBloom: '0x00000000000000000000000000000000000000000000200000000000000000000000000000000000001000000000000000000000000000000000000000000000200000000000000000000008000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000010000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000002000000000000000000020000000080000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000',
rawLogs: [ [Object] ]
logs: [
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x2117baf16bf016885f9081b5f3a2ebf9681af0c60df8ae8b2b84caa94a77fed9',
blockHash: '0x4eb868c2dbde65c5c9ea1c7d2530fb32ed5b737257b71a22066a80f29601a99d',
blockNumber: 6,
address: '0x2068728D1Ca0b5F174A660131ceCccCB16560305',
type: 'mined',
id: 'log_77dfcf05',
event: 'Transfer',
args: [Result]
// Check the account 1 The balance of the
truffle(ganache)> let received = await instance.getBalance(accounts[1])
truffle(ganache)> received.toNumber()
// Check the account 0 The balance of the
truffle(ganache)> let newBalance = await instance.getBalance(accounts[0])
truffle(ganache)> newBalance.toNumber()

Although the above command is executed on the command line , But with DAPP Created during user interface development vue Front end engineering introduces Web3.js Library to call is the same , The essence is to call Web3.js The code base , Interact with Ethereum .