【Truffle系列第2篇】3分钟快速玩转truffle框架

这篇文章将一步步带领你如何一步步创建一个truffle项目,以及如何将智能合约部署到区块链网络。

你将了解到

  1. 建立专案
  2. 项目结构
  3. 测试
  4. 编译
  5. 使用truffle develop进行迁移
  6. 替代方案:使用Ganache进行迁移
  7. 与合约交互

一、建立专案

你如果想使用truffle的相关命令,那么你得先建立一个truffle项目,使用truffle建立项目时,我们可以使用Truffle Boxes,这里面有很多现成的项目模板,我们可以基于这些模板来进行拓展开发,在本篇文章中,我们首先使用Metacoin 框架搭建项目,这个框架可以创建账户之间的令牌转移。

  1. 为您的Truffle项目创建一个新目录:
mkdir MetaCoin
cd MetaCoin
  1. 下载MetaCoin框架
(base) localhost:MetaCoin liyuechun$ truffle unbox metacoin

Starting unbox...
=================

 Preparing to download box
 Downloading
 cleaning up temporary files
 Setting up box

Unbox successful, sweet!

Commands:

  Compile contracts: truffle compile
  Migrate contracts: truffle migrate
  Test contracts:    truffle test

(base) localhost:MetaCoin liyuechun$ 

备注:您可以使用truffle unbox命令下载其他任何truffle项目,如果你想下载不带智能合约源码的项目模板,可以通过truffle init进行创建。

完成此操作后,您现在将拥有一个包含以下项目的项目结构:

  • contracts/:Solidity 合约目录
  • migrations/:可编写脚本的部署文件的目录
  • test/:用于测试您的应用程序和合约的测试文件目录
  • truffle.js: Solidity 配置文件

【Truffle系列第2篇】3分钟快速玩转truffle框架

二、项目结构

注意:这篇教程只是一个快速入门,因此我们在这里不再赘述。

  1. contracts/MetaCoin.sol:这是一个用Solidity编写的可创建MetaCoin令牌的智能合约,打开文件,不难看出本文件同时引用了同一目录中的另一个Solidity文件contracts/ConvertLib.sol

  2. contracts/Migrations.sol:这是一个单独的Solidity文件,用于管理和更新已部署智能合约的状态。该文件随每个Truffle项目一起提供,通常不进行编辑。

  3. migrations/1_initial_migration.js:该文件是Migrations迁移(部署)的合约脚本。

  4. migrations/2_deploy_contracts.js:。该文件是MetaCoin迁移(部署)的合约脚本。(迁移脚本按顺序运行,因此以开头的文件2将在开头1的文件后运行。)

  5. test/TestMetacoin.sol:这是用Solidity编写的测试文件,可确保您的合约按预期工作。

  6. test/metacoin.js:这是一个用JavaScript编写的测试文件,其执行与上述Solidity测试类似的功能。

  7. truffle-config.js:这是Truffle配置文件,用于设置网络信息和其他与项目相关的设置。该文件为空,但这没关系,因为我们将使用内置的一些默认的Truffle命令。

三、测试

  1. 在终端运行Solidity测试文件
(base) localhost:MetaCoin liyuechun$ pwd
/Users/liyuechun/Desktop/demo/MetaCoin
(base) localhost:MetaCoin liyuechun$ ls
LICENSE         migrations      truffle-config.js
contracts       test
(base) localhost:MetaCoin liyuechun$ truffle test ./test/TestMetaCoin.sol

Compiling your contracts...
===========================
> Compiling ./contracts/ConvertLib.sol
> Compiling ./contracts/MetaCoin.sol
> Compiling ./contracts/Migrations.sol
> Compiling ./test/TestMetaCoin.sol
> Artifacts written to /var/folders/cg/gbffc3nx2033d74hrgmjkqsc0000gn/T/test-2020512-16360-1yd5nvd.vhpi
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

  TestMetaCoin
     testInitialBalanceUsingDeployedContract (118ms)
     testInitialBalanceWithNewMetaCoin (82ms)

  2 passing (7s)

(base) localhost:MetaCoin liyuechun$ 
  1. 运行JavaScript测试文件:
(base) localhost:MetaCoin liyuechun$ truffle test ./test/metacoin.js

