# 5. 使用 Truffle

{% hint style="info" %}
Consensys 宣布终止与 Truffle 和 Ganache 的合作关系以及和 HardHat 新的合作关系，[更多详情](https://consensys.io/blog/consensys-announces-the-sunset-of-truffle-and-ganache-and-new-hardhat?utm_source=github\&utm_medium=referral\&utm_campaign=2023_Sep_truffle-sunset-2023_announcement_)。
{% endhint %}

## 1. 打开 Sandbox

注：以 GIthub 方式登录 ChainIDE 后才可使用 Sandbox 功能。

<figure><img src="https://2772835953-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZ6_j0WUFnBhwIdP3LR%2Fuploads%2Fvtyd8s84ShEux70plVWP%2Fimage.png?alt=media&#x26;token=dfa8e0b2-1e7a-4585-980c-fff86501d3ad" alt=""><figcaption></figcaption></figure>

打开 Sandbox，输入 `truffle version 可查看当前 truffle 版本`

<figure><img src="https://2772835953-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZ6_j0WUFnBhwIdP3LR%2Fuploads%2Fh14jVycX5T1C7C6HxTza%2Fimage.png?alt=media&#x26;token=41c8ab87-56f7-4db5-bff5-7cd58d4ba602" alt=""><figcaption></figcaption></figure>

## 2. 创建项目

你可以使用 `truffle init` 创建一个没有智能合约的裸项目，但对于那些初学者，你可以使用 Truffle Boxes 示例应用程序和项目模板。我们将使用 MetaCoin ，它创建一个可以在账户之间转移的代币。请注意，这与 ERC-20 不兼容。

1. 下载 ("unbox") the MetaCoin box:

```bash
truffle unbox metacoin [PATH/TO/DIRECTORY]
```

完成此操作后，您将拥有包含以下项目结构：

* `contracts/`: [Solidity contracts](https://trufflesuite.com/docs/truffle/getting-started/interacting-with-your-contracts) 目录
* `migrations/`: [scriptable deployment files](https://trufflesuite.com/docs/truffle/getting-started/running-migrations#migration-files) 目录
* `test/`: [testing your application and contracts](https://trufflesuite.com/docs/truffle/testing/testing-your-contracts) 的目录
* `truffle.js`: Truffle [configuration file](https://trufflesuite.com/docs/truffle/reference/configuration)

## 3. 探索项目&#x20;

在文本编辑器中打开 `contracts/MetaCoin.sol` 文件。这是一个智能合约（用 Solidity 编写），用于创建 MetaCoin 代币。请注意，这也引用了同一目录中的另一个 Solidity 文件 `contracts/ConvertLib.sol` 。

打开 `migrations/1_deploy_contracts.js` 文件。此文件是迁移（部署）脚本。

打开 `test/TestMetaCoin.sol` 文件。这是一个用 Solidity 编写的测试文件，可确保您的合约按预期工作。

打开 `test/metacoin.js` 文件。这是一个用 JavaScript 编写的测试文件，它具有与上面的 Solidity 测试文件类似的功能。该测试也可以用 typescript 编写。

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

## 4. 测试

要运行所有测试，只需运行 `truffle test` 。因为 `development` 被 `truffle-config.js` 注释掉了， `truffle test` 所以会启动并关闭一个本地测试实例 （ `ganache` ）。如果你想使用 ganache 更多的功能，您可以启动一个单独的实例，并在 truffle-config 中指定端口号。

```bash
TestMetaCoin
  ✔ testInitialBalanceUsingDeployedContract
  ✔ testInitialBalanceWithNewMetaCoin

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

您还可以通过调用 `truffle test ./test/TestMetaCoin.sol` 和 `truffle test ./test/metacoin.js` 来单独运行每个测试。

## 5. 编译

如果只想编译，可以简单地运行 `truffle compile`&#x20;

您将看到以下输出：

```bash
Compiling your contracts...
===========================
> Compiling ./contracts/ConvertLib.sol
> Compiling ./contracts/MetaCoin.sol
> Artifacts written to /Users/emilylin/dev/metacoin-box/build/contracts
> Compiled successfully using:
- solc: 0.8.13+commit.abaa5c0e.Emscripten.clang
```

## 6. 使用 Truffle Develop 进行迁移

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

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

1. 运行 Truffle Develop：

```
truffle develop
```

您将看到以下信息：

```bash
Truffle Develop started at http://127.0.0.1:9545/

Accounts:
(0) 0x627306090abab3a6e1400e9345bc60c78a8bef57
(1) 0xf17f52151ebef6c7334fad080c5704d77216b732
(2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef
(3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544
(4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2
(5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e
(6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5
(7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5
(8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc
(9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de

Private Keys:
(0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3
(1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f
(2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1
(3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c
(4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418
(5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63
(6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8
(7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7
(8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4
(9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5

Mnemonic: candy maple cake sugar pudding cream honey rich smooth crumble sweet treat

⚠️  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(development)>
```

这显示了在与区块链交互时可以使用的十个帐户（及其私钥）。

2. 在 Truffle Develop 提示符下，可以通过省略 `truffle` 前缀来运行 Truffle 命令。例如，若要在提示符下运行 `truffle compile` ，请键入 `compile` 。将编译的合约部署到区块链的命令是 `truffle migrate` 。默认情况下， `truffle migrate` 也会运行 `truffle compile` ，因此您只需执行以下操作：

```
migrate
```

您将看到以下输出：

```bash
Starting migrations...
======================
> Network name:    'develop'
> Network id:      4447
> Block gas limit: 6721975

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

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0x3fd222279dad48583a3320decd0a2d12e82e728ba9a0f19bdaaff98c72a030a2
   > Blocks: 0            Seconds: 0
   > contract address:    0xa0AdaB6E829C818d50c75F17CFCc2e15bfd55a63
   > account:             0x627306090abab3a6e1400e9345bc60c78a8bef57
   > balance:             99.99445076
   > gas used:            277462
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00554924 ETH

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

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

   Deploying 'ConvertLib'
   ----------------------
   > transaction hash:    0x97e8168f1c05fc40dd8ffc529b9a2bf45cc7c55b07b6b9a5a22173235ee247b6
   > Blocks: 0            Seconds: 0
   > contract address:    0xfb39FeaeF3ac3fd46e2123768e559BCe6bD638d6
   > account:             0x627306090abab3a6e1400e9345bc60c78a8bef57
   > balance:             99.9914458
   > gas used:            108240
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.0021648 ETH

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

   Deploying 'MetaCoin'
   --------------------
   > transaction hash:    0xee4994097c10e7314cc83adf899d67f51f22e08b920e95b6d3f75c5eb498bde4
   > Blocks: 0            Seconds: 0
   > contract address:    0x6891Ac4E2EF3dA9bc88C96fEDbC9eA4d6D88F768
   > account:             0x627306090abab3a6e1400e9345bc60c78a8bef57
   > balance:             99.98449716
   > gas used:            347432
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00694864 ETH

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

Summary
=======
> Total deployments:   3
> Final cost:          0.01466268 ETH
```

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

## 7. 使用 Truffle Console 迁移

虽然 Truffle Develop 是一个多合一的个人区块链和控制台，但它启动了一个非常基本的 ganache 实例。您还可以使用应用程序来启动您的个人区块链，对于那些刚接触以太坊和区块链的人来说，这是一个更容易理解的工具，因为它预先显示了更多信息。

可以参考 [使用 Ganache v7](https://chainide.gitbook.io/chainide-chinese/chainide/1.-ethereum-ide-2/4.-shi-yong-ganache-bu-shu) 在 ChainIDE 中运行 Ganache。下一步需要编辑 Truffle 配置文件以指向 Ganache 实例。

1. 在文本编辑器中打开 `truffle-config.js` 。将内容替换为以下内容：

```json
module.exports = {
  networks: {
    development: {
      host: "*******",   // ****为之前端口转发生成的本地链接并去掉“https://”
      port: 80,          //80为http端口
      network_id: "*"
    }
  }
};
```

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

2. 保存并关闭该文件。
3. 在终端上，将合约迁移到 Ganache 创建的区块链：

```
truffle migrate
```

您将看到以下输出：

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


Starting migrations...
======================
> Network name:    'development'
> Network id:      1661545227029
> Block gas limit: 30000000 (0x1c9c380)


1_deploy_contracts.js
=====================

Deploying 'ConvertLib'
----------------------
> transaction hash:    0x259332521763056a5b949d33e3f52bff424c357b56af939ca46f96baa4386729
> Blocks: 0            Seconds: 0
> contract address:    0x7c31fB61DC4b817A7AFF135382FC85bcc9078f5e
> block number:        1
> block timestamp:     1661545283
> account:             0x0BD3Ea7C1CDE97e91e83615D7F6eF8910b3d0FEB
> balance:             999.999468208
> gas used:            157568 (0x26780)
> gas price:           3.375 gwei
> value sent:          0 ETH
> total cost:          0.000531792 ETH


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

Deploying 'MetaCoin'
--------------------
> transaction hash:    0x86b381fa96891e619a60a75db681d8aa95648b53572acc02690c9b94c76eadae
> Blocks: 0            Seconds: 0
> contract address:    0x03709DE4e1a3dA52505345Bd5129b48Ac891d63B
> block number:        2
> block timestamp:     1661545283
> account:             0x0BD3Ea7C1CDE97e91e83615D7F6eF8910b3d0FEB
> balance:             999.998107289579739204
> gas used:            416594 (0x65b52)
> gas price:           3.266773934 gwei
> value sent:          0 ETH
> total cost:          0.001360918420260796 ETH

> Saving artifacts
-------------------------------------
> Total cost:     0.001892710420260796 ETH

Summary
=======
> Total deployments:   2
> Final cost:          0.001892710420260796 ETH
```

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

{% hint style="info" %}
注意：您的交易ID和合约地址可能与上述不同。
{% endhint %}

4. 要与合约交互，您可以使用 Truffle 控制台。Truffle 控制台类似于 Truffle Develop，不同之处在于它连接到现有的区块链（在本例中为 Ganache 生成的区块链）。

```
truffle console
```

您将看到以下提示：

```
truffle(development)>
```

## 8. 与合约交互

通过以下方式使用控制台与合约交互：

{% hint style="info" %}
注意：我们在这些示例中使用 `web3.eth.getAccounts()` ，它返回一个 promise，该 promise 解析为助记词生成的所有帐户的数组。因此，鉴于上面我们助记词生成的地址，指定 `(await web3.eth.getAccounts())[0]` 等价于地址 `0x627306090abab3a6e1400e9345bc60c78a8bef57` 。
{% endhint %}

从 Truffle v5 开始，控制台支持 async/await 函数，从而可以更轻松地与合约进行交互。

* 首先建立已部署的 MetaCoin 合约实例和 Truffle 的内置区块链或 Ganache 创建的账户：

```bash
truffle(development)> let instance = await MetaCoin.deployed()
truffle(development)> let accounts = await web3.eth.getAccounts()
```

* 查看部署合约的账户的 metacoin 余额：

```sh
truffle(development)> let balance = await instance.getBalance(accounts[0])
truffle(development)> balance.toNumber()
```

* 查看该余额的价值（请注意，合约将 metacoin 定义为价值 2 个以太币）：

```sh
truffle(development)> let ether = await instance.getBalanceInEth(accounts[0])
truffle(development)> ether.toNumber()
```

* 将一些 metacoin 从一个帐户转移到另一个帐户：

```sh
truffle(development)> instance.sendCoin(accounts[1], 500)
```

* 检查收到 metacoin 的账户余额：

```sh
truffle(development)> let received = await instance.getBalance(accounts[1])
truffle(development)> received.toNumber()
```

* 检查发送 metacoin 的账户余额：

```sh
truffle(development)> let newBalance = await instance.getBalance(accounts[0])
truffle(development)> newBalance.toNumber()
```

## 9. 部署到主网、测试网等 <a href="#deploy-to-mainnet-testnet-and-beyond" id="deploy-to-mainnet-testnet-and-beyond"></a>

如果要部署到备用网络，请考虑使用 Truffle Dashboard。只需调用 `truffle dashboard` `--network dashboard` 并部署、测试和运行控制台即可。

## 10. 继续学习

本快速入门介绍了 Truffle 项目生命周期的基础知识，但还有很多东西需要学习。请继续阅读 [Truffle 官方文档](https://trufflesuite.com/docs/truffle/)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chainide.gitbook.io/chainide-chinese/chainide/1.-ethereum-ide/3.-shi-yong-truffle-he-ganache.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
