当前位置:网站首页>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")
边栏推荐
- [AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?
- Principal component calculation weight
- After studying 11 kinds of real-time chat software, I found that they all have these functions
- Technology implementation and Architecture Practice
- Leetcode-83 delete duplicate elements in the sorting linked list
- R language epidisplay package ordinal or. The display function obtains the summary statistical information of the ordered logistic regression model (the odds ratio and its confidence interval correspo
- Memo - about C # generating barcode
- 6款红黄黑榜摄像头评测:谁最安全?谁画质好?从此让你不再踩雷
- Write an open source, convenient and fast database document query and generation tool with WPF
- PriorityQueue的用法和底层实现原理
猜你喜欢

Lumiprobe lumizol RNA extraction reagent solution

斯坦福、Salesforce|MaskViT:蒙面视觉预训练用于视频预测

前4A高管搞代运营,拿下一个IPO

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

Privacy sandbox is finally coming

Lumiprobe non fluorescent alkyne EU (5-ethynyluridine)

After studying 11 kinds of real-time chat software, I found that they all have these functions

Facebook聊单,SaleSmartly有妙招!

How to use the low code platform of the Internet of things for personal settings?

Must see, time series analysis
随机推荐
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
ETL development of data warehouse (IV)
Clean up system cache and free memory under Linux
前4A高管搞代运营,拿下一个IPO
搭建一個通用監控告警平臺,架構上需要有哪些設計
Lumiprobe biomolecular quantification - qudye Protein Quantification Kit
The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise
Lumiprobe bifunctional crosslinker sulfo cyanine 5 bis NHS ester
Go Technology Daily (2022-02-14) - go language slice interview real questions 8 consecutive questions
Improve yolov5 with gsconv+slim neck to maximize performance!
ES6数组方法find()、findIndex()的总结「建议收藏」
app发版后的缓存问题
Lumiprobe非荧光炔烃丨EU(5-乙炔基尿苷)
golang 错误处理
解决方案:可以ping别人,但是别人不能ping我
R language uses the aggregate function of epidisplay package to divide numerical variables into different subsets based on factor variables, and calculate the summary statistics of each subset
洞态在某互联⽹⾦融科技企业的最佳落地实践
Lumiprobe lumizol RNA extraction reagent solution
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
ES6数组去重的三个简单办法