Compiling your contracts...
===========================
> Compiling ./contracts/ConvertLib.sol
> Compiling ./contracts/MetaCoin.sol
> Compiling ./contracts/Migrations.sol
> Artifacts written to /var/folders/cg/gbffc3nx2033d74hrgmjkqsc0000gn/T/test-2020512-16511-dl0cp4.icqs8
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

  Contract: MetaCoin
     should put 10000 MetaCoin in the first account
     should call a function that depends on a linked library (57ms)
     should send coin correctly (147ms)

  3 passing (280ms)

(base) localhost:MetaCoin liyuechun$ 

四、编译

(base) localhost:MetaCoin liyuechun$ truffle compile

Compiling your contracts...
===========================
> Compiling ./contracts/ConvertLib.sol
> Compiling ./contracts/MetaCoin.sol
> Compiling ./contracts/Migrations.sol
> Artifacts written to /Users/liyuechun/Desktop/demo/MetaCoin/build/contracts
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

五、使用Truffle Develop进行迁移

注意:要使用Ganache,请跳至下一部分。

为了部署我们的智能合约,我们将需要连接到区块链。Truffle具有内置的可用于测试的区块链。该区块链在您的系统本地,它不与以太坊网络交互。

您可以创建该区块链并使用Truffle Develop与之交互。

  1. 运行Truffle Develop:
(base) localhost:MetaCoin liyuechun$ truffle compile

你将看到终端有如下信息:

(base) localhost:MetaCoin liyuechun$ truffle compile

Compiling your contracts...
===========================
> Compiling ./contracts/ConvertLib.sol
> Compiling ./contracts/MetaCoin.sol
> Compiling ./contracts/Migrations.sol
> Artifacts written to /Users/liyuechun/Desktop/demo/MetaCoin/build/contracts
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

(base) localhost:MetaCoin liyuechun$ truffle develop
Truffle Develop started at http://127.0.0.1:9545/

Accounts:
(0) 0x7ee9b9f4e590ad4c3bf493090961e94461d30253
(1) 0x64e23661ba26baa4c620ac8617f537dbd2e44bb8
(2) 0xf782ce63dea03490311f3d7088ae3b4d2d2a3ff2
(3) 0x33f6f0499a636ae3e72d215d38470fa61df81d5a
(4) 0x5e60b96cff19dd641c21615c395060d504c36b6b
(5) 0xf4d4481fecf3089feaa142407d09f8c14b8d8a58
(6) 0xf5029a1147218ce7e8c34ff2be9efddfaee8db26
(7) 0x535183191781904d7e07aeed6cf8ec772da8a6d6
(8) 0x0dae94aff9fd80767092a98f8a80bc698f1899e6
(9) 0x0a02c6303bde4d5c984ff7b7a4190877c19a3f2f

Private Keys:
(0) df60116e8fa7b72ab12f1df2c92ce4210dfd2d7a087cc2b727d998baad150fc4
(1) 481e4e043dda801a845a6ff71d9532b07d002951d9dc8676328e19822a914db2
(2) fbb71797cb7f056184552e667155fd483bedbee90303febef26aa1c440924c20
(3) 42d003da13240cb1a5c36cf4c6ec9482f885dd69bddaaa8eff19ea5dfccf6fb1
(4) 00610d992e2c1df3627142cea5219c70a551600919a20918d9356105e63c8064
(5) b42ea218056adebe8905d0997b03eb8ed9fce80e99a3a53e24cd28dc3636b58c
(6) be8afa1868ec73675c8d816bd0c0a6278e9a9e5201209e1c3d2b151bc16feb13
(7) 3265c18c92f0c860ae5f75d5a3b5eefc9d548687fbbafe0f452506d952a84772
(8) 887baa63c07fa95ae74041c78c087fb680c868d6089f5168b8141b6fda2a4162
(9) cd585e445b96f04deae3ba17c024f18f39141357b0798add905f3f3a6e0534bf

Mnemonic: live spring tube drum history hawk diet sort long liquid library execute

️  Important ️  : This mnemonic was created for you by Truffle. It is not secure.
Ensure you do not use it on production blockchains, or else you risk losing funds.

truffle(develop)> 

这显示了与区块链进行交互时可以使用的十个账户(及其私钥)。

  1. Truffle Develop提示符下,可以通过省略truffle前缀来运行Truffle命令。例如,要truffle compile在提示符下运行,直接键入compile即可。将已编译合约部署到区块链的命令是truffle migrate,因此在提示符下键入:
