RIN:hardhat 教程及 hardhat-deploy 插件使用_SatoShi Monsters

译文出自:登链翻译计划

译者:翻译小组

校对:Tiny熊

本文在官方hardhat教程的基础上,加入了hardhat-deploy插件的使用介绍,本文代码的GitHub:https://github

/***Afunctiontotransfertokens.**The`external`modifiermakesafunction*only*callablefromoutside*thecontract.*/functiontransfer(addressto,uint256amount)external{//Checkifthetransactionsenderhasenoughtokens.//If`require`'sfirstargumentevaluatesto`false`thenthe//transactionwillrevert

/***Readonlyfunctiontoretrievethetokenbalanceofagivenaccount.**The`view`modifierindicatesthatitdoesn'tmodifythecontract's*state,whichallowsustocallitwithoutexecutingatransaction.*/functionbalanceOf(addressaccount)externalviewreturns(uint256){returnbalances;}}

*

;exportdefaultfunc;func

;exportdefaultfunc;func

);});

依赖的chai-setup同样在测试文件夹中,内容如下:

importchaiModulefrom'chai';import{chaiEthers}from'chai-ethers';chaiModule

);});

全面覆盖测试

现在我们已经介绍了测试合约所需的基础知识,这里有一个完整的代币测试Case,其中有很多关于Mocha的附加信息以及如何构建测试。我们建议通过阅读。

但首先我们要添加一些实用函数,我们将在该测试套件中使用。

在test文件夹中创建一个utils文件夹,并在其中创建一个index

returnusers;}exportasyncfunctionsetupUser<Textends{:Contract}>(address:string,contracts:T):Promise<{address:string}&T>{//eslint-disable-next-line;for(constkeyofObject

returnuseras{address:string}&T;}

通过utils可以方便的创建账号,让测试简洁和容易阅读,例如下面的Test

//`describe`isaMochafunctionthatallowsyoutoorganizeyourtests

);it("Shouldassignthetotalsupplyoftokenstotheowner",asyncfunction(){const{Token,tokenOwner}=awaitsetup();constownerBalance=awaitToken

);});describe("Transactions",function(){it("Shouldtransfertokensbetweenaccounts",asyncfunction(){const{Token,users,tokenOwner}=awaitsetup();//Transfer50tokensfromownertousersawaittokenOwner

);it("Shouldfailifsenderdoesn’thaveenoughtokens",asyncfunction(){const{Token,users,tokenOwner}=awaitsetup();constinitialOwnerBalance=awaitToken

);it("Shouldupdatebalancesaftertransfers",asyncfunction(){const{Token,users,tokenOwner}=awaitsetup();constinitialOwnerBalance=awaitToken

);});});

下面是yarnhardhattest的输出。

$yarnhardhattestTokencontractDeployment?Shouldsettherightowner?ShouldassignthetotalsupplyoftokenstotheownerTransactions?Shouldtransfertokensbetweenaccounts(199ms)?Shouldfailifsenderdoesn’thaveenoughtokens?Shouldupdatebalancesaftertransfers(111ms)5passing(1s)

请记住,当你运行yarnhardhattest时,如果合约在你上次运行测试后发生了变化,合约将被重新编译。

6.使用Hardhat网络进行调试

Hardhat内置了Hardhat网络,这是一个专为开发设计的本地以太坊网络。它允许你部署合约,运行测试和调试代码。这是Hardhat连接到的默认网络,所以你不需要设置任何东西就可以工作,只需要简单运行测试。

Solidityconsole

当你运行测试时,日志输出将显示:

$yarnhardhattestTokencontractDeployment?Shouldsettherightowner?ShouldassignthetotalsupplyoftokenstotheownerTransactionsSenderbalanceis1000tokensTryingtosend50tokensto0xead9c93b79ae7c1591b1fb5323bd777e86e150d4Senderbalanceis50tokensTryingtosend50tokensto0xe5904695748fe4a84b40b3fc79de2277660bd1d3?Shouldtransfertokensbetweenaccounts(373ms)?Shouldfailifsenderdoesn’thaveenoughtokensSenderbalanceis1000tokensTryingtosend100tokensto0xead9c93b79ae7c1591b1fb5323bd777e86e150d4Senderbalanceis900tokensTryingtosend100tokensto0xe5904695748fe4a84b40b3fc79de2277660bd1d3?Shouldupdatebalancesaftertransfers(187ms)5passing(2s)

查看文档来了解更多关于这个功能的信息。

7.部署到真实的网络

一旦准备好与其他人分享应用程序,你可能想做的是部署到一个实时网络。这样其他人就可以访问到。

处理真金白银的以太坊网络被称为主网(mainnet),还有其他不处理真金白银的网络,但确实能很好地模拟真实世界的场景,这些被称为测试网(testnet),以太坊有多个测试网:Ropsten、Kovan、Rinkeby_和_Goerli。

在软件层面,部署到testnet和部署到mainnet是一样的。唯一不同的是连接的网络。

由于我们使用了hardhat-deploy插件,并且我们已经编写了部署脚本,现在只需要对部署到的网络进行一些配置,就可以部署到真实网络中。

正如我们的部署部分所解释的那样,你可以执行yarnhardhatdeploy,但它只部署在内存中模式的默认的网络中,输出如下:

Nothingtocompiledeploying"Token"(tx:0x259d19f33819ec8d3bd994f82912aec6af1a18ec5d74303cfb28d793a10ff683)...:deployedat0x5FbDB2315678afecb367f032d93F642f64180aa3with592983gasDonein3

}leturi=process

