【区块链】Truffle 安装和使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/loy_184548/article/details/77984366

Truffle开发入门


一、安装truffle 和 testrpc

npm install -g truffle

pip install eth-testrpc

安装过程中,会遇到很多问题,例如版本太旧。

可以参考:here

二、使用

1. 新建

mkdir hello    //新建文件夹
cd hello       //进入该文件夹
truffle init   //默认会生成一个MetaCoin的demo,可以从这个demo中学习truffle的架构

2. 编译

truffle compile

3. 部署

先启动 testrpc

testrpc
truffle migrate

如果这里遇到错误:No network specified. Cannot determine current network.

解决方案:修改truffle.js文件

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,    // 区块链服务端口号
      network_id: "*"
    }
  }
};

启动服务

truffle serve

启动项目后可以在浏览器访问 http://localhost:8080/

如果是3.x版本的,实际上你会发现,显示的是Cannot GET /

解决方法:

truffle init  ====>  truffle init webpack

truffle serve ====>  npm run dev

就可以成功显示界面啦。

这里写图片描述

参考博客:here

4. 命令行调用

实际上跟geth的命令行调用操作差不多。

可以参考之前的一篇博客关于geth命令行的操作:here

需要注意的是:

    例如:eth.accounts ==> web3.eth.accounts (修改:在前面加web3)

1、进入 console

truffle console

2、实例化合约

contract = MetaCoin.at(MetaCoin.address)

3、 调用

a. call

使用这个方法调用合约只会在本地上运行; 
===>如果你只想得知运算的结果,那么使用该方法

b. sendTransaction

使用这个方法调用合约将会使调用的结果成为全局共识的一部分
===>如果想要改变合约的状态,那么就使用该方法

例如:用户缴纳押金

 function Deposit() payable returns (bool success)
 {
     users[msg.sender].depositValue = msg.value;
     return true;
 }

//调用
contract.Deposit.sendTransaction({from: user1, value: web3.toWei(.05, 'ether')})

猜你喜欢

转载自blog.csdn.net/loy_184548/article/details/77984366
今日推荐