想知道更多关于区块链技术知识,请百度【链客区块链技术问答社区】
链客,有问必答!!
Truffle框架
Truffle框架安装:npm install -g truffle
使用truffle –version 看是否安装成功
新建目录后,可以使用truffle init来创建项目
使用truffle develop 进入本地搭建好的私有区块链,有创建好的10个默认的账户
使用web3.eth.account[1]来查看第二个账户
使用web3.eth.getBalance(“账号地址”) 查看账户余额
转账的数量:account = web3.toWei(30,’ether’);将30个以太币转成位,10的18次方 位 =1以太币
使用转账交易
Web3.eth.sendTransaction({from:"",to:"",value:account})
进入truffle develop之后,可以使用compile进行合约的编译
合约部署:
var helloWorld 定义变量
合约名.deployed().then((instance)=>{helloWorld = instance}) migrate; var contract; SimpleStorage.deployed().then((i)=>{contract=i;});
合约的调用 helloWorld.test()进行合约的调用
修改合约内容后,重新编译部署的方法:rm -rf build/ 将编译的内容清空
进行项目开发时,可以新建一个文件夹,使用truffle unbox react来创建项目,集成前端的代码
使用npm run start命令来运行项目
Solidity智能合约编程语言
变量的类型有很多,暂时接触到的:uint,bool,address,byte,string,day,结构体
结构体struct 类似于java中的类
主要的就是function, 函数名,参数,权限程度,返回值等
function winningProposal() public constant returns (uint8 _winningProposal) {
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
}
三个关键字 constant,pure,view
Constant 关键字:指如果函数返回值是类变量,就用constantpure关键字:如果函数返回值是字符串或数值与类变量无关,就用pure
view关键字:如果既没有类变量又不包含字符串等,就用view
mapping类似于java中的hashmap,放在合约中,可以用来保存数据
mapping(address => Voter) voters; address是钱包地址 Voter是一个结构体
如果函数中使用了结构体,则这个函数一定只能是internal,不能使public,即无法在外部访问
类型直接转换比较困难,下面代码是uint转string的
function uintToString(uint v) pure public returns (string) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i] = byte(48 + remainder);
i++;
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i-j-1];
}
return string(s);
}