hardhat使用命令:npx hardhat run scripts/deploy.js --network XXXnet,既可以把合约部署到主网(mainnet)、测试网(ropsten、rinkey),还可以部署到本地网络(ganache,hardhat-test)。比如,npx hardhat run scripts/deploy.js --network ganache,就可以把合约部署到ganache,下面以onehat工程为例,将token.sol合约部署到ganache。

1、配置ganache

    设置ganache的IP为127.0.0.1,端口为9545,然后重启ganache

图(1) 将ganache端口改为9545,然后重启ganache

2、修改hardhat.config.js

    修改onehat/hardhat.config.js文件,添加 ganache网段和账户,如下所示。
    //hardhat.config.js

/*** @type import('hardhat/config').HardhatUserConfig*/
require("@nomiclabs/hardhat-waffle");//选取ganache下的4个账户的私钥
const PRIVATE_KEY1 = "0dab...4e1c";
const PRIVATE_KEY2 = "ff73...a9e6";
const PRIVATE_KEY3 = "d7b4...5c2d";
const PRIVATE_KEY4 = "28d8...7163";module.exports = {solidity: "0.6.12",networks: {ganache: {url: `http://127.0.0.1:9545`,accounts: [`0x${PRIVATE_KEY1}`,`0x${PRIVATE_KEY2}`,`0x${PRIVATE_KEY3}`,`0x${PRIVATE_KEY4}`]},// ropsten: {//   url: `https://eth-ropsten.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,//   accounts: [`0x${ROPSTEN_PRIVATE_KEY}`]// },// rinkeby: {//   url: `https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,//   accounts: [`0x${rinkeby_PRIVATE_KEY}`]// },}
};

图(2) 修改hardhat.config.js里的ganache网段和私钥

3、部署合约

3.1 智能合约.sol

    // onehat/contracts/Token.sol

//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;// This is the main building block for smart contracts.
contract Token {// Some string type variables to identify the token.// The `public` modifier makes a variable readable from outside the contract.string public name = "My Hardhat Token";string public symbol = "MBT";// 固定发行量,保存在一个无符号整型里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.*/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];}
}

3.2 部署脚本.js

    // onehat/scripts/1_deploy_token.js

async function main() {//使用hardhat.config.js network字段里指定的网段//比如,npx hardhat run scripts/deploy.js --network ganache,表示使用ganache网段//      npx hardhat run scripts/deploy.js --network rinkeby,表示使用rinkeby网段//      npx hardhat run scripts/deploy.js --network ropsten,表示使用ropsten网段//  ethers.getSigners是根据--network参数来获取对应的网段,//  若没有填写--network,则使用hardhat自带的测试网络: hardhat-test//  比如,npx hardhat run scripts/deploy.js ,则表示使用 hardhat-test网段(端口为8545)const [deployer] = await ethers.getSigners();console.log("Deploying contracts with the account:", deployer.address);console.log("Account balance:", (await deployer.getBalance()).toString());const Token = await ethers.getContractFactory("Token");const token = await Token.deploy();console.log("Token address:", token.address);}main().then(() => process.exit(0)).catch((error) => {console.error(error);process.exit(1);});

3.3 测试脚本.js

    // onehat/test/token.js

// We import Chai to use its asserting functions here.
const { BigNumber } = require("@ethersproject/bignumber");
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 hardhatToken;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.hardhatToken = await Token.deploy();});// 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 object. 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 hardhatToken.owner()).to.equal(owner.address);});it("Should assign the total supply of tokens to the owner", async function () {const ownerBalance = await hardhatToken.balanceOf(owner.address);expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);});});describe("Transactions", function () {it("Should transfer tokens between accounts", async function () {// Transfer 50 tokens from owner to addr1await hardhatToken.transfer(addr1.address, 50);const addr1Balance = await hardhatToken.balanceOf(addr1.address);expect(addr1Balance).to.equal(50);// Transfer 50 tokens from addr1 to addr2// We use .connect(signer) to send a transaction from another accountawait hardhatToken.connect(addr1).transfer(addr2.address, 50);const addr2Balance = await hardhatToken.balanceOf(addr2.address);expect(addr2Balance).to.equal(50);});it("Should fail if sender doesn’t have enough tokens", async function () {const initialOwnerBalance = await hardhatToken.balanceOf(owner.address);// Try to send 1 token from addr1 (0 tokens) to owner (1000 tokens).// `require` will evaluate false and revert the transaction.await expect(hardhatToken.connect(addr1).transfer(owner.address, 1)).to.be.revertedWith("Not enough tokens");// Owner balance shouldn't have changed.expect(await hardhatToken.balanceOf(owner.address)).to.equal(initialOwnerBalance);});it("Should update balances after transfers", async function () {const initialOwnerBalance = await hardhatToken.balanceOf(owner.address);init1 = BigNumber.from(initialOwnerBalance);init1 = init1.sub(150);initiBalance = init1.toString();// Transfer 100 tokens from owner to addr1.await hardhatToken.transfer(addr1.address, 100);// Transfer another 50 tokens from owner to addr2.await hardhatToken.transfer(addr2.address, 50);// Check balances.const finalOwnerBalance = await hardhatToken.balanceOf(owner.address);final1 = BigNumber.from(finalOwnerBalance);finalBalance = final1.toString();expect(initiBalance).to.equal(finalBalance);const addr1Balance = await hardhatToken.balanceOf(addr1.address);expect(addr1Balance).to.equal(100);const addr2Balance = await hardhatToken.balanceOf(addr2.address);expect(addr2Balance).to.equal(50);});});
});

