current position:Home>From Idea to Minimal Viable Dapp - Truffle Command Line Interface Part 1

From Idea to Minimal Viable Dapp - Truffle Command Line Interface Part 1

2022-11-24 12:10:18ConsenSys

1.png

Each software engineer when building applications from scratch will default to a series of tools.In the traditional software industry,有很多工具可供选择,Can interoperate with end-to-end development.在 Web3 This emerging industry,,Not so many tools are considering interoperability build.

这就是 Truffle For developers to solve the problem of.Truffle 通过在 Truffle Suite in the creation and Web3 The other tools in compatible with the tools and functions to simplify the developer experience.

这是新的 Truffle The first part of the content of the series,In which we are outlined from one idea to the smallest possible dapp 的步骤,展示了 Truffle Suite for any level of experience in the intelligent contract developers with cool feature and tools.

在第一部分中,我们将专注于 Truffle CLI,And by creating a smart contract project、编写智能合约代码、编译、Migration and the interaction with smart contracts to show Truffle CLI 的所有可能,所有这些都在 Truffle CLI 中进行.

在后续的文章中,We will by adding automated tests to build this project,展示使用 Truffle 在 JavaScript/TypeScript 和 Solidity Add intelligent contract tests how easy it is to.稍后,We will also explore through Truffle Debugger 和 console.log Give us the debug options.

到本系列结束时,You will be able to build from scratch dapp,利用 Truffle Tool suite offers a variety of tools,包括 Ganache、用于 VS Code 扩展的 TruffleTruffle 仪表板Truffle boxes 等等更多的.

要求

In order to be able to follow up the content of this article,您需要满足以下要求:

  • Node.js v14 - v18
  • Windows、Linux 或 macOS

建议您使用 Node Version download manager Node.js,以避免使用 sudo 下载 Truffle 导致权限错误.按照此处Download instructions for your operating system Node 版本管理器.

安装 Node.js 后,您可以使用命令 npm install -g truffle全局安装 Truffle.有关更多信息,请参阅 Truffle 安装指南.

使用 Truffle Init 创建一个 Truffle 项目

要使用 Truffle 创建智能合约项目,有两个选项可供选择,一个是 Truffle box选项,We will in detail later in this series.第二个选项是 Truffle CLI 选项.对于这篇文章,我们将使用 Truffle CLI 选项.

Through worldwide download Truffle,您可以使用 Truffle CLI.For your project to create an empty folder and name it daily-nft,And then in this new folder in the root directory of the runningtruffle init.This should create a contract does not include the intelligence of quasi Truffle 项目.

If you check the newly created project structure,You will find that the following items:

contracts/: Solidity 合约目录

migrations/: Can write the script of the deployment file directory

test/: Used for testing the application and contract the test file directory

truffle-config.js: Truffle configuration file

智能合约

对于智能合约,We will use my excellent colleagues Josh 构建的这个项目.它被称为Daily NFT.The idea behind this project is,According to the winner of the auction,Every day to show a NFT.The user can with a display of the day NFT At the same time continue to bid on the second day NFT.

正如您将看到的,这是一个简单的项目,易于理解,但也足够复杂,不能成为一个 hello world Or the timer project.

在 contracts/目录下,新建一个 Solidity 文件并命名为 Auction.sol,Then add the following content:

// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.13;contract Auction {    event Start();    event Bid(address indexed sender, uint amount);    event Withdraw(address indexed bidder, uint amount);    event End(address winner, uint amount);    address payable public seller;    uint public endAt;    bool public started;    bool public ended;    address public highestBidder;    uint public highestBid; // Wei    mapping(address => uint) public bids;    mapping(address => address) public nfts;    mapping(address => uint256) public nftIds;}

A brief description of what happened in the code.我们定义了四个事件,They will be in the four important stages of contract trigger;When weStart 拍卖 - 手动、何时Bid、何时触发WithdrawAnd when the auction in 24 小时内End.

We also defines some public variables,如下所述:

seller:The auction owner to pay address - 部署地址.

endAt:Hours after the auction ended - 24 小时.

started:Indicates whether the auction has started True 或 False 值.

ended:True or false value,Indicates whether the auction has ended.

highestBidder:The current highest bidder's address.

highestBid:以WeiSaid the highest bid amount.

bids:Address instead of their bid amount the mapping between the

nfts:Address and their respective bidnft地址之间的映射

nftIds:nft Address and their respective Id 之间的映射.

...    constructor(        uint _startingBid    ) {        seller = payable(msg.sender);        highestBid = _startingBid;    }    function start() external {        require(!started, "started");        require(msg.sender == seller, "not seller");        started = true;        endAt = block.timestamp + 1 days;        emit Start();    }    function bid() external payable {        require(started, "not started");        require(block.timestamp < endAt, "ended");        require(msg.value > highestBid, "value < highest");        require(nfts[msg.sender] != address(0), "include nft to display");        if (highestBidder != address(0)) {            bids[highestBidder] += highestBid;        }        highestBidder = msg.sender;        highestBid = msg.value;        emit Bid(msg.sender, msg.value);    }    // Overload if the user submits an NFT    function bid(address nft, uint256 nftId) external payable {        require(started, "not started");        require(block.timestamp < endAt, "ended");        require(msg.value > highestBid, "value < highest");        if (highestBidder != address(0)) {            bids[highestBidder] += highestBid;        }        if (nfts[msg.sender] == address(0)) {            require(nft != address(0), "invalid nft address");            nfts[msg.sender] = nft;            nftIds[msg.sender] = nftId;        }        highestBidder = msg.sender;        highestBid = msg.value;        emit Bid(msg.sender, msg.value);    }    function withdraw() external {        uint bal = bids[msg.sender];        bids[msg.sender] = 0;        payable(msg.sender).transfer(bal);        emit Withdraw(msg.sender, bal);    }    function end() external {        require(started, "not started");        require(block.timestamp >= endAt, "end time in future");        require(!ended, "ended");        ended = true;        emit End(highestBidder, highestBid);    }

