当前位置:网站首页>3. "Create your own NFT collections and publish a Web3 application to show them" cast NFT locally
3. "Create your own NFT collections and publish a Web3 application to show them" cast NFT locally
2022-07-01 19:05:00 【Han Ru_】
Write our entry contract .
First, let's do a little cleaning up .
We want to remove some automatically generated but less needed code . We have to write it ourselves .
First look at the directory structure :

Delete first test Under folder sample-test.js file .

Then delete scripts In the catalog sample-script.js file ,

Finally delete contracts In the catalog Greeter.sol.

Be careful , Just delete the file , Do not delete the folder where these files are located !
Now? , stay VSCode Open project in , Let's start writing NFT contract . If you have never written a smart contract , Please don't worry . Follow our tutorial . If you still don't understand, you can Google or ask questions on the message board .
stay contracts Under the table of contents , Create a file named :MyEpicNFT.sol. In the use of Hardhat The file structure is very important , So be careful here !

Be careful : I suggest you download VSCode Of Solidity Expand , It provides good syntax highlighting .

Here we start with a very basic contract , From shallow to deep .
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.1;
import "hardhat/console.sol";
contract MyEpicNFT {
constructor() {
console.log("This is my NFT contract. Whoa!");
}
}
Be careful : Sometimes VSCode Itself will throw an untrue error , for example , It may be in hardhat Import the underline and say it doesn't exist . These may be because of your overall situation Solidity The compiler is not set locally . If you don't know how to solve this problem , These can be ignored for the time being . In addition, I advise you not to use VSCode Terminal , Use your own separate terminal ! If the compiler is not set , Sometimes VSCode The terminal will have problems .
Let's explain line by line here :
// SPDX-License-Identifier: UNLICENSED
Just a comment . It is called “SPDX License identifier ”, You can Here, Read more about .
pragma solidity ^0.8.1;
This is what we want the contract to use Solidity The version of the compiler . It means :“ When running this program , I just want to use version 0.8.1 Or higher, but not higher than 0.9.0 Of Solidity compiler . Be careful , Please make sure that hardhat.config.js The compiler is set accordingly ( for example 0.8.1).
import "hardhat/console.sol";
Hardhat It allows us to execute some console logs in the contract . Debugging smart contracts is actually challenging , This is a Hardhat One of the relatively easy ways for us .
contract MyEpicNFT {
constructor() {
console.log("This is my NFT contract. Whoa!");
}
}
Smart contracts are a bit like those in other languages class . If we initialize this contract for the first time , That constructor will run and print out this line . You can, too 、 You can modify the printed line , Change to something else you want to print .
How do we run it ?
Now we have a smart contract ! however , We don't know whether it works . We actually need :
- Compile it .
- Deploy it to our local blockchain .
- Once it is deployed there ,console.log It will run .
We will write a custom script to handle this for us 3 A step .
Get into scripts And create a directory called run.js The file of .
This is a run.js What's in it :
const main = async () => {
const nftContractFactory = await hre.ethers.getContractFactory('MyEpicNFT');
const nftContract = await nftContractFactory.deploy();
await nftContract.deployed();
console.log("Contract deployed to:", nftContract.address);
};
const runMain = async () => {
try {
await main();
process.exit(0);
} catch (error) {
console.log(error);
process.exit(1);
}
};
runMain();
How it works ?
Be careful :VSCode Ethereum may be automatically imported . We don't need to import ether .
Let's explain the above code line by line .
const nftContractFactory = await hre.ethers.getContractFactory("MyEpicNFT");
This will actually compile our contract and generate the necessary file directories in the directory we need to use the contract artifacts . Check it after running .