3.4 部署到ganache

    使用npx命令运行1_deploy_token.js脚本,即可在ganache里部署合约

## 进入工程目录
cd onehat
npx hardhat run scripts/1_deploy_token.js --network ganache

    效果如下:

图(3) npx部署合约成功

    使用hardhat,部署token.sol合约到ganache网络(127.0.0.1:9545) 成功。

3.5 在ganache里测试合约

    使用npx命令运行token.js脚本,即可在ganache里测试合约

npx hardhat test test/token.js --network ganache

4、 完整工程

    onehat工程地址: onehat案例 提取码:y5t1

使用hardhat将合约部署到ganache相关推荐

  1. 三:将智能合约部署到ganache测试网

    三:将智能合约部署到ganache测试网 文章目录 三:将智能合约部署到ganache测试网 实验目的 实验原理 开始条件 实验过程 实验步骤 相关官方知识库 下一章内容: 实验目的 掌握将智能合约部 ...

  2. 四:调用部署在ganache的智能合约

    四:调用部署在ganache的智能合约 文章目录 四:调用部署在ganache的智能合约 实验目的 实验原理 开始条件 实验过程 实验步骤 相关官方知识库 下一章内容: 如果朋友有代码,工具,使用流程 ...

  3. 如何使用hardhat进行合约uups模式升级

    id:BSN_2021 公众号:BSN研习社 背景:在开发或维护solidity语言的智能合约时,经常会因为业务逻辑变动而变动合约内的逻辑,这就要考虑在不影响以前智能合约中已上链的数据的同时,修改或扩 ...

  4. 将智能合约部署到Rinkeby测试链上

    引言 在上一篇文章中<快速上手第一个智能合约中>,我们介绍了如何编写与运行我们的第一个智能合约.但那只是将合约运行在了浏览器的区块链虚拟环境中,与区块链还是有一定的区别,另外也无法被其它人 ...

  5. CTF中智能合约部署交互基础

    0x01 前言 Solidity在以太坊中是编写智能合约最受欢迎的语言,一般的CTF竞赛中的智能合约方向的题目都是以solidity语言编写的智能合约. 为什么写这一篇文章,主要是因为在接触智能合约类 ...

  6. 智能合约部署Error: exceeds block gas limit undefined

    在学习区块链时,我们按照某些文章的教程,使用 Browser-solidity 在 Go-Ethereum上进行智能合约部署时,可能会出现Error: exceeds block gas limit ...

  7. 超级账本Fabric2.x 如何将智能合约部署到通道

    如何将智能合约部署到通道--部署Fabric测试网络的实例 使用系统版本:Ubuntu 18.04 提示:任何命令错误都可以试试加sudo提升权限!!! 参考文章:官方文档 一.启动网络 1.1 进入 ...

  8. HyperLedger超级账本智能合约部署问题

    HyperLedger超级账本智能合约部署问题 报错:Error: could not assemble transaction: ProposalResponsePayloads do not ma ...

  9. 以太坊笔记 使用 Browser-solidity 在 Go-Ethereum1.7.2 上进行简单的智能合约部署

    转载自:https://mshk.top/2017/11/browser-solidity-go-ethereum-1-7-2/ 目录 Contents [hide] 目录 1.基本概念 1.1.什么 ...

最新文章

  1. android源码编译 简书,android学习笔记之源码编译
  2. 左右侧滑菜单功能的实现
  3. mysql学习【第14篇】:pymysql
  4. 【数据分析】近10年学术论文的数据分析!
  5. referer htttp headers 统计信息 防盗链
  6. CodeForces - 222C Reducing Fractions(唯一分解定理)
  7. HDU - 1358 Period(KMP的next数组求最小循环节)
  8. ueditor php 网络链接错误,ueditor使用editor.execCommand( 'link', {})插入链接无效的问题...
  9. BZOJ1045 HAOI2008糖果传递(贪心)
  10. np.percentile获取中位数、百分位数
  11. Hibernate学习(一)创建数据表
  12. css table 合并单元格
  13. 我来告诉你2019新版微信转发语音消息的方法!就是这么简单
  14. 高薪程序员面试题精讲系列82之说一下SQL查询语句的执行顺序详解-原理篇(下)
  15. Swift3.0知识点:高度模仿斗鱼TV(一)
  16. Mac苹果键盘多个按键没响应该如何解决呢
  17. 在vue里面使用eval()函数
  18. 解谜:为何用了9-Patch背景图后自带Padding属性?
  19. 基于UML的软件开发过程
  20. Pixel 4刷机常见问题指南(Android 11 211001版本可用!)

热门文章

  1. GPS定位及获取卫星参数实例整理
  2. 整理经济学人词频表(词频分割过程)
  3. Android Canvas进阶之自定义View实现Splash的旋转、扩散聚合、水波纹特效
  4. 继 Linux 上火星之后,树莓派计算机飞往国际空间站
  5. 域名、dns、服务器、IP、主机名
  6. 压缩图片大小的java代码_java按比例压缩图片的源代码,用java如何把图片处理到指定大小...
  7. python手撸桌面计算器
  8. 2.1 八大类50条小红书爆款标题文案【玩赚小红书】
  9. linux windows 垃圾清理,windows垃圾清理
  10. 在Ubuntu20.04中安装edb1.3.0