(solidity)HelloWorld智能合约编写
新建智能合约项目
1.mkdir 新建一个项目文件夹并进入文件夹
$ mkdir lession2
$ cd lession2
2. 初始化智能合约项目框架
$ truffle init

3.使用atom打开智能合约项目
$ atom ./
图1是早期智能合约项目目录结构,图2是当前目录接口

目录结构简单说明如下:
app/ - 你的应用文件运行的默认目录。这里面包括推荐的javascript文件和css样式文件目录,但你可以完全决定如何使用这些目录。
contract/ - Truffle默认的合约文件存放地址。
migrations/ - 存放发布脚本文件
test/ - 用来测试应用和合约的测试文件
truffle.js - Truffle的配置文件
上图引自 TryBlockchain 链接:https://www.jianshu.com/p/8794afea1996

目录结构简单说明如下:
app/ - 你的应用文件运行的默认目录。这里面包括推荐的javascript文件和css样式文件目录,但你可以完全决定如何使用这些目录。
contract/ - Truffle默认的合约文件存放地址。
migrations/ - 存放发布脚本文件
test/ - 用来测试应用和合约的测试文件
truffle.js - Truffle的配置文件
相关详细说明,详见:初始化Truffle
4.创建我们自己的合约
在./contract 目录下创建我们自己的HelloWorld.sol合约,切记不要删除migrations.sol文件

5.编写HelloWorld.sol智能合约
pragma solidity ^0.4;contract HelloWorld {
function sayHelloWorld() internal pure returns (string) {
return ("hello world");
}
}

在这里说明一下,以前版本是可以不指定类型internal pure(外部不可调用),public pure(外部可调用)(如不指定表示函数为可变行,需要限制)
error: Function state mutability can be restricted to pure
6.编译
$truffle compile
编译前先检查当前终端所在目录是否是智能合约项目根目录,可使用:
$pwd

编译完成,看项目目录结构变化:

编译成功后,会在 HelloWorld 文件夹下面的 build/contracts 文件夹下面看见 HelloWorld.json文件。

7.部署
truffle 框架中提供了方便部署合约的脚本。打开 migrations/1_initial_migration.js 文件(脚
本使用 Javascript 编写),将内容修改如下:
var HelloWorld = artifacts.require("HelloWorld");module.exports = function(deployer) {
deployer.deploy(HelloWorld);
};
$ truffle migrate
如果出现一下错误日志:
error: No network specified. Cannot determine current network.

需要在truffle.js配置
module.exports = { // See // to customize your Truffle configuration!
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
}
}
};

port端口号是启动服务时产生的端口号见下图:

执行部署后合约就已经部署到 testrpc 中。切换到 testrpc 窗口,可以看到 testrpc 有反应了

这里的gas指的就是本次消耗的矿工费
8.与合约互动
truffle 提供命令行工具,执行 truffle console 命令后,可用 Javascript 来和刚刚部署的合约
互动。
$ truffle console
$ HelloWorld.deployed().then(instance => contract = instance)
truffle console 中预载了 truffle-contract 函数库,以方便操作部署到区块链上的合约。
这边使用 HelloWorld.deployed().then 语句来取得 HelloWorld 合约的 Instance (实例),并存
到 contract 变量中,以方便后续的调用。

然后可以调用我们HelloWorld.sol写的方法sayHelloWorld
$ contract.sayHelloWorld()
$ contract.sayHelloWorld.call()
使用call()只读方法,读取数据不需要消耗gas,因此如果遇到的操作需要向区块链写入
数据,我们就不能用 call 语句了。

9.编写一个传参方法saveName

$ truffle compile
$ truffle migrate --reset
另一点需要注意的,是这次如果还是用 truffle migrate 命令,我们会得到如下信息:
$ truffle migrate
Using network 'development'.
Network up to date.
Truffle 会告诉你现在网络上的合约都已是最新的,但事实上刚刚程序中新增的方法并没有更新到内存块链上。要更新内存块链上已部署的程序,需要改写 migrations 中的脚本,但现在还不到介绍 migration 的时候。还好我们开发用的内存块链是怎么修改都没关系的 testrpc ,可以使用truffle migrate --reset 命令直接重新在 testrpc 上部署一次。

Lession1 Demo下载地址:https://github.com/zys563488512/solidity.git
Truffle - 以太坊Solidity编程语言开发框架:http://truffle.tryblockchain.org/truffle-migration-移植合约.html
Solidity 官方文档中文版:http://wiki.jikexueyuan.com/project/solidity-zh/units-globally-available-variables.html
Solidity 官方文档英文版:http://solidity.readthedocs.io/en/latest/index.html