以太坊Dapp开发通过truffle部署合约

以太坊Dapp开发通过truffle部署合约


Truffle是一个非常流行 DApp 开发框架,他可以帮我们处理掉大量无关紧要的小事情,让我们可以迅速开始写代码-编译-部署-测试-打包DApp这个流程

下面来演示一下truffle是如何部署一个合约的
前提工作:已安装truffle,granche-cli以及node等需要的依赖,可以参考我在以太坊Dapp这一分栏内的文章

首先需要将我们的ganache启动

[root@ ~]# ganache-cli
Ganache CLI v6.12.2 (ganache-core: 2.13.2)

Available Accounts
==================
(0) 0x797368b5C8BE44214263EC541268B923d44908a1 (100 ETH)
(1) 0x45Cc4Ca1CC14Fa8B937F891a2BCd8f3Eb89A486C (100 ETH)
(2) 0x35Bfe1333364fa019B47CeccB397f295f00DC95A (100 ETH)
(3) 0x53f7311235321bA38D7c08784Aa23dD4Cb8101E3 (100 ETH)
(4) 0xfeDE6BB3693006bdc8ce52f6C62767549eeD7591 (100 ETH)
(5) 0xA3d922a8542C2cEec2D12503fdD2552b970CE907 (100 ETH)
(6) 0xe5F6D71b98A7dBa783e44BaB2B88e8dBcAbb6B59 (100 ETH)
(7) 0x70E475CbCDA1e6A37cAb3EfbEE688E4AeC5bB147 (100 ETH)
(8) 0x0889602df801e19A26446542F5373A34C0A3470b (100 ETH)
(9) 0xD67dca7F27A471b13C2acA97Bf737A3A3FD44C49 (100 ETH)

Private Keys
==================
(0) 0xf0783482f9e83356f58d5ad46b4a3115ee44c8f6ed07778d802b04f43f2084c4
(1) 0x6cc4874b2eb70b6bf56fb052e7e2b91ed29acd1de2053ddfe3242d050f46b7c4
(2) 0xb74f8518913e8d7e7af911db60f7bf3fc82c0194b44fa471ce4aa75e3fffd1a7
(3) 0x9f219c5d615a00f266cd9a4dae923fd91f789571701ac67fc525d710fa78014b
(4) 0x748a74d9a06f431db0cdea00dce7bb38a780b1acc37e416f4bc18bbdf249ea9e
(5) 0xe5f2f85e947ea8c3d5d319e590a064d6eeac4829e2ba26645e4ef37088b704c9
(6) 0x28cdac10857c510c32c150edbef59a05e9d499825dfe41f00fe72eb5b1fdb3c5
(7) 0x6ebafac7402475609af624fcfd703acf1798a41d69a2ebb8bb199acf2a3d5a97
(8) 0xfaa4c05f1e2ecae4691ec413f1c0a3c992e9702e865f8e22921f89cee85b2f1b
(9) 0x30b91968397ccce46edeb2305d72f0699e6eee22dcd126a2b5b1829d97e5de11

HD Wallet
==================
Mnemonic:      forward demise dial awake immune head during cement document vendor year shuffle
Base HD Path:  m/44'/60'/0'/0/{account_index}

Gas Price
==================
20000000000

Gas Limit
==================
6721975

Call Gas Limit
==================
9007199254740991

Listening on 127.0.0.1:8545

测试我们的truffle是否安装成功

truffle -v

出现以下的内容证明安装成功

[root@]# truffle --version
Truffle v5.1.48 - a development framework for Ethereum

Usage: truffle <command> [options]

Commands:
  build     Execute build pipeline (if configuration present)
  compile   Compile contract source files
  config    Set user-level configuration options
  console   Run a console with contract abstractions and commands available
  create    Helper to create new contracts, migrations and tests
  debug     Interactively debug any transaction on the blockchain
  deploy    (alias for migrate)
  develop   Open a console with a local development blockchain
  exec      Execute a JS module within this Truffle environment
  help      List all commands or provide information about a specific command
  init      Initialize new and empty Ethereum project
  install   Install a package from the Ethereum Package Registry
  migrate   Run migrations to deploy contracts
  networks  Show addresses for deployed contracts on each network
  obtain    Fetch and cache a specified compiler
  opcode    Print the compiled opcodes for a given contract
  publish   Publish a package to the Ethereum Package Registry
  run       Run a third-party command
  test      Run JavaScript and Solidity tests
  unbox     Download a Truffle Box, a pre-built Truffle project
  version   Show version number and exit
  watch     Watch filesystem for changes and rebuild the project automatically

See more at http://trufflesuite.com/docs

在dapp目录下创建一个vote目录,进入到vote目录执行truffle unbox metacoin命令

truffle unbox metacoin

这是一个truffle自带一个工程,可以直接进行安装,安装成功后有以下的内容

[root@ vote]# ls
app  contracts  migrations  test  truffle-config.js