const nftContract = await nftContractFactory.deploy();
What's going on here is ,Hardhat Will create a local Ethereum network for us , But just for this contract . then , After the script is completed , It will destroy the local network . therefore , Every time you run a contract , It will be a new blockchain . What's the point ? It's a bit like refreshing your local server every time , So always start from scratch , This makes it easy to debug errors .
await nftContract.deployed();
We will wait until our contracts are officially mined and deployed to our local blockchain !hardhat In fact, a fake is created on your machine “ The miners ”, Try to imitate the actual blockchain .
Our constructor constructor Run at actual full deployment !
console.log("Contract deployed to:", nftContract.address);
Last , Once the deployment is complete , Will give us the address of the deployment contract nftContract.address . This address is the way we really find the contract on the blockchain . But now on our local blockchain , Only us .
however , There are actually millions of contracts on the blockchain . therefore , This address allows us to easily access the contracts we are interested in ! In the next few classes , When we deploy the contract to the actual blockchain , This can come in handy .
function .
Before running this function , Please ensure that the hardhat.config.js Medium solidity: “0.8.4” Change to solidity: “0.8.1”.

Let's run it ! Open your terminal and run it :
npx hardhat run scripts/run.js
You can see what runs in the contract console.log , The printed contract address !!! This is what I got :

Hardhat & HRE
In these code blocks , You will notice that we often use hre.ethers, but hre Never imported anywhere ? So why can it be used ?
Go straight to see it Hardhat file , You will notice this :
Hardhat Runtime Environment, Or abbreviation HRE, Is a containing Hardhat Running tasks 、 The object of all functions exposed when testing or scripting . actually ,Hardhat Namely HRE.
So what does that mean ? ok , Each time you run one with npx hardhat At the beginning of the terminal command , You use the code specified hardhat.config.js State build this hre object ! This means that you will never have to actually import a file of some kind , for example :
const hardhat = require("hardhat")
边栏推荐
- R language ggplot2 visualization: gganimate package transition_ Time function to create dynamic scatter animation (GIF), shadow_ The wake function configures the gradient falloff tailing effect of the
- 精益思想:来源,支柱,落地。看了这篇文章就懂了
- 太爱速M源码搭建,巅峰小店APP溢价寄卖源码分享
- 解决方案:可以ping别人,但是别人不能ping我
- 数据仓库(四)之ETL开发
- Leetcode-160 intersecting linked list
- 华为联机对战服务玩家掉线重连案例总结
- Livedata postvalue will "lose" data
- AI 训练速度突破摩尔定律;宋舒然团队获得RSS 2022最佳论文奖
- Halcon图片标定,使得后续图片处理过后变成与模板图片一样
猜你喜欢

力扣每日一题-第32天-589.N×树的前序遍历

Salesmartly has some tricks for Facebook chat!

如何使用物联网低代码平台进行个人设置?

Viewing the whole ecology of Tiktok from a macro perspective

隐私沙盒终于要来了
![[AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?](/img/66/674a06d8e45a31ae879b81554ef373.png)
[AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?

Leetcode-128 longest continuous sequence

Leetcode-141 circular linked list

Halcon图片标定,使得后续图片处理过后变成与模板图片一样

华为云专家详解GaussDB(for MySQL)新特性
随机推荐
微服务大行其道的今天,Service Mesh是怎样一种存在?
Principal component calculation weight
透过华为军团看科技之变(六):智慧公路
摄像头的MIPI接口、DVP接口和CSI接口[通俗易懂]
斯坦福、Salesforce|MaskViT:蒙面视觉预训练用于视频预测
ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing
ES6 summary "suggestions collection" of array methods find(), findindex()
Lumiprobe 生物分子定量丨QuDye 蛋白定量试剂盒
docker 部署mysql8.0
ETL development of data warehouse (IV)
【快应用】Win7系统使用华为IDE无法运行和调试项目
如何使用物联网低代码平台进行个人设置?
Golang error handling
LiveData postValue会“丢”数据
Usage and underlying implementation principle of PriorityQueue
1. "Create your own NFT collections and publish a Web3 application to show them." what is NFT
The R language uses the tablestack function of epidisplay package to make statistical summary tables (descriptive statistics based on the grouping of target variables, hypothesis testing, etc.). If th
如何在自有APP内实现小程序实现连麦直播
Evaluation of 6 red, yellow and black list cameras: who is the safest? Who has good picture quality? From now on, let you no longer step on thunder
ES6数组方法find()、findIndex()的总结「建议收藏」