truffle(develop)> migrate

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

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

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

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0x12edce599f2b6383557e9b675fe0dd0fae2776477185886993aa3966a7121d48
   > Blocks: 0            Seconds: 0
   > contract address:    0x3dEA1A0B88462714C50c87cb8c4F333652808e4a
   > block number:        1
   > block timestamp:     1591947475
   > account:             0x7ee9b9F4E590ad4C3Bf493090961E94461d30253
   > 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:    0xe65ce4ace196bcc91502ee53dfdeb6bb4ac4d93f0d299871aa07f8003e815110
   > Blocks: 0            Seconds: 0
   > contract address:    0x913d5C05A098Ac6B1Bcce783E9cCC9a019d1C437
   > block number:        3
   > block timestamp:     1591947475
   > account:             0x7ee9b9F4E590ad4C3Bf493090961E94461d30253
   > 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: 0x913d5C05A098Ac6B1Bcce783E9cCC9a019d1C437)

   Deploying 'MetaCoin'
   --------------------
   > transaction hash:    0x86828016df707c47eefd2a4729fa58a9670bf0d2accd21cfab4162130803e602
   > Blocks: 0            Seconds: 0
   > contract address:    0xf81DD76A64d740ba043DcF5CB0290A62858Df151
   > block number:        4
   > block timestamp:     1591947475
   > account:             0x7ee9b9F4E590ad4C3Bf493090961E94461d30253
   > balance:             99.98822898
   > gas used:            286565 (0x45f65)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.0057313 ETH

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

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

truffle(develop)> 

这显示了已部署合约的交易ID和地址。它还包括成本汇总和实时状态更新。

注意:您的交易哈希,合约地址和帐户将与上述不同。
注意:要查看如何与合约进行交互,请跳至下一部分。

六、替代方案:使用Ganache进行迁移

尽管Truffle Develop是一个多合一的内置区块链和控制台,但您也可以使用桌面应用程序Ganache启动您的个人区块链。对于那些以太坊和区块链新手来说,Ganache可能是一个更易于理解的工具,因为它可以预先显示更多信息。

除了运行Ganache之外,唯一的额外步骤是它需要编辑Truffle配置文件以指向Ganache实例。

  1. 下载并安装Ganache

  2. Atom打开truffle-config.js文件,用以下内容替换:

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*"
    }
  }
};

这将允许使用Ganache的默认连接参数进行连接。

  1. 保存并关闭该文件。
  2. 启动Ganache。

【Truffle系列第2篇】3分钟快速玩转truffle框架

  1. 在终端上,将合约迁移到由Ganache创建的区块链:
(base) localhost:MetaCoin liyuechun$ truffle migrate

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

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

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

   Replacing 'Migrations'
   ----------------------
   > transaction hash:    0x94b58facfab65fb66ec6f4f15a7c84c7bc13c980e55475dcc769b35ba0d05b3b
   > Blocks: 0            Seconds: 0
   > contract address:    0xD6A6EEdbBe44E4d43fA9DcAb8a970843cd54C473
   > block number:        1
   > block timestamp:     1591951051
   > account:             0xE2A58560AF5244c6D8080b5f650b3a23BEd3ea84
   > 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
=====================

   Replacing 'ConvertLib'
   ----------------------
   > transaction hash:    0x8f20f7362a2be3f14929f9c41930269255ceeadabc710037c2534422b687f863
   > Blocks: 0            Seconds: 0
   > contract address:    0xEFD5C494EddE78279A9bD897669B5c353ebf5734
   > block number:        3
   > block timestamp:     1591951051
   > account:             0xE2A58560AF5244c6D8080b5f650b3a23BEd3ea84
   > 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: 0xEFD5C494EddE78279A9bD897669B5c353ebf5734)

   Replacing 'MetaCoin'
   --------------------
   > transaction hash:    0xff82a6ae1552c29f731e0c725b020a99e48177bd2593b613693b5a567be85f1c
   > Blocks: 0            Seconds: 0
   > contract address:    0x0C234b820fa632538B2828Ba6F1EEb14D81E0247
   > block number:        4
   > block timestamp:     1591951051
   > account:             0xE2A58560AF5244c6D8080b5f650b3a23BEd3ea84
   > balance:             99.98822898
   > gas used:            286565 (0x45f65)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.0057313 ETH

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

