使用truffle开发以太坊Dapp

  上一篇我们介绍了使用web3.js与以太坊智能合约交互,其中介绍了合约的编译、部署、执行等操作,但是很明显,如果要开发dapp,仅仅使用web3.js是不够的,开发繁琐,项目不够规范等。
今天我们就来介绍一种更快捷的方式:truffle,使用truffle能帮我们快速的搭建dapp项目,并规范项目结构,甚至truffle还提供了一些入门的dapp,帮助开发者快速上手。
本文主要介绍truffle提供的一个转账应用,如果需要学习更多的dapp,请移步 https://truffleframework.com/...

准备工作:
安装node,npm,这里就不介绍了,私有链仍然使用的是Ganache

> npm install -g truffle

1、新建项目

> mkdir demo && cd demo
> npm init

> truffle unbox webpack

# 如果需要搭建宠物商店,执行这条命令
> truffle unbox pet-shop

执行完之后,完整的项目结构如下:

.
├── app
│   ├── index.html
│   ├── scripts
│   │   └── index.js
│   └── styles
│       └── app.css
├── box-img-lg.png
├── box-img-sm.png
├── build  //智能合约编译后的内容
│   ├── app.js
│   ├── app.js.map
│   ├── contracts
│   │   ├── ConvertLib.json
│   │   ├── MetaCoin.json
│   │   └── Migrations.json
│   └── index.html
├── contracts  //智能合约存放目录
│   ├── ConvertLib.sol
│   ├── MetaCoin.sol
│   └── Migrations.sol
├── migrations  //智能合约部署信息
│   ├── 1_initial_migration.js
│   └── 2_deploy_contracts.js
├── package-lock.json
├── package.json
├── test  //测试文件
│   ├── TestMetacoin.sol
│   └── metacoin.js
├── truffle.js  //truffle配置
└── webpack.config.js

2、编译、部署
需要先启动Ganache,不然部署时连不上

> truffle  migrate


# 编译成功后会显示如下内容
Writing artifacts to ./build/contracts

Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0x1d307f4ba87bba7bfcbd06baf5fa8e2d2e64a8a69a18d8c56e277f36cc1d1677
  Migrations: 0x42b27a0495c97b75e3f5ca6de5f45401320d7169
Saving successful migration to network...
  ... 0xf6d61e8a6840ac9438b6ddd64509f939438fe8eb7fa2f2283e2e9c52a1639857
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying ConvertLib...
  ... 0xb8c26443eda840cbdc5e5a61b11678236b2fea14ffd1f8d9c2434cda9a1ba642
  ConvertLib: 0x8d8f5fc48c5ab607b2eea17403d96c371895347f
  Linking ConvertLib to MetaCoin
  Deploying MetaCoin...
  ... 0xc9a2c12726cdd0a9160d832eed092d1a15b3a25a70dbe8b8cb9a079dedd5a345
  MetaCoin: 0x84db03db9b32f49b054502e86fcfa9552052c10b
Saving successful migration to network...
  ... 0xc8f28755bd1094201014b13fb1f7773315e3b6f1f46a9e8e60b0567597888c52
Saving artifacts...

如果报这个错No network specified. Cannot determine current network.,找到truffle.js,把networks中的名称修改为development即可,因为默认连的就是development

module.exports = {
  networks: {
    development: {
      host: '127.0.0.1',
      port: 7545,
      network_id: '*' // Match any network id
    }
  }
}

如果报这个错误Attempting to run transaction which calls a contract function,删除build目录,重新执行truffle migrate命令
这个错误是因为编译后又修改了truffle.js中的development,地址不对导致的

3、启动项目

> npm run dev

启动成功后,打开chrome浏览器http://localhost:8080/,会弹出一个错误,或者在You have META这个位置没显示余额,因为在app/avascripts/app.js文件中连的端口是9545,修改成7545,刷新页面就可以看到You have 10000 META
需要提醒的是:不需要装MetaMask,不需要装MetaMask,不需要装MetaMask!

如果你装了MetaMask,打开这个页面会显示You have 0 META,这是因为MetaMask提供了web3对象,所以根本不会连本机的http://localhost:8080/
具体代码可以查看app/avascripts/app.js,拉到文件最下方可以看到如下内容

window.addEventListener('load', function () {
  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    console.warn(
      'Using web3 detected from external source.' +
      ' If you find that your accounts don\'t appear or you have 0 MetaCoin,' +
      ' ensure you\'ve configured that source properly.' +
      ' If using MetaMask, see the following link.' +
      ' Feel free to delete this warning. :)' +
      ' http://truffleframework.com/tutorials/truffle-and-metamask'
    )
    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider)
  } else {
    console.warn(
      'No web3 detected. Falling back to http://127.0.0.1:9545.' +
      ' You should remove this fallback when you deploy live, as it\'s inherently insecure.' +
      ' Consider switching to Metamask for development.' +
      ' More info here: http://truffleframework.com/tutorials/truffle-and-metamask'
    )
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:9545'))
  }

  App.start()
})

所以如果你装了Metamask,就需要修改下文件,把web3对象是否存在的判断注释掉,并修改端口为7545,只保留window.web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545')),具体修改如下

window.addEventListener('load', function () {
  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  // if (typeof web3 !== 'undefined') {
  //   console.warn(
  //     'Using web3 detected from external source.' +
  //     ' If you find that your accounts don\'t appear or you have 0 MetaCoin,' +
  //     ' ensure you\'ve configured that source properly.' +
  //     ' If using MetaMask, see the following link.' +
  //     ' Feel free to delete this warning. :)' +
  //     ' http://truffleframework.com/tutorials/truffle-and-metamask'
  //   )
  //   // Use Mist/MetaMask's provider
  //   window.web3 = new Web3(web3.currentProvider)
  // } else {
  //   console.warn(
  //     'No web3 detected. Falling back to http://127.0.0.1:9545.' +
  //     ' You should remove this fallback when you deploy live, as it\'s inherently insecure.' +
  //     ' Consider switching to Metamask for development.' +
  //     ' More info here: http://truffleframework.com/tutorials/truffle-and-metamask'
  //   )
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545'))
  // }

  App.start()
})



欢迎订阅「K叔区块链」 - 专注于区块链技术学习

博客地址: http://www.jouypub.com
简书主页: https://www.jianshu.com/u/756c9c8ae984
segmentfault主页: https://segmentfault.com/blog/jouypub
腾讯云主页: https://cloud.tencent.com/developer/column/72548
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值