if(!uri||uri===''){if(networkName==='localhost'){return'http://localhost:8545';}return'';}if(uri

returnuri;}exportfunctiongetMnemonic(networkName?:string):string{if(networkName){constmnemonic=process

}constmnemonic=process

returnmnemonic;}exportfunctionaccounts(networkName?:string):{mnemonic:string}{return{mnemonic:getMnemonic(networkName。;}

然后我们可以修改hardhat.config.ts文件,使其包含以下内容。

import{HardhatUserConfig}from'hardhat/types';import'hardhat-deploy';import'hardhat-deploy-ethers';import{node_url,accounts}from'./utils/network';constconfig:HardhatUserConfig={solidity:{version:'0.7.6',},networks:{rinkeby:{url:node_url('rinkeby'),accounts:accounts('rinkeby'),},},namedAccounts:{deployer:0,tokenOwner:1,},paths:{sources:'hide',},};exportdefaultconfig;

最后,我们需要设置环境变量,让utils/networks.ts从.env中自动读取。

创建一个.env,在其中写上你自己的alchemyapi键和rinkeby的助记词。

ETH_NODE_URI_RINKEBY=https://eth-rinkeby.alchemyapi.io/v2/MNEMONIC_RINKEBY=forrinkeby>

我们使用的是Alchemy,你可以使用任何其他指向以太坊节点或网关的URL。

要在Rinkeby上部署,你需要把rinkeby-ETH发送到要进行部署的地址。你可以从水龙头那里获得一些ETH的测试网。

你可以通过以下链接获得一些ETH,用于其他测试网。

Kovan水龙头

Rinkeby水龙头

Goerli水龙头

然后运行:

yarnhardhat--networkrinkebydeploy

如果一切顺利,你应该看到这样的内容:

Nothingtocompiledeploying"Token"(tx:0xb40879c3162e6a924cfadfc1027c4629dd57ee4ba08a5f8af575be1c751cd515)...:deployedat0x8bDFEf5f67685725BC0eD9f54f20A2A4d3FEDA98with475842gas

你还会看到在deployments/rinkeby文件夹中创建了一些文件。

最值得注意的是,你会看到deployments/rinkeby/Token.json,其中包含了你部署的合约信息,包括addres、abi以及用于创建合约的solidity输入。

然后你可以用sourcify或etherscan来验证它。

对于sourceify,你可以执行以下操作:

yarnhardhat--networkrinkebysourcify

这应该给你以下输出。

verifyingToken(0x8bDFEf5f67685725BC0eD9f54f20A2A4d3FEDA98onchain4)...=>contractTokenisnowverified

对于etherscan,你可以执行以下工作(注意,你也可以通过env变量ETHERSCAN_API_KEY指定api密钥):

yarnhardhat--networkrinkebyetherscan-verify--api-key

然后你应该看到。

verifyingToken(0x8bDFEf5f67685725BC0eD9f54f20A2A4d3FEDA98)...waitingforresult...=>contractTokenisnowverified

本翻译由CellNetwork赞助支持。

来源:https://github.com/wighawag/tutorial-hardhat-deploy

参考资料

登链翻译计划:https://github.com/lbc-team/Pioneer

翻译小组:https://learnblockchain.cn/people/412

Tiny熊:https://learnblockchain.cn/people/15

这个安装说明安装git:https://www.atlassian.com/git/tutorials/install-git

node版本管理器(nvm):http://github.com/creationix/nvm

Git的Windows安装程序:https://git-scm.com/download/win

此处:https://nodejs.org/dist/latest-v12.x

这里:https://github.com/nodesource/distributions#debinstall

nvm:http://github.com/creationix/nvm

相同的安装说明:#windows

这里:https://nodejs.org/en/download/releases/

yarn:yarnpkg.com

创建任务:https://hardhat.org/guides/create-task.html

ERC20:https://learnblockchain.cn/tags/ERC20

Mocha:https://mochajs.org/

Chai:https://www.chaijs.com/

Wafflechaimatchers:https://getwaffle.io/

文档:https://hardhat.org/hardhat-network/

Alchemy:https://alchemyapi.io/?r=7d60e34c-b30a-4ffa-89d4-3c4efea4e14b

Kovan水龙头:https://faucet.kovan.network/

Rinkeby水龙头:https://faucet.rinkeby.io/

Goerli水龙头:https://goerli-faucet.slock.it/

CellNetwork:https://www.cellnetwork.io/?utm_souce=learnblockchain

免责声明:作为区块链信息平台,本站所发布文章仅代表作者个人观点,与链闻ChainNews立场无关。文章内的信息、意见等均仅供参考,并非作为或被视为实际投资建议。

本文来源于非小号媒体平台:

登链社区

现已在非小号资讯平台发布105篇作品,

非小号开放平台欢迎币圈作者入驻

入驻指南:

/apply_guide/

本文网址:

/news/9847358.html

免责声明:

1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险

2.本文版权归属原作所有,仅代表作者本人观点,不代表非小号的观点或立场

上一篇:

盘点零知识证明代表性项目:如何影响和塑造区块链生态系统?

郑重声明: 本文版权归原作者所有, 转载文章仅为传播更多信息之目的, 如作者信息标记有误, 请第一时间联系我们修改或删除, 多谢。

大币网

[0:15ms0-3:397ms