写很多文章,被很多人转载,发现很多人在学习的时候遇到很多的问题,其实我学习的时候也遇到过。下面开始编写真实的智能合约,并使用web3进行调研,实现任何上链的追溯。
pragma solidity ^0.4.17;
contract Enjoy{
//发起者
address issuer;
//姓名
string name;
// 价格
uint price;
uint number = 1;
mapping (address => uint) balances;
//合约发起人
address public creator;
event Issue(address account, uint amount);
event Transfer(address from, address to, uint amount);
//发送订单保存
struct Attribute {
address owner; // 发单人
string name; // 类型的名字
string date; // 接单日期
string desc; // 描述信息
}
//使用数组保存数据
Attribute[] public attribute;
//合约订单保存
struct Orderes{
address owner;//发单人
address order;//接单人
uint maney;//金额
string date;//日期
string desc;//其他
}
//使用数组保存数据
Orderes[] public orderes;
constructor() public{
creator = msg.sender;
}
//对自己发行货币
function issue(address account, uint amount) public {
if (msg.sender != issuer) {
revert();
}
balances[account] += amount;
}
//代币转账
function transfer(address to, uint amount) public {
if (balances[msg.sender] < amount) revert();
balances[msg.sender] -= amount;
balances[to] += amount;
emit Transfer(msg.sender, to, amount);
}
//查询余额
function getBalance(address account) public constant returns (uint) {
return balances[account];
}
//添加一条数据
function add(address _owner,string _name, string _date,string _desc) public returns(bool) {
if(msg.sender != creator) {
revert();
}
attribute.push(Attribute({
owner: _owner,
name: _name,
date: _date,
desc: _desc // 当前时间戳
}));
return true;
}
function addTrs(address _owner,address _order, uint _maney,string _date,string _desc) public returns(bool) {
if(msg.sender != creator) {
revert();
}
orderes.push(Orderes({
owner: _owner,
order:_order,
maney:_maney,
date: _date,
desc: _desc
}));
return true;
}
}
上面是完整的编写solidity代码,都有解释,我就不多说上面的了,下面我们编写web3.js连接代码:
var
web3
=
require
(
"web3"
);
var
web3
=
new
web3
();
var
web3Admin
=
require
(
"web3admin"
);
web3Admin
.
extend
(
web3
);
//扩展web3模块
web3
.setProvider(
new
web3
.providers.
HttpProvider
(
"http://localhost:8545"
));
var abi =..........省略(太多了写不下哦);
var
aAddress
=
"0x4456bfe80dA05EC414bC0d673AFF73f4E227E826"
;
var
a
=
web3
.eth.
contract
(
abi
).
at
(
aAddress
);
web3
.personal.unlockAccount(
web3
.eth.accounts[
0
],
"long3737257"
,
15000
);
//放开指定的账号
web3
.eth.
defaultAccount
=
web3
.eth.accounts[
0
];
//上链数据
var
sayes
=
a
.
add
.
sendTransaction
(
web3
.eth.accounts[
0
],
"this is file hash"
,
"this is the title"
,
"abc"
,{
from
:
web3
.eth.accounts[
0
],
gas
:
4700000
});
console
.
log
(
sayes
);
//打印上链数据到js中
var
abs
=
a
.
attribute
(
0
);
console
.
log
(
abs
);
输出的数据是:
[ '0x58525c150ee0832bf71395068a5806c76542fdd6',
'this is file hash',
'this is the title',
'abc' ]
好了,完整编写,你可以到自己的Dapp上实现哦。感谢,如果有问题请联系[email protected]