如何部署TRUFFLE智能合约到以太坊主网(以宠物商店为例)

  • 辉哥
  • 更新于 2018-09-07 12:07
  • 阅读 4039

如何部署TRUFFLE智能合约到以太坊主网(以宠物商店为例)

1. 摘要

通过 技术小白如何开发一个DAPP区块链应用(以宠物商店为例) 学习,大家掌握了一个DAPP的编程和以太坊私有测试环境调试,本文做进一步的技术深入学习。 【本文目标】 (1)采用INFURA配置的方式把智能合约部署到ROPSTEN测试网络; (2)采用INFURA配置的方式把智能合约部署到以太坊主网络; (3)了解采用.env配置的方式把助记词保存到本地防止泄露;

【前提条件】 本文假设你已完成 《第六课 技术小白如何开发一个DAPP区块链应用(以宠物商店为例)》 的学习,在UBUTU环境编译成功智能合约,通过浏览器运行宠物商店程序并点击领养宠物成功。

2. 操作内容

2.1 注册infura获取API-KEY

地址https://infura.io

辉哥注册后,获得API KEY:8ce5ebd357144bef8dceae3de1915e29

2.2 增加配置文件.env

Dotenv是一个零依赖模块,用于从".env"文件中导入环境变量到 process.env 。对DAPP来说,这样就可以不用上传钱包助记词等核心机密到GITHUB,便于资产安全。

如何获取META MASK的助记词 META MASK的助记词是针对原创账户的。在TRUFFLE框架下默认使用第一个创建的ACCOUNT1进行部署操作。

2.获取seed KEY

如何获取imToken钱包的助记词 imToken钱包的助记词一般在你创建钱包的时候已经备份好了,之后会被删除。钱包此时只能导出私钥或者keystore了。

2.3 增加配置文件truffle.js的ROSPTEN和MAINNET环境配置

修改配置文件配置文件truffle.js,增加ROSPTEN和MAINNET环境配置内容。

/*读取.env环境配置的文件变量定义*/
const dotenv = require('dotenv');
const result = dotenv.config();
if (result.error) {
  throw result.error;
}
console.log(result.parsed);

var NonceTrackerSubprovider = require("web3-provider-engine/subproviders/nonce-tracker");
var HDWalletProvider = require("truffle-hdwallet-provider");

/*访问https://infura.io/注册后获取的api-key*/
var infura_apikey = "8ce5ebd357144bef8dceae3de1915e29";

/*读取.env文件配置的助记词*/
var mnemonic_ropsten = process.env.mnemonic_ropsten;
var mnemonic_mainnet = process.env.mnemonic_mainnet;

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*", // Match any network id
      gas: 4500000
    },
    local: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*", // Match any network id
      //gas: 4300000
    },
    ropsten: {
      provider: new HDWalletProvider(mnemonic_ropsten, "https://ropsten.infura.io/"+infura_apikey),
      network_id: 3,
      gas: 3012388,
      gasPrice: 30000000000
    },
    mainnet: {
      provider: function () {
        var wallet = new HDWalletProvider(mnemonic_mainnet, "https://mainnet.infura.io/Np7IGWoN2UOb0tgRWx55");
        var nonceTracker = new NonceTrackerSubprovider();
        wallet.engine._providers.unshift(nonceTracker);
        nonceTracker.setEngine(wallet.engine);
        return wallet;
      },
      gas: 6000000,
      network_id: 1,
      gasPrice: 10 * 1000000000
    }
  }
};

2.4 上传代码

辉哥假设你已经创建好了宠物商店的代码,完成了第六课的实践。 没有的话,可加入辉哥知识星球,从中下载本案例代码工程,也可加专门微信群交流技术问题。

把DAPP工程上传到UBUNTU的ETH环境。记得把WINDOWS下的main.env文件改为.env文件,便于运行时环境读取。

3.修改配置文件.png

2.5 安装 truffle-hdwallet-provider

Infura组织是MetaMask背后的以太坊供应商。Infura提供了一个托管的以太坊节点集群,可以将你开发的以太坊智能合约部署到infura提供的节点上,而无需搭建自己的以太坊节点。 Infura不保存你的私钥,Infura可以通过使用HDWalletProvider来签署交易。 该服务可以处理事务签名以及与以太坊网络的连接。 在宠物商店根目录下运行命令:

npm install truffle-hdwallet-provider

成功输出参考如下:

duncanwang@ubuntu:~/work/dapp-guide-pet-shop$ npm install truffle-hdwallet-provider

> scrypt@6.0.3 preinstall /home/duncanwang/work/dapp-guide-pet-shop/node_modules/scrypt
> node node-scrypt-preinstall.js
...
npm WARN truffle-hdwallet-provider@0.0.6 requires a peer of truffle@4.x but none is installed. You must install peer dependencies yourself.
npm WARN pet-shop@1.0.0 No description
npm WARN pet-shop@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"ia32"})

+ truffle-hdwallet-provider@0.0.6
added 566 packages from 381 contributors in 188.892s

辉哥在安装truffle-hdwallet-provider时遇到了巨大的各种坑。刚开始怀疑是被墙的问题,尝试过各种手段,最终发现是没有安装C/C++编译器的欢迎,参考本文章节"3,常见问题和解决方法"解决。

2.6 安装 dotenv

npm install  dotenv 

安装成功的输入如下:

duncanwang@ubuntu:~/work/dapp-guide-pet-shop$ npm install  dotenv
npm WARN truffle-hdwallet-provider@0.0.6 requires a peer of truffle@4.x but none is installed. You must install peer dependencies yourself.
npm WARN pet-shop@1.0.0 No description
npm WARN pet-shop@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"ia32"})

+ dotenv@6.0.0
added 1 package from 1 contributor in 15.671s

如果安装失败,请参考本文章节"3,常见问题和解决方法"解决。

2.7 把智能合约部署到ROPSTEN测试网络

(1), 在宠物商店根目录下运行命令:

truffle migrate --network ropsten  --reset --compile-all

重新编译成功后会部署到ropsetn测试环境。成功输出内容参考:

duncanwang@ubuntu:~/work/dapp-guide-pet-shop$ truffle migrate --network ROPSTEN  --reset --compile-all
...
Writing artifacts to ./build/contracts

Using network 'ropsten'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0xe9a11fa0cb23c1c87068c97719b1400285bb56c1d6592415104d794657c23e36
  Migrations: 0x4c6475632bd8101727d0b4bcce8f9fbc5eef43f0
Saving successful migration to network...
  ... 0xe04d70b45866abfae901396d76d8509c39c747dee203e979b60ec324d2bf3179
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying Adoption...
  ... 0x824322568f00e51b7b707d212da9f9c1a2f56a1bdb9a2734ea5ce6c544f7bb2a
  Adoption: 0xa65fc2fbbfb0c74a984144df3174853fe74e2179
Saving successful migration to network...
  ... 0xe209420af44a028590408aff402829e746ef9abb109db808b75ff8aa1ec28ac3
Saving artifacts...

提取合约地址,点击可以查看部署成功的合约链接:

(2) 本次因为不需要采用本地环境,所以不需要启动ganache-cli环境,但是需要在独立环境窗口安装,运行lite-server环境,以便访问宠物商店网页。 输入命令:

npm install lite-server --save-dev
npm run dev

安装成功输出参考:

duncanwang@ubuntu:~/work/dapp-guide-pet-shop$ npm install lite-server --save-dev
npm WARN truffle-hdwallet-provider@0.0.6 requires a peer of truffle@4.x but none is installed. You must install peer dependencies yourself.
npm WARN pet-shop@1.0.0 No description
npm WARN pet-shop@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"ia32"})

+ lite-server@2.4.0
added 19 packages from 24 contributors, removed 19 packages and updated 40 packages in 41.6s

lite-server运行成功参考:

> pet-shop@1.0.0 dev /home/duncanwang/work/dapp-guide-pet-shop
> lite-server

** browser-sync config **
{ injectChanges: false,
  files: [ './**/*.{html,htm,css,js}' ],
  watchOptions: { ignored: 'node_modules' },
  server: 
   { baseDir: [ './src', './build/contracts' ],
     middleware: [ [Function], [Function] ] } }
[Browsersync] Access URLs:
 --------------------------------------
       Local: http://localhost:3000
    External: http://192.168.2.209:3000
 --------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.2.209:3001
 --------------------------------------
[Browsersync] Serving files from: ./src
[Browsersync] Serving files from: ./build/contracts
[Browsersync] Watching files...

