Buidler 新手教程

2020-08-12 20:08 栏目:经验之谈 来源:网络整理 查看()
1. 概述

欢迎来到Buidler的初学者指南,看看如何基于Buidler进行以太坊合约和dApp开发。

Buidler是一个方便在以太坊上进行构建的任务运行器。使用它可以帮助开发人员管理和自动化构建智能合约和dApp的过程中固有的重复任务,以及轻松地围绕此工作流程引入更多功能。

Buidler还内置了Buidler EVM,后者是为开发而设计的本地以太坊网络。它允许你部署合约,运行测试和调试代码。

在本教程中,我们将指导你完成以下操作:
为以太坊开发设置Node.js环境
创建和配置 Buidler 项目
实现Solidity智能合约代币
使用 Ethers.js[3] 和 Waffle[4]为合约编写自动化测试
使用Buidler EVM通过console.log()调试Solidity
将合约部署到Buidler EVM和以太坊测试网

要完成本教程,你应该能够:

编写 JavaScript[5]
打开 terminal[6]
使用 git[7]
了解 smart contracts[8] 基础知识
设置 Metamask[9]钱包
如果你不具备上述知识,请访问链接并花一些时间来学习基础知识。

2. 环境搭建

大多数以太坊库和工具都是用JavaScript编写的,Buidler也是如此。如果你不熟悉Node.js,它是基于Chrome的V8 JavaScript引擎构建的JavaScript运行时。这是在网络浏览器之外运行JavaScript的最受欢迎的解决方案,**Buidler **就是建立Node.js之上。

安装 Node.js

如果你已经安装了的Node.js> = 10.0,则可以跳过本节。如果没有,请按照以下步骤在Ubuntu,MacOS和Windows上安装它。

Linux
Ubuntu

将以下命令复制并粘贴到终端中:

sudo apt update
sudo apt install curl git
sudo apt install build-essential ## 构建工具,我们需要它来建立本地依赖
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt install nodejs

MacOS

确保你已安装git。否则,请遵循这些说明[10]安装。

在MacOS上有多种安装Node.js的方法。我们将使用 Node 版本管理器(nvm)[11]。将以下命令复制并粘贴到终端中:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.2/install.sh | bash
nvm install 10
nvm use 10
nvm alias default 10
npm install npm --global ## 将npm升级到最新版本
npm install -g node-gyp ## 确保我们已安装node-gyp
## 下一步需要构建本地依赖项。
## 将会出现一个弹出窗口,你必须继续进行安装。
## 这将需要一些时间,并且可能会下载几个G的数据。

xcode-select --install
Windows

在Windows上安装Node.js需要一些手动步骤。我们将安装git,Node.js 10.x和NPM的Windows构建工具。下载并运行以下命令:

· Git的Windows安装程序[12]
· 从 这里[13]下载node-v10.XX.XX-x64.msi

然后 以管理员身份打开终端[14] 并运行以下命令:

npm install --global --production windows-build-tools
这将需要几分钟,并且可能会下载几GB的数据。

检查环境

为了确保你的开发环境已经准备就绪,请将以下命令复制并粘贴到新的终端中:

git clone https://github.com/nomiclabs/ethereum-hackathon-setup-checker.git
cd ethereum-hackathon-setup-checker
npm install

如果成功,你将看到一条确认消息,表示你的开发环境已准备就绪。你可以随时删除这个检查环境的代码库目录,然后在 创建新的Buidler项目[15]中继续前进。

如果遇到提示失败,则说明你的环境未正确设置。确保已经安装了git和Node.js >= 10.0。如果看到提到“ node-gyp”的错误,请确保安装了前面提到的构建工具。

如果你有旧版本的Node.js,请参阅下一节。

升级 Node.js

如果你的Node.js版本低于 10.0 ,请按照以下说明进行升级。完成后,请返回 检查环境[16]。

Linux

Ubuntu

在控制台运行 sudo apt remove nodejs 以删除 node.js

在此处[17]中找到要安装的Node.js版本,然后按照说明进行操作。

在控制台运行  sudo apt update && sudo apt install nodejs 以再次安装新的 node.js