Summary
=======
> Total deployments:   3
> Final cost:          0.0109242 ETH
  1. 查看Ganache相关事务

【Truffle系列第2篇】3分钟快速玩转truffle框架

  1. 要与合约进行交互,可以使用Truffle控制台。Truffle控制台类似于Truffle Develop,不同之处在于它连接到现有的区块链(在本例中为Ganache生成的区块链)。
(base) localhost:MetaCoin liyuechun$ truffle console
truffle(development)> 

七、与合约互动

通过以下方式使用控制台与合同进行交互:

注意:在这些示例中,我们使用web3.eth.getAccounts(),它返回一个promise,该promise解析为助记符生成的所有帐户的数组。因此,根据上面助记符生成的地址,指定(await web3.eth.getAccounts())[0]等同于地址’0xE2A58560AF5244c6D8080b5f650b3a23BEd3ea84`。

Truffle v5开始,该控制台支持异步/等待功能,从而使与合约的交互更加简单。

  • 首先建立部署的MetaCoin合约实例和Truffle的内置区块链或Ganache创建的帐户:
truffle(development)> let instance = await MetaCoin.deployed()
undefined
truffle(development)> let accounts = await web3.eth.getAccounts()
undefined
  • 检查部署合约帐户的原始代币余额:

    truffle(development)> let accounts = await web3.eth.getAccounts()
    undefined
    truffle(development)> let balance = await instance.getBalance(accounts[0])
    undefined
    truffle(development)> balance.toNumber()
    10000
  • 查看该原始代币值多少以太币(注意,该合约将一个元代币定义为价值2以太币):

    truffle(development)> let ether = await instance.getBalanceInEth(accounts[0])
    undefined
    truffle(development)> ether.toNumber()
    20000
    truffle(development)> 
  • 将一些原始代币从一个帐户转移到另一个帐户:

    truffle(development)> instance.sendCoin(accounts[1], 500)
    { tx:
    '0x9bf3fdbca9821bb8cba1c3240ca2418795c75dedf5894699d061582cfc0b182d',
    receipt:
    { transactionHash:
      '0x9bf3fdbca9821bb8cba1c3240ca2418795c75dedf5894699d061582cfc0b182d',
     transactionIndex: 0,
     blockHash:
      '0x7f772c4d25703d936f76bd5de6b53cada1aadfec2bbd6890e0a4c438091c0337',
     blockNumber: 6,
     from: '0xe2a58560af5244c6d8080b5f650b3a23bed3ea84',
     to: '0x0c234b820fa632538b2828ba6f1eeb14d81e0247',
     gasUsed: 51520,
     cumulativeGasUsed: 51520,
     contractAddress: null,
     logs: [ [Object] ],
     status: true,
     logsBloom:
      '0x00000000000000000000000000000000000000000040000000000000000000000000000000000000000000004008200000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000040000000000000000002000000000000000000000000000000000000000000000010000000000000400000000000000000000000400000000000000000000000000000000000',
     rawLogs: [ [Object] ] },
    logs:
    [ { logIndex: 0,
       transactionIndex: 0,
       transactionHash:
        '0x9bf3fdbca9821bb8cba1c3240ca2418795c75dedf5894699d061582cfc0b182d',
       blockHash:
        '0x7f772c4d25703d936f76bd5de6b53cada1aadfec2bbd6890e0a4c438091c0337',
       blockNumber: 6,
       address: '0x0C234b820fa632538B2828Ba6F1EEb14D81E0247',
       type: 'mined',
       id: 'log_646f189f',
       event: 'Transfer',
       args: [Result] } ] }
  • 检查收到原始代币的账户余额:

truffle(development)> let received = await instance.getBalance(accounts[1])
undefined
truffle(development)> received.toNumber()
500
truffle(development)> 
  • 检查发送元代币的账户余额:
    truffle(development)> let newBalance = await instance.getBalance(accounts[0])
    undefined
    truffle(development)> newBalance.toNumber()
    9500

继续学习

这篇文章属于快速入门教程,并没有繁琐的讲解太多,这篇文章向您展示了Truffle项目生命周期的基础知识,但还有很多东西要学习。请继续阅读我们的其余文档。

该内容来自于互联网公开内容,非区块链原创内容,如若转载,请注明出处:https://htzkw.com/archives/24985

联系我们

aliyinhang@gmail.com