使用truffle compile命令编译合约源文件

truffle compile

这是成功编译出现的结果

[root@ vote]# truffle compile

Compiling your contracts...
===========================
✔ Fetching solc version list from solc-bin. Attempt #1
✔ Downloading compiler. Attempt #1.
> Compiling ./contracts/ConvertLib.sol
> Compiling ./contracts/MetaCoin.sol
> Compiling ./contracts/Migrations.sol
> Artifacts written to /root/dapp/vote/build/contracts
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

编译完成之后我们再进行部署,使用 truffle migrate命令

[root@ vote]# truffle migrate

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.



Starting migrations...
======================
> Network name:    'development'
> Network id:      1638243424148
> Block gas limit: 6721975 (0x6691b7)


1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0x5eb2e706a7ec6abbcb2c69a3a82e7c7ce0708b24ee1c9006d42be404b6ec9c44
   > Blocks: 0            Seconds: 0
   > contract address:    0x33a965d0B2873b984a2Be8C6004f17a728c23536
   > block number:        1
   > block timestamp:     1638243725
   > account:             0x797368b5C8BE44214263EC541268B923d44908a1
   > balance:             99.9967165
   > gas used:            164175 (0x2814f)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.0032835 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:           0.0032835 ETH


2_deploy_contracts.js
=====================

   Deploying 'ConvertLib'
   ----------------------
   > transaction hash:    0x15c51c472a7cd546898680154f8c88c719e19c9863bd43e89f564c1444d19f08
   > Blocks: 0            Seconds: 0
   > contract address:    0xaA82fe2C467ad275865B9c6ebA902aCFe979d47a
   > block number:        3
   > block timestamp:     1638243726
   > account:             0x797368b5C8BE44214263EC541268B923d44908a1
   > balance:             99.99396028
   > gas used:            95470 (0x174ee)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.0019094 ETH


   Linking
   -------
   * Contract: MetaCoin <--> Library: ConvertLib (at address: 0xaA82fe2C467ad275865B9c6ebA902aCFe979d47a)

   Deploying 'MetaCoin'
   --------------------
   > transaction hash:    0x14bc2665723f4aa5de359caf3666b921780f0a9f2841caa8c01dfb47a31b06ca
   > Blocks: 0            Seconds: 0
   > contract address:    0x60c65DABfF427a262CaadCDC53739De8D3d28917
   > block number:        4
   > block timestamp:     1638243727
   > account:             0x797368b5C8BE44214263EC541268B923d44908a1
   > balance:             99.98822922
   > gas used:            286553 (0x45f59)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00573106 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00764046 ETH


Summary
=======
> Total deployments:   3
> Final cost:          0.01092396 ETH

这里我们还需要改动一下truffle-config.js当中的配置文件,使用vim truffle-config.js命令,将 development配置注释解开,并将develop注释,方便我们进行测试。

  networks: {
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.
    //
     development: {
      host: "127.0.0.1",     // Localhost (default: none)
            port: 8545,            // Standard Ethereum port (default: none)
      network_id: "*",       // Any network (default: none)
     },

 //    develop: {
 //     port: 8545
 //  },

接下来进入到vote下面的app目录
执行npm run dev命令,此时这里报错

[root@ app]# npm run dev

> [email protected] dev
> webpack-dev-server

sh: webpack-dev-server: 未找到命令

解决办法:执行npm install webpack-dev-server -g命令进行全局安装

[root@ app]#  npm install webpack-dev-server -g
npm WARN deprecated [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.

added 292 packages, and audited 293 packages in 4m

39 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

接下来再次执行npm run dev命令

[root@ app]# npm run dev

> [email protected] dev
> webpack-dev-server

ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /root/dapp/vote/app/dist
ℹ 「wdm」: Hash: 9f5e63a62c8d71bc82f2
Version: webpack 4.41.2
Time: 2604ms
Built at: 2021/11/30 上午11:59:00
     Asset       Size  Chunks             Chunk Names
index.html  879 bytes          [emitted]  
  index.js   2.43 MiB    main  [emitted]  main
Entrypoint main = index.js
[0] multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js 40 bytes {main} [built]
[../build/contracts/MetaCoin.json] 101 KiB {main} [built]
[./node_modules/ansi-html/index.js] 4.16 KiB {main} [built]
[./node_modules/html-entities/index.js] 231 bytes {main} [built]
[./node_modules/web3/src/index.js] 2.01 KiB {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.89 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js] (webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js] (webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main} [built]
[./node_modules/webpack-dev-server/node_modules/strip-ansi/index.js] (webpack)-dev-server/node_modules/strip-ansi/index.js 161 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./src/index.js] 2.08 KiB {main} [built]
    + 350 hidden modules
ℹ 「wdm」: Compiled successfully.

在浏览器当中输入127.0.0.1:8080就能看到我们这个合约的界面了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43537319/article/details/121632196