以太坊开发(一)Truffle入门到实战

什么是Truffle

Truffle是一个世界级的开发环境,测试框架,以太坊的资源管理通道,致力于让以太坊上的开发变得简单,Truffle提供:

  • 内置的智能合约编译,链接,部署和二进制文件的管理。
  • 针对快速迭代开发的自动化合约测试。
  • 可脚本化,可扩展的部署与迁移框架。
  • 用于部署到任意数量的公网或私网的网络环境管理。
  • 使用EthPM&NPM提供的包管理,使用ERC190标准。
  • 与合约直接通信的交互控制台。
  • 可配的构建流程,支持紧密集成。
  • 在Truffle环境里支持执行外部的脚本。

本篇文章将介绍怎样使用Truffle进行智能合约的编译、部署和测试。

第一步,安装Truffle

$ sudo npm install -g truffle

安装完成后执行下面的命令,确保Truffle被正确安装

zhujiantao@ubuntu:~$ truffle
Truffle v4.1.14 - a development framework for Ethereum

Usage: truffle <command> [options]

Commands:
  init      Initialize new and empty Ethereum project
  compile   Compile contract source files
  migrate   Run migrations to deploy contracts
  deploy    (alias for migrate)
  build     Execute build pipeline (if configuration present)
  test      Run JavaScript and Solidity tests
  debug     Interactively debug any transaction on the blockchain (experimental)
  opcode    Print the compiled opcodes for a given contract
  console   Run a console with contract abstractions and commands available
  develop   Open a console with a local development blockchain
  create    Helper to create new contracts, migrations and tests
  install   Install a package from the Ethereum Package Registry
  publish   Publish a package to the Ethereum Package Registry
  networks  Show addresses for deployed contracts on each network
  watch     Watch filesystem for changes and rebuild the project automatically
  serve     Serve the build directory on localhost and watch for changes
  exec      Execute a JS module within this Truffle environment
  unbox     Download a Truffle Box, a pre-built Truffle project
  version   Show version number and exit

See more at http://truffleframework.com/docs

第二步,创建并初始化项目

创建工程目录并执行初始化命令

zhujiantao@ubuntu:~$ mkdir dapp
zhujiantao@ubuntu:~$ cd dapp/
zhujiantao@ubuntu:~/dapp$ truffle init
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!

Commands:

  Compile:        truffle compile
  Migrate:        truffle migrate
  Test contracts: truffle test
zhujiantao@ubuntu:~/dapp$ tree
.
├── contracts
│   └── Migrations.sol
├── migrations
│   └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js

3 directories, 4 files

执行初始化命令后可以看到目录下生成了一些目录及文件,其中:contracts目录下存放合约文件,migrations下存放迁移部署脚本,test目录下存放测试文件,truffle.js和truffle-config.js为Truffle配置文件

接下来介绍一下 Truffle Boxes,Truffle Boxes装有很多一些实用的项目模板,能让你忽略一些环境配置问题,从而使你能更专注于你的dapp特性开发。此外,Truffle Boxes还包含其他有用的组件, Solidity 合约和库, 前后端视图等等。更多可查看官网

那就下载个模板看看,MetaCoin是一个简单的代币应用,以此为例

zhujiantao@ubuntu:~/dapp$ truffle unbox metacoin
Downloading...
Error: Something already exists at the destination. `truffle init` and `truffle unbox` must be executed in an empty folder. Stopping to prevent overwriting data.
   at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-box/lib/utils/unbox.js:22:1
   at <anonymous>
   at process._tickCallback (internal/process/next_tick.js:188:7)
   at Function.Module.runMain (module.js:695:11)
   at startup (bootstrap_node.js:188:16)
   at bootstrap_node.js:609:3

可以看到truffle init和truffle unbox都需要在空文件夹中执行,以防止数据重写,没关系,重新建一个工程目录好了。

zhujiantao@ubuntu:~$ mkdir MetaCoin
zhujiantao@ubuntu:~$ cd MetaCoin/
zhujiantao@ubuntu:~/MetaCoin$ truffle unbox metacoin
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!

Commands:

 Compile contracts: truffle compile
 Migrate contracts: truffle migrate
 Test contracts:    truffle test
zhujiantao@ubuntu:~/MetaCoin$ tree
.
├── contracts
│   ├── ConvertLib.sol
│   ├── MetaCoin.sol
│   └── Migrations.sol
├── migrations
│   ├── 1_initial_migration.js
│   └── 2_deploy_contracts.js
├── test
│   ├── metacoin.js
│   └── TestMetacoin.sol
├── truffle-config.js
└── truffle.js

3 directories, 9 files

相比执行init,多了关于metacoin的合约和库文件,合约部署文件和测试文件,关于这些文件的详细内容将在下篇文章中一一拆解

第三步,启动以太坊客户端

我们需要安装Ethereum客户端来支持JSON RPC API的调用。

有许多的以太坊客户端可以选择。我们推荐在本地开发和主网部署时使用不同客户端。

本地开发可以使用Canache、Ethereumjs-testrpc、或者truffle自带的Truffle Develop。

主网部署时使用Geth。

这里以Ethereumjs-testrpc为例,事实上,合约在部署到主网之前,都应先使用TestRPC进行充分测试。

安装

$ sudo npm install -g ethereumjs-testrpc

运行

zhujiantao@ubuntu:~$ testrpc
EthereumJS TestRPC v6.0.3 (ganache-core: 2.0.2)