MacOS

你可以使用nvm[18]更改Node.js版本。要升级到Node.js12.x,请在终端中运行以下命令:

nvm install 12
nvm use 12
nvm alias default 12
npm install npm --global ## Upgrade npm to the latest version
npm install -g node-gyp ## Make sure we have node-gyp installed

Windows

你需要像以前一样遵循安装说明[19],但选择其他版本。你可以在此处[20]检查所有可用版本的列表。

3. 创建新的 Buidler 工程

我们将使用npm 命令行安装**Builder **。NPM是一个Node.js软件包管理器和一个JavaScript代码在线存储库。打开一个新终端并运行以下命令:

mkdir buidler-tutorial 
cd buidler-tutorial 
npm init --yes 
npm install --save-dev @nomiclabs/buidler

提示:安装Builder将安装一些以太坊JavaScript依赖项,因此请耐心等待。

在安装Builder的目录下运行:

npx buidler

使用键盘选择 “创建一个新的builder.config.js(Create an empty buidler.config.js)”,然后回车。

$ npx buidler
888               d8b      888 888
888               Y8P      888 888
888                        888 888
88888b.  888  888 888  .d88888 888  .d88b.  888d888
888 "88b 888  888 888 d88" 888 888 d8P  Y8b 888P"
888  888 888  888 888 888  888 888 88888888 888
888 d88P Y88b 888 888 Y88b 888 888 Y8b.     888
88888P"   "Y88888 888  "Y88888 888  "Y8888  888

 Welcome to Buidler v1.0.0 

? What do you want to do? …
  Create a sample project
❯ Create an empty buidler.config.js
  Quit

在运行Buidler时,它将从当前工作目录开始搜索最接近的buidler.config.js文件。这个文件通常位于项目的根目录下,一个空的buidler.config.js足以使Buidler正常工作。

Buidler 架构

Buidler是围绕**task(任务)和plugins(插件)**的概念设计的。**Buidler **的大部分功能来自插件,作为开发人员,你可以自由选择[21]你要使用的插件。

Tasks(任务)

每次你从CLI运行Buidler时,你都在运行任务。例如 npx buidler compile正在运行compile任务。要查看项目中当前可用的任务,运行npx buidler。通过运行npx buidler help [task],可以探索任何任务。

提示:你可以创建自己的任务。请查看创建任务[22]指南。

Plugins(插件)

在最终选择哪种工具,Buidler并不是排他的,但是它确实内置了一些特性,所有这些也都可以覆盖。大多数时候,使用给定工具的方法是使用将其集成到Buidler中的插件。

在本教程中,我们将使用Ethers.js和Waffle插件。他们允许你与以太坊进行交互并测试合约。稍后我们将解释它们的用法。要安装它们,请在项目目录中运行:

npm install --save-dev @nomiclabs/buidler-ethers ethers @nomiclabs/buidler-waffle ethereum-waffle chai

将高亮行添加到你的builder.config.js中,如下所示:

usePlugin("@nomiclabs/buidler-waffle");

module.exports = {
  solc: {
    version: "0.6.8"
  }
};

我们在这里仅调用builder-waffle,因为它依赖于builder-ethers,因此不需要同时添加两者。

4. 编写和编译合约

我们将创建一个简单的智能合约,该合约实现可以转让的代币。代币合约最常用于交换或存储价值。在本教程中,我们将不深入讨论合约的Solidity代码,但是我们实现一些逻辑你应该知道:

· 代币有固定的发行总量,并且总量是无法更改的。
· 整个发行总量都分配给了部署合约的地址。
· 任何人都可以接收代币。
· 拥有至少一个代币的任何人都可以转让代币。
· 代币不可分割。你可以转让1、2、3或37个代币,但不能转让2.5个代币。

提示:你可能听说过ERC20,这是以太坊中的代币标准。DAI,USDC,MKR和ZRX之类的代币都遵循ERC20标准,使这些代币都可以与任何能处理ERC20代币的软件兼容。为了简单起见,我们要构建的代币不是ERC20。

编写合约

首先创建一个名为 contracts 的新目录,然后在目录内创建一个名为Token.sol的文件。