(3) 网页访问宠物商店 辉哥服务器的地址页面地址:http://192.168.2.209:3000

4.主页

(4) 领养宠物狗狗 点击领养的流程同第六课私有以太坊环境的操作。

5.点击领养.png

点击可查看辉哥本次操作成功的交易记录: https://ropsten.etherscan.io/tx/0x26c8458ff0fadfb74f214d421d894198594ea638a2176630cab136987cf5ef4b

2.8 把智能合约部署到以太坊主网络

记得把有以太坊余额的助记词配置到.env文件。 运行命令:

truffle migrate --network mainnet  --reset --compile-all

运行成功结果参考:

duncanwang@ubuntu:~/work/dapp-guide-pet-shop$truffle migrate --network mainnet --reset --compile-all
...
Writing artifacts to ./build/contracts

Using network 'mainnet'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0xa31fa855a85808c974f49d894b2116d6bdd916c52118026bb3ab02fbcbe765c9
  Migrations: 0x71636b5d2ee99a251b511226e17a27d79d73276f
Saving successful migration to network...
  ... 0xb36f92716e38e28dcb0c9e4f8fa13e54a1ab0ddd81a8ac70c8384aa680a5cb10
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying Adoption...
  ... 0x047ef9057c76aac9929ff2a2d72426170b12bd513452a05281b14dbd7414a37f
  Adoption: 0xe2202412f3a6c8ce4fedd1bcad5890444416a524
Saving successful migration to network...
  ... 0x709859af998907ee1b17815f621430dc4cfdc663a5f3f4ad78517c8675c15016
Saving artifacts...

点击可查看辉哥本次部署合同的合约地址链接:

运营宠物商店网址也可以完成相关的操作。 http://192.168.2.209:3000/

辉哥最终cancel了本次交易,就不花这蛋疼的钱了。

1,主网后交易.png

3,常见问题和解决方法

3.1 安装truffle-hdwallet-provider失败

【输出描述】

Error: Error: Command failed: ./configure
configure: error: in `/home/duncanwang/work/cet-token/node_modules/scrypt/scrypt/scrypt-1.2.0':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details
...

【解决方法】 针对这个问题的解决,辉哥走过较多的弯路,包括VPN,安装GCC"npm install -g gcc", "npm rebuild"都没有解决。最终通过运行命令解决了。

sudo apt-get install build-essential

【解决方法2】 辉哥在CentOS6.5上安装truffle-hdwallet-provider时又遇到类似问题。采用CentOS的安装命令 yum groupinstall "Development Tools" yum install -y gcc g++ kernel-devel 安装成功后编译truffle-hdwallet-provider时还是失败。 查看g++的版本,发现是V4.4.7的,这个至少需要V4.7才能成功。

#g++ --version
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

最后参考 《CentOS升级gcc4.4.7到gcc4.8.5》 文档,花了1个多小时完成g++的版本升级后,安装truffle-hdwallet-provider才成功。

3.2 部署到主网不成功

【输出描述】

Running migration: 1_initial_migration.js
  Deploying Migrations...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
insufficient funds for gas * price + value

【解决方法】 (1)辉哥忘记在.env中配置mnemonic_mainnet的助记词,提示也是这个。 (2)后来辉哥使用METAMASK导出的助记词配置给mnemonic_mainnet,也往METAMASK导入了有足够主网ETH的账号,还是提示错误。后来确认导入账号的助记词不能从METAMASK导出。获取正确的助记词就解决了。

3.3 安装TRUFFEL5.0版本后,部署到ROPSTEN网络失败

【输出描述】

duncanwang@ubuntu:~/work/PuzzleBID$ truffle migrate --network ropsten  --reset
...
Error: Cannot find module 'web3-provider-engine/subproviders/nonce-tracker'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)

【解决方法】 安装这2步之后,部署到ROPSTEN就成功了。

duncanwang@ubuntu:~/work/PuzzleBID$ sudo npm install  web3-provider-engine

duncanwang@ubuntu:~/work/PuzzleBID$ sudo node-gyp rebuild

4, 参考

(1) 【区块链】部署智能合约到以太坊主网(truffle+infura) (2) dotenv介绍

点赞 0
收藏 0
分享

0 条评论

请先 登录 后评论
辉哥
辉哥
0x5bAe...0BE7
HiBlock技术社区上海合伙人,区块链落地产业应用布道者