Available Accounts
==================
(0) 0x14b1cf637d214963cd31c923711930aa7b97fd5b
(1) 0x8703ffa009e31e0eebf3aa2dacb32486e06077c0
(2) 0x2237e37056828dfb27e94a3274132a59ae5b4413
(3) 0x1744da91d3eca87fbcf2711740b12e62739965ec
(4) 0x3c35f08665a047f90ddce14d0f82b703a240a56f
(5) 0x2d4fa09b9f71d7b66a9c36d15eeda7311f49b837
(6) 0xc75df94d9a941cbab2a1297bd5770f0c036e4f89
(7) 0x7aaa5ff5f64970268183e06f56110a30571f753f
(8) 0x7c3b0b8193fff996b01bc77154fb91f3b361a646
(9) 0x2a5c667ba684bf0b7db61d7dec17751a6f6e03f8

Private Keys
==================
(0) 237fda9ce07f11cff672e58f633b514575613e96cb2653ea9d08ca69e882f042
(1) 50ea263a896e3b4ec3337ede58131e71dfdd71e7afa879b0957f3a3443b14b85
(2) dd251d5192bb0a73c1a9896f394099d646f6c8e2e96b88e7288f4e83d70a7392
(3) 3409d7a67896bbf2e6a8c9e414bb75284cf87fc66b9bb0e222cb8648a494709e
(4) e1229c76e7c1e5aad682c8b27da5d1a67171c7b3ad560fdb52cb1ae3855cc31d
(5) b627f6f491e8ed270733cd2483287cfa092d0b56b15de0f838ffc06257416c5b
(6) b25209ef82d3a44205d72b418b86476ac710afa1dcc582525954bc31db6c6832
(7) 20b540aa45c394306d38c1d37458d9c46d404311f822fc149fcd523c2e34d84d
(8) 838e1a99cca13ced482d9af2dbba6911a4ee3b676baa395a1462fd29fec070a5
(9) f586c3fe792d63b7459e399454d1798c21eb191db861aff67d9ec771cc22f83a

HD Wallet
==================
Mnemonic:      virus bamboo couch ankle afraid glide family attend empty bulb stadium cricket
Base HD Path:  m/44'/60'/0'/0/{account_index}

Listening on localhost:8545

第四步,编译部署合约

编辑配置文件truffle.js,保证配置文件中指定网络和你运行的网络一致。

这里要注意的是:Ganache默认运行在7545端口,Ethereumjs-testrpc 默认运行在8545端口,Truffle Develop 默认运行在9545端口

module.exports = {
    networks: {
        development: {
            host: 'localhost',
            port: '8545',
            network_id: '*' // Match any network id
        }
    }
};

使用truffle compile命令编译,生成build文件夹

zhujiantao@ubuntu:~/MetaCoin$ truffle compile
Compiling ./contracts/ConvertLib.sol...
Compiling ./contracts/MetaCoin.sol...
Compiling ./contracts/Migrations.sol...
Writing artifacts to ./build/contracts

zhujiantao@ubuntu:~/MetaCoin$ tree
.
├── build
│   └── contracts
│       ├── ConvertLib.json
│       ├── MetaCoin.json
│       └── Migrations.json
├── contracts
│   ├── ConvertLib.sol
│   ├── MetaCoin.sol
│   └── Migrations.sol
├── migrations
│   ├── 1_initial_migration.js
│   └── 2_deploy_contracts.js
├── test
│   ├── metacoin.js
│   └── TestMetacoin.sol
├── truffle-config.js
└── truffle.js

5 directories, 12 files

部署合约

zhujiantao@ubuntu:~/MetaCoin$ truffle migrate
Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0xf8e61ddf4663ae812678e0a62324911866b3b38c48d933c50c554a17f56da4f0
  Migrations: 0xb8d96e14501462f922b05d08bd1e461f59e71b77
Saving successful migration to network...
  ... 0xe6806b8ded1054326b5b795828c5306f186e584794732cba9f1fb50bd8e1dad8
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying ConvertLib...
  ... 0xddac202a2dc8dbe32b96867080e64ce6931dd05e3e2a9b1b29ef7b7970615a3b
  ConvertLib: 0xef4d768c8cb7dec157d40e06af71598176b15c5b
  Linking ConvertLib to MetaCoin
  Deploying MetaCoin...
  ... 0x4c2d8dcc99ffb631208a5568140e194515b03f38b9019d9c833770cfb3c262b6
  MetaCoin: 0xbc2104e9f774ea0a1d5f708401ff71ba451670b3
Saving successful migration to network...
  ... 0xabacbc322a9af2d359a49cdbc0e5a4ab55914956f95b4bc177b1789621bea3c9
Saving artifacts...

第五步,测试合约

zhujiantao@ubuntu:~/MetaCoin$ truffle test
Using network 'development'.

Compiling ./contracts/ConvertLib.sol...
Compiling ./contracts/MetaCoin.sol...
Compiling ./test/TestMetacoin.sol...
Compiling truffle/Assert.sol...
Compiling truffle/DeployedAddresses.sol...


  TestMetacoin
    ✓ testInitialBalanceUsingDeployedContract (88ms)
    ✓ testInitialBalanceWithNewMetaCoin (94ms)

  Contract: MetaCoin
    ✓ should put 10000 MetaCoin in the first account
    ✓ should call a function that depends on a linked library (50ms)
    ✓ should send coin correctly (128ms)


  5 passing (1s)

可以看到测试结果和用时等相关信息。

那么今天就先到这里啦,接下来,分析metacoin和webpack代码,学习怎样编写合约、迁移脚本和测试脚本,七夕快乐,嗒嗒嗒。

推荐阅读更多精彩内容