将下面的代码粘贴到文件中,花一点时间阅读代码。它很简单,并且有很多解释Solidity基础语法[23]的注释。

提示:在文本编辑器中添加相应的插件(搜索Solidity 或 Ethereum 插件)可以支持Solidity语法高亮,我们建议使用Visual Studio Code或Sublime Text 3。

// Solidity files have to start with this pragma.
// It will be used by the Solidity compiler to validate its version.
pragma solidity ^0.6.0;

// This is the main building block for smart contracts.
contract Token {
    // Some string type variables to identify the token.
    string public name = "My Buidler Token";
    string public symbol = "MBT";

    // The fixed amount of tokens stored in an unsigned integer type variable.
    uint256 public totalSupply = 1000000;

    // An address type variable is used to store ethereum accounts.
    address public owner;

    // A mapping is a key/value map. Here we store each account balance.
    mapping(address => uint256) balances;

    /**
     * 合约构造函数
     *
     * The `constructor` is executed only once when the contract is created.
     * The `public` modifier makes a function callable from outside the contract.
     */
    constructor() public {
        // The totalSupply is assigned to transaction sender, which is the account
        // that is deploying the contract.
        balances[msg.sender] = totalSupply;
        owner = msg.sender;
    }

    /**
     * 代币转账.
     *
     * The `external` modifier makes a function *only* callable from outside
     * the contract.
     */
    function transfer(address to, uint256 amount) external {
        // Check if the transaction sender has enough tokens.
        // If `require`'s first argument evaluates to `false` then the
        // transaction will revert.
        require(balances[msg.sender] >= amount, "Not enough tokens");

        // Transfer the amount.
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }

    /**
     * 读取某账号的代币余额
     *
     * The `view` modifier indicates that it doesn't modify the contract's
     * state, which allows us to call it without executing a transaction.
     */
    function balanceOf(address account) external view returns (uint256) {
        return balances[account];
    }
}

提示:*.sol 的Solidity 合约文件的后缀。我们建议将文件名与其包含的合约名一致,这是一种常见的做法。

编译合约

要编译合约,请在终端中运行 npx buidler compile 。compile任务是内置任务之一。

$ npx buidler compile
Compiling...
Compiled 1 contract successfully

合约已成功编译,可以使用了。

5. 测试合约

为智能合约编写自动化测试至关重要,因为事关用户资金。为此,我们将使用Buidler EVM,这是一个内置的以太坊网络,专门为开发而设计,并且是**Buidler **中的默认网络。你无需进行任何设置即可使用它。在我们的测试中,我们将使用ethers.js[24]与上一节中构建的以太坊合约进行交互,并使用 Mocha[25] 作为测试框架。

编写测试用例

在项目根目录中创建一个名为test的新目录,并创建一个名为Token.js的新文件。

让我们从下面的代码开始。接下来,我们将对其进行解释,但现在将其粘贴到Token.js中:

const { expect } = require("chai");

describe("Token contract", function() {
  it("Deployment should assign the total supply of tokens to the owner", async function() {
    const [owner] = await ethers.getSigners();

    const Token = await ethers.getContractFactory("Token");

    const buidlerToken = await Token.deploy();
    await buidlerToken.deployed();

    const ownerBalance = await buidlerToken.balanceOf(owner.getAddress());
    expect(await buidlerToken.totalSupply()).to.equal(ownerBalance);
  });
});

在终端上运行npx buidler test。你应该看到以下输出:

$ npx buidler test
All contracts have already been compiled, skipping compilation.

  Token contract
    ✓ Deployment should assign the total supply of tokens to the owner (654ms)

  1 passing (663ms)

这意味着测试通过了。现在我们逐行解释一下:

const [owner] = await ethers.getSigners();

ethers.js中的Signer是代表以太坊账户的对象。它用于将交易发送到合约和其他帐户。在这里,我们获得了所连接节点中的帐户列表,在本例中节点为Buidler EVM,并且仅保留第一个帐户。

ethers变量在全局作用域下都可用。如果你希望代码始终是明确的,则可以在顶部添加以下行:

const { ethers } = require("@nomiclabs/buidler");
提示:要了解有关Signer的更多信息,可以查看Signers文档[26]。

const Token = await ethers.getContractFactory("Token");

ethers.js中的ContractFactory是用于部署新智能合约的抽象,因此此处的Token是我们代币合约实例的工厂。

const buidlerToken = await Token.deploy();

在ContractFactory上调用deploy()将启动部署,并返回解析为Contract的Promise。该对象包含了智能合约所有函数的方法。

await buidlerToken.deployed();

当你调用deploy()时,将发送交易,但是直到该交易打包出块后,合约才真正部署。调用deployed()将返回一个Promise,因此该代码将阻塞直到部署完成。

const ownerBalance = await buidlerToken.balanceOf(owner.getAddress());

部署合约后,我们可以在buidlerToken 上调用我们的合约方法,通过调用balanceOf()来获取所有者帐户的余额。

请记住,获得全部代币发行量的账户是进行部署的帐户,并且在使用 buidler-ethers 插件时,默认情况下, ContractFactory和Contract实例连接到第一个签名者。这意味着owner变量中的帐户执行了部署,而balanceOf()应该返回全部发行量。

expect(await buidlerToken.totalSupply()).to.equal(ownerBalance);

在这里,我们再次使用Contract实例调用Solidity代码中合约函数。totalSupply()返回代币的发行量,我们检查它是否等于ownerBalance。

为此,我们使用Chai[27],这是一个断言库。这些断言函数称为“匹配器”,我们在此使用的实际上来自Waffle[28]。这就是为什么我们使用buidler-waffle插件,这使得从以太坊上断言值变得更容易。请查看Waffle文档中的此部分[29],了解以太坊特定匹配器的完整列表。

使用不同的账号

如果你需要从默认帐户以外的其他帐户(或ethers.js 中的 Signer)发送交易来测试代码,则可以在ethers.js的Contract中使用connect()方法来将其连接到其他帐户。像这样:

const { expect } = require("chai");

describe("Transactions", function () {

  it("Should transfer tokens between accounts", async function() {
    const [owner, addr1, addr2] = await ethers.getSigners();

    const Token = await ethers.getContractFactory("Token");

    const buidlerToken = await Token.deploy();
    await buidlerToken.deployed();
   
    // Transfer 50 tokens from owner to addr1
    await buidlerToken.transfer(await addr1.getAddress(), 50);
    expect(await buidlerToken.balanceOf(await addr1.getAddress())).to.equal(50);
    
    // Transfer 50 tokens from addr1 to addr2
    await buidlerToken.connect(addr1).transfer(await addr2.getAddress(), 50);
    expect(await buidlerToken.balanceOf(await addr2.getAddress())).to.equal(50);
  });
});

完整测试

既然我们已经介绍了测试合约所需的基础知识,一下是代币的完整测试用例,其中包含有关Mocha以及如何构组织测试的许多信息。我们建议你通读。

// We import Chai to use its asserting functions here.
const { expect } = require("chai");

// `describe` is a Mocha function that allows you to organize your tests. It's
// not actually needed, but having your tests organized makes debugging them
// easier. All Mocha functions are available in the global scope.

// `describe` receives the name of a section of your test suite, and a callback.
// The callback must define the tests of that section. This callback can't be
// an async function.
describe("Token contract", function () {
  // Mocha has four functions that let you hook into the the test runner's
  // lifecyle. These are: `before`, `beforeEach`, `after`, `afterEach`.

  // They're very useful to setup the environment for tests, and to clean it
  // up after they run.

  // A common pattern is to declare some variables, and assign them in the
  // `before` and `beforeEach` callbacks.

  let Token;
  let buidlerToken;
  let owner;
  let addr1;
  let addr2;
  let addrs;

  // `beforeEach` will run before each test, re-deploying the contract every
  // time. It receives a callback, which can be async.
  beforeEach(async function () {
    // Get the ContractFactory and Signers here.
    Token = await ethers.getContractFactory("Token");
    [owner, addr1, addr2, ...addrs] = await ethers.getSigners();

    // To deploy our contract, we just have to call Token.deploy() and await
    // for it to be deployed(), which happens onces its transaction has been
    // mined.
    buidlerToken = await Token.deploy();
    await buidlerToken.deployed();

    // We can interact with the contract by calling `buidlerToken.method()`
    await buidlerToken.deployed();
  });

  // You can nest describe calls to create subsections.
  describe("Deployment", function () {
    // `it` is another Mocha function. This is the one you use to define your
    // tests. It receives the test name, and a callback function.

    // If the callback function is async, Mocha will `await` it.
    it("Should set the right owner", async function () {
      // Expect receives a value, and wraps it in an assertion objet. These
      // objects have a lot of utility methods to assert values.

      // This test expects the owner variable stored in the contract to be equal
      // to our Signer's owner.
      expect(await buidlerToken.owner()).to.equal(await owner.getAddress());
    });

    it("Should assign the total supply of tokens to the owner", async function () {
      const ownerBalance = await buidlerToken.balanceOf(owner.getAddress());
      expect(await buidlerToken.totalSupply()).to.equal(ownerBalance);
    });
  });

  describe("Transactions", function () {
    it("Should transfer tokens between accounts", async function () {
      // Transfer 50 tokens from owner to addr1
      await buidlerToken.transfer(await addr1.getAddress(), 50);
      const addr1Balance = await buidlerToken.balanceOf(
        await addr1.getAddress()
      );
      expect(addr1Balance).to.equal(50);

      // Transfer 50 tokens from addr1 to addr2
      // We use .connect(signer) to send a transaction from another account
      await buidlerToken.connect(addr1).transfer(await addr2.getAddress(), 50);
      const addr2Balance = await buidlerToken.balanceOf(
        await addr2.getAddress()
      );
      expect(addr2Balance).to.equal(50);
    });

    it("Should fail if sender doesn’t have enough tokens", async function () {
      const initialOwnerBalance = await buidlerToken.balanceOf(
        await owner.getAddress()
      );

      // Try to send 1 token from addr1 (0 tokens) to owner (1000 tokens).
      // `require` will evaluate false and revert the transaction.
      await expect(
        buidlerToken.connect(addr1).transfer(await owner.getAddress(), 1)
      ).to.be.revertedWith("Not enough tokens");

      // Owner balance shouldn't have changed.
      expect(await buidlerToken.balanceOf(await owner.getAddress())).to.equal(
        initialOwnerBalance
      );
    });

    it("Should update balances after transfers", async function () {
      const initialOwnerBalance = await buidlerToken.balanceOf(
        await owner.getAddress()
      );

      // Transfer 100 tokens from owner to addr1.
      await buidlerToken.transfer(await addr1.getAddress(), 100);

      // Transfer another 50 tokens from owner to addr2.
      await buidlerToken.transfer(await addr2.getAddress(), 50);

      // Check balances.
      const finalOwnerBalance = await buidlerToken.balanceOf(
        await owner.getAddress()
      );
      expect(finalOwnerBalance).to.equal(initialOwnerBalance - 150);

      const addr1Balance = await buidlerToken.balanceOf(
        await addr1.getAddress()
      );
      expect(addr1Balance).to.equal(100);

      const addr2Balance = await buidlerToken.balanceOf(
        await addr2.getAddress()
      );
      expect(addr2Balance).to.equal(50);
    });
  });
});

这是 npx buidler test在完整测试用例下输出的样子:

$ npx buidler test
All contracts have already been compiled, skipping compilation.

  Token contract
    Deployment
      ✓ Should set the right owner
      ✓ Should assign the total supply of tokens to the owner
    Transactions
      ✓ Should transfer tokens between accounts (199ms)
      ✓ Should fail if sender doesn’t have enough tokens
      ✓ Should update balances after transfers (111ms)

微信二维码
售前客服二维码

文章均源于网络收集编辑侵删

提示:仅接受技术开发咨询!

郑重申明:资讯文章为网络收集整理,官方公告以外的资讯内容与本站无关!
NFT开发,NFT交易所开发,DAPP开发 Keywords: NFT开发 NFT交易所开发 DAPP开发