相关工具
Solidity:https://github.com/ethereum/solidity
Web3.js:https://github.com/ethereum/web3.js
Geth:https://github.com/ethereum/go-ethereum
Mist:https://github.com/ethereum/mist
Remix:https://remix.ethereum.org/
Solidity是以太坊开发智能合约的高级语言,采用面向对象的开发方式,有一套自己的语法体系,是图灵完备的。
Web3.js是基于javascript的调用智能合约的类库。之前还可以编译和部署智能合约,不过现在已经废除了,暂时还没有找到更好的替代方式,本文是采用mist客户端进行编译和部署的,然后再通过web3.js进行调用。
Geth是以太坊客户端,可以用来挖矿,也可以搭建私有的以太坊环境。
Mist是以太坊的钱包工具,可以进行转账交易和智能合约的开发。
Remix是Solidity语言的基于Web的IDE,代码编写以及错误调试非常方便,一般在Remix调试没有问题之后,在通过Mist进行发布。另外,在没有搭建私链的环境是,可以结合chrom的浏览器扩展metamask,在测试链上进行开发。
私链环境搭建
Geth搭建以太坊私链环境:http://blog.youkuaiyun.com/koastal/article/details/78737543
搭建以太坊私有链多节点环境:http://blog.youkuaiyun.com/koastal/article/details/78749211
智能合约
- 利用
struct
存储用户的属性,这里只写了姓名和年龄。 - 利用
mapping
存储uid
与struct
的映射关系。 - 利用
array
存储uid
,也就是作为“数据库的索引”。 - 插入操作成功之后,用户获得一个自增的
uid
,也就是IdList
中的最大值+1的结果。 - 更新和删除都是通过
uid
找到该用户记录,然后操作。 - 插入、更新和删除都属于写操作,需要调用者支付费用(Gas)。
- 写操作都定义了相关的事件,在操作成功之后调用事件。
pragma solidity ^0.4.6;
contract UserCurd {
struct UserStruct {
string name;
uint age;
}
mapping(uint => UserStruct) private UserStructs;
uint[] private IdList;
event InsertEvent(uint uid,string name,uint age);
event UpdateEvent(uint uid,string name,uint age);
event DeleteEvent(uint uid);
//插入操作
function insertUser(string name,uint age) public returns(uint uid){
uint length =