The following is the second part of the contract code:

  • constructor() Functions are called during deployment,The seller and highestBid Set respectively for the deployer address and _startingBid.

  • start() The function is called manual to start an auction.It sets the auction end time to from the start time of 24 小时.

  • 有两个 bid() 函数,一个接受 nft 地址和 Id,And the other does not accept any parameters.They ensure that the new bid value is higher than the current highest bid will be accepted.

  • withdraw()Function allows the user to withdraw their bid amount.

  • end()Function check before to stop the auction has reached the auction end time.

使用 Truffle CLI 编译合约

To compile the newly created contract,Please navigate to the project root directory and run thetruffle compile命令.Truffle 将遍历 /contracts目录,编译以 .sol At the end of each file and library.在我们的例子中,We have only one contract need to compile.

2.png

另请注意,在第一次运行时,Will compile all the contract,But in the subsequent operation of the,Truffle Will only compile has changed since the last compile contract.您可以通过使用--allOption to run the above command to override this behavior.

编译成功后,Please pay attention to isbuildA new build directory.This directory contains the compiled artifact,特别是在 build/contracts/ 目录中,相对于您的项目根目录.To continue to check this directory content.

使用 Truffle CLI In the local deployment contract

Truffle Comes with a built-in personal block chain,Can be used to interact locally with intelligent contracts and test.The block local chain in your system,Not with etheric lane or test network interaction.要访问它,只需运行命令truffle develop.

为了能够使用 Truffle Will be deployed to any contract the etheric lane network,You must create a migration file for the contract.迁移是 JavaScript 文件,Assume that your deployment requirements may change over time and write,Can help you will be deployed to any contract the etheric lane network,Including local operation node,如 Truffle The attached node.

现在在 migrations/文件夹中,创建一个新文件并将其命名为 1_migration.js.“_migration”之前的数字“1”非常重要,Because it says order,Is it to tell Truffle In another migration file which migration run before.Each new files are added to the migration folder to increase this number.

Copies of the following to the newly created migration file:

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

在这里,我们使用 artifacts.require()函数来告诉 Truffle We want to interact with which the contract documents.It returns a contract abstract,We can use it in the rest of the deployment script.在第二行,We are now exporting a function,This function USES the deployment program objects when the call and call deployer.deploy()Function to deploy the contract,At the same time introduced to auction contract constructor parameters needed in the specified.If you need more detailed understanding of the migration in Truffle 中的工作方式,请访问 Truffle 迁移文档.After finishing the migration file,We are ready to intelligent deployment contract to Truffle The built-in local block chain.首先运行命令truffle develop以公开 Truffle 开发人员控制台——If you haven't run it.

3.png

请注意,它在端口 9545 Started a local block chain.This command also openly 10 A etheric fang account as well as the associated private key and mnemonic word.Make sure not to send these addresses the real Eth 代币,Because they are safe and not only for the smart contracts to interact with you.

In the console,运行命令migrateWill be deployed to the local block your contract chain node.This should return the deployed contract deal ID 和地址,Including the cost.

4.png

使用 Truffle CLI Interact with local deployment contract

将合约部署到 Truffle After the local block chain,由于我们还没有 dapp 的前端,我们可以直接从 truffle develop Command and open the developer's console manually interact contracts with the deployment of smart.让我们开始吧!

获取已部署的合约:

truffle(develop)> let auction = await Auction.deployed()

Gets the current set of sellers and highest bid

truffle(develop)> let seller = await auction.seller()truffle(develop)> let highestBid = await auction.highestBid()

According to the seller and the highest bid,在我的例子中:

truffle(develop)> seller'0x1a33B6853b36F4c2E3872E229F3a77Bf75943F9d'truffle(develop)> highestBid.toNumber()100

Check to see if the auction has been started:

truffle(develop)> let started = await auction.stared()truffle(develop)> startedfalse

开始拍卖:

truffle(develop)> await auction.start()truffle(develop)> started = await auction.started()true

下一步是什么?

You have just successfully created a new Truffle 项目,Write a smart contract,Compile and deploy the intelligent contract!We have even use Truffle The developer's console in the local contract and deploy interact.恭喜!

在下一篇文章中,我们将探索使用 Truffle CLI Intelligent contract writing and running automated tests for us.

在 Truffle,We are always committed to by creating developer tools、资源和教育材料来改善和简化 Web3 生态系统中 dapp 开发人员的用户体验.

To learn about our developers tool suite for more information,请访问 Truffle 官方网站.如果您有任何疑问,请随时在我们的Github 讨论页面In discussing.

本文首发于:https://mp.weixin.qq.com/s/M92UTrKfGwmuBfndA8Qn6w

copyright notice
author[ConsenSys],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/328/202211241159422750.html

Random recommended