# Truffle 入门

By [nightelfamber](https://paragraph.com/@nightelfamber) · 2022-03-03

---

Truff: 编译、部署、测试合约一套开发工具

Ganache: 开发区块链，提供本地模拟的链上环境

[https://trufflesuite.com/docs/truffle/](https://trufflesuite.com/docs/truffle/)

本人都在`linux` 系统上面学习，所以下面说说明都是基于`cli`

Truff，Ganache的安装不再进行说明

创建工程
----

创建文件

    mkdir MetaCoin
    cd MetaCoin
    

初始化工程，为了方便简单操作，这里我直接使用init的方式

    truffle init
    

![文件目录](https://storage.googleapis.com/papyrus_images/b967315db4cbf55382609b770242d21fa7d5f990461c8075f535af5e728a8dcc.png)

文件目录

contracts : 合约目录

Migrations：迁移文件，用来指示如何部署智能合约

test：智能合约测试用例文件夹

truffle-config.js: 配置文件，配置truffle连接的网络及编译选项

编译合约
----

    truffle compile
    

`truffle-config.js` 指定编译版本,这里指定0.8.11

![指定编译版本](https://storage.googleapis.com/papyrus_images/e158b882d07f0724284086e28a897c3fd4076b0f33e1e43f32c130fc1140c252.png)

指定编译版本

输出结果

![控制台](https://storage.googleapis.com/papyrus_images/e1225c7b4c67c0a0cb79474846dff3415fa67fa4a5e72eadf04b3675f6cae719.png)

控制台

部署合约
----

`truffle-config.js`配置网络,这里先展示基于Gananche的本地部署

网络配置

![本地部署](https://storage.googleapis.com/papyrus_images/c52d50abd00bed581a4518d0e354091f35d1780ff89ba5f9d59d38bd35eac58b.png)

本地部署

编写部署脚本，需要在migrations文件下面进行文件的编写,init 其实已经OK了的，这里可以先看看，熟悉一下

    const Migrations = artifacts.require("Migrations");
    
    module.exports = function (deployer) {
      deployer.deploy(Migrations);
    };
    

启动本地网络
------

这里是rpc 以及链上的相关信息,所以我们的配置信息也要改成这样的

![rpc](https://storage.googleapis.com/papyrus_images/0c42f14694d519d68728acdf092938061b2c4528440194bd3382dc31b21c634f.png)

rpc

部署
--

这个就会部署了，成功

![success](https://storage.googleapis.com/papyrus_images/a125ecb540b552256c173cca4781320caff60c0f5c53c7cbefa577ef490f9dde.png)

success

部署远程网络
------

配置,`mnemonic` 密钥和助记词都可以

    rinkeby: {
          provider: () => new HDWalletProvider(mnemonic, `https://rinkeby.infura.io/v3/${your-id}`),
          network_id: 4, // Ropsten's id
          gas: 5500000, // Ropsten has a lower block limit than mainnet
          confirmations: 2, // # of confs to wait between deployments. (default: 0)
          timeoutBlocks: 200, // # of blocks before a deployment times out  (minimum/default: 50)
          skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
        },
    

安装,千万不要全局安装

    npm install @truffle/hdwallet-provider
    

启动部署

    truffle migrate --network rinkeby
    

部署成功

![result](https://storage.googleapis.com/papyrus_images/2b10210e6c75431a18464c9229808bbec23f2249b6f08d971d44aeabe5ae3974.png)

result

查看交易hash 链上

![](https://storage.googleapis.com/papyrus_images/44541a23452fe2fca6f488264bf679920bba9e7b4508b5f18094d7cd363214f3.png)

---

*Originally published on [nightelfamber](https://paragraph.com/@nightelfamber/truffle)*
