Back to all courses
DeepMind recently released a new type of Transformer called the Perceiver IO, which was able to achieve state of the art accuracy across multiple data types (text, images, point clouds, and more). In this episode of the AlphaCare series, I'll explain how Perceiver works, and how we used it to improve accuracy scores for Cardiac video data. The EchoNet dataset was recently made public by Stanford University, and it contains 10K privatized heart videos from patients. We'll also discuss why Transformer networks work so well, and how by using 2 key features (Cross attention & positional embeddings), the Perceiver improved on all variants of Transformers. Get hype!
I'm a technologist on a mission to spread data literacy. Artificial Intelligence, Mathematics, Science, Technology, I simplify these topics to help you understand how they work. Using this knowledge you can build wealth and live a happier, more meaningful life. I live to serve this community. We are the fastest growing AI community in the world!
This article demonstrates how to mint an NFT and thoroughly discusses the process using the Ethereum blockchain's polygon side chain.
This is the fourth article about AlphaCare. You can take a looks at the first three before we move on. The list of them is below:
This article includes a sample genome to help you better understand its fundamentals. This genome was sequenced using the 23andMe service and minted on the Ethereum blockchain using a polygon from the OpenSea marketplace. Although it is paid software, there is no need to purchase it because we will only use it for this demo.
First of all, the revolution in NFT is just getting started. Pixel art and images of dogs and cats are currently regarded as NFTs. However, in the future, everything will be converted to an NFT, including voting rights, a variety of apps, entire corporations, physical assets like homes and vehicles, and personhood.
In light of this, this article focuses on leveraging these technologies to create your own NFT for free and discusses how we might utilize them in the healthcare industry to support doctors by preserving and providing patient data.
The picture below shows a sample genome, which is visualized using python. Whoever has this NFT will receive the actual genome txt file as an unlock. It has an image listed on OpenSea.
We will cover a lot of ground in this guide. We'll also examine how RapidAPI Hub may be used to search for various NFTs visually. So I want to start out by explaining what NFTs are.
NFT is a non-fungible token, meaning it can neither be replaced nor interchanged because it has unique properties.
Fungible assets and tokens are items that can be exchanged one for one. For example, a dollar, a bitcoin, and an ether are all fungible. That means I can exchange dollar for dollar, a Bitcoin for a Bitcoin, and so on.
Semi-fungible assets are those that can be exchanged one for one but are not necessarily unique. For example, I could have a seat A ticket, and you could have a seat B ticket. Because they are different seats, they are non-fungible.
They are, however, interchangeable if they are for the same seat. So consider fungible to be a synonym for inter-interchangeable.
Non-fungible means that it cannot be exchanged one for one. That means there is only one version of this. Because there is only one Mona Lisa, it is a non-fungible painting.
As we are creating it, the metaverse consists of Crypto, Web3, and Virtual Reality. All of these technologies contribute to creating this new universe within the internet.
We require a method for granting patent protection to a single piece of digital property, which is data. Data can now be replicated infinite times. This implies that I can repeatedly reproduce any image, guide, text, or audio I have.
However, an NFT gives it a special token and declares that whoever holds the token also holds this particular piece of the data. And because of that, this idea is quite difficult to comprehend. Yes, it is really contemporary.
This idea of owning digital property, which is typically a single asset like land or a painting, has never existed before. This is definitely non-fungible because land cannot be replicated, but data can. However, a piece of digital property gains the same uniqueness thanks to an NFT.
There is an entire ecosystem built around this. NFTs are utilized for domain infrastructure, such as the Ethereum Name Service. It is utilized for in-game purchases, asset items, armor, swords, and marketplaces for games like OpenSea. As NFT, these can be exchanged equally.
NFTs are here to stay; this is not hype or some sort of passing fad—we are simply at the very beginning. NFTs are governed by code rather than by lawyers, similar to the proof of ownership. Lawyers only apply to a certain jurisdiction, whereas NFTs are governed by code globally. Because gas is so expensive, minting NFTs costs a lot of money.
NFTs are still far less expensive than a lawyer would be, and they are also interoperable between various institutions. So, in theory, you could exchange my genes for a work of art at the NFT. However, using NFTs, you can perform things that are ordinarily impossible.
The fact that creators, like NFT artists, will be allowed to keep the ownership of some piece of NFT art is one of the most fascinating aspects of this whole thing. As a result, they are the sole owners of the revenue and are not required to split it with the platform.
There is a way to mint an NFT in which the creator receives a % royalty on each sale. This can be given programmatically in the initial minting contact, so what are some examples of NFTs?
In 2017, George Hotz created an NFT called Cryptokitties. Nobody, though, discussed it as much as they are doing now.
NFTs are now widely used for several reasons, but mostly because using the Ethereum blockchain is much simpler now, thanks to so-called "Layer 2" solutions. Nevertheless, CryptoKitties are digital collectibles that feature only one type of cat.
Twitter's creator, Jack Dorsey, created an NFT of his very first tweet. It is sold for a ludicrously high price.
Similarly, the musician Grimes sold her music videos on the niftygateway NFT marketplace. You can see a lot of her NFTs and they're all priced in USD.
These are only a few instances, but the opportunity to offer patients control over their health data is what I find most fascinating about NFTs. such as biomedical information, test results, biomarkers, images from medical imaging, etc. If you convert it to an NFT and sell it, you can still keep ownership of it.
As more institutions, academics, hospitals, and clinics use your NFT, the more they will be able to resell it to their provider and partner networks, increasing the patient's earnings. So, this might be considered a passive source of income.
Aimedis Blockchain is a recent blockchain that is used as an example below. They want to establish a market for NFTs with a focus on health. Patients can create NFTs using their health records. Numerous health-related items can be converted into NFTs, which can then be purchased by various providers and given to the patient.
Indeed, discussing NFTs would be incomplete without including Ethereum. The second most well-known blockchain after Bitcoin is Ethereum. In computer science, Ethereum is a shared-state, transactional singleton machine that is cryptographically secure. Now, let's clarify what that means.
This indicates that it is a digital currency that employs mathematical algorithms to make it nearly impossible to cheat the system. That entails producing two tokens of the same kind. Instead of relying on the trust of a third party, math is used to demonstrate trust.
Given that it is a state machine, every transaction will change the state of the network as a whole.
Millions and millions of transactions occur inside each state, and each of these transactions is organized into a block. A mining validation procedure is carried out each time a transaction takes place to ensure it is valid
You may find the proof of work algorithm below. Ethereum currently uses proof of work mining. Since it's quite intense, we won't discuss it more.
There are two types of Ethereum accounts:
Externally owned accounts have no accompanying code and are managed via private keys. Contract accounts have a code attached to them and are governed by that code.
It's critical to comprehend the key distinction between externally owned accounts and contract accounts.
By creating and signing a transaction with its private key, an externally owned account can send messages to other externally owned accounts OR to other contract accounts.
A message between two accounts that the same person does not own is simply a value transfer. A message sent from an externally owned account to a contract account, on the other hand, activates the contract account's code, allowing it to perform a variety of actions (e.g. transfer tokens, write to internal storage, mint new tokens, perform some calculations, create new contracts, etc.).
Unlike externally owned accounts, contract accounts cannot initiate new transactions on their own. Contract accounts are only permitted to respond to other transactions by firing their own transactions (from an externally owned account or another contract account).
The Ethereum virtual machine is a computer, but not just any computer. Because it resembles a hydra, it is an unstoppable, un-censorable computer. If you remove the head, three more will grow back. It is not a server; it is a network. It has a global presence spanning tens of thousands of nodes.
With this, we can submit some code to a service similar to Heroku that is decentralised and unstoppable. Ethereum might be compared to a computer, and that computer is known as the Ethereum Virtual Machine. Its own bytecode language, memory, and storage are all present.
We use the solidity programming language, which compiles to bytecode, to create smart contracts. The Ethereum computer is an unstoppable machine; you can see a very high-level and detailed depiction below:
The Ethereum virtual machine processor will check that the data, for instance, system state, the quantity of computing gas you have left to pay for, etc., is available and accurate before performing a specific computation.
EVM will start a transaction that compiles and runs some code. It will process all of these calls recursively, much like a virtual computer, and has a stack, memory, and storage. This makes our ability to create unstoppable applications employing these smart contracts possible.
A developer put ERC-20 into practice a few years ago. On top of Ethereum, developers can build tokens using ERC-20. So, if you visit Coinbase or virtually any other exchange, you will see all of these tokens, most of which are based on Ethereum.
They have new names but are still Ethereum tokens. Ethereum is the foundation for all cryptocurrencies, enabling you to construct your own.
The protocol ERC-20 is widely used. As long as you adhere to a particular set of naming conventions, this specification enables you to construct tokens. A name, symbol, decimal, balance, sender address, or events for what happens when we transfer a token are all required for each token.
On the Ethereum website, you can see how to define all of the features necessary to generate a token by installing the Python package web3
, then creating the token according to the specifications put out in the spec.
As a reminder, this smart contract will exist on the Ethereum blockchain in perpetuity. After that, we can use the token however we choose.
More recently, another spec called ERC-721 defines a non-fungible token standard. This is what almost all NFTs are based on. Just like ERC-20, it has a set of methods that need to be implemented inside your smart contract to comply with that spec.
These methods are connected to NFT minting. Once again, we can see an illustration of how this operates thanks to the numerous applications, such as Cryptokitties, Ethereum Name Service, etc.
So that's the concept behind NFTs, which are mostly based on Ethereum. Additionally, there are blockchains like Solana that compete directly with Ethereum. However, I prefer Ethereum since it has been around the longest, has the most development activity, and has, in my opinion, the most intelligent developers working on it to improve continually.
Ethereum is not flawless and has a critical drawback. The issue is that it is congested. There are too many transactions, and it is very expensive to mint NFT on Ethereum. The network is gradually becoming slower and more crowded.
A group of programmers developed something known as a polygon to address this problem. By using Polygon, a Layer 2 solution, we may leverage the Ethereum network without having to deal with its expensive gas and lengthy transaction times. Polygon is an Ethereum Go fork that has undergone various changes to enable faster transaction processing at a cheaper gas cost.
Blockchain scaling typically has two options, the first of which is to attempt to scale the main chain. We refer to that as "Layer 1," and if we implement it, we must give up either scalability, security, or decentralisation. It goes by the name of Blockchain Telima.
Using a side chain, which runs on top of the main chain and offloads some of the work, is an alternative that reduces the strain on the main chain. By using strategies like sharding and switching to proof of stake from proof of work, the Ethereum developers are attempting to improve Layer 1 at the moment, which is E2.
A Layer 2 solution with a built-in blockchain is Polygon. Simply put, it enables users and developers to conduct quick and inexpensive transactions on the Ethereum blockchain utilizing its own infrastructure, token, user notes, and validator notes.
A lightning network is a name given to Bitcoin's Layer 2 for its quick transactions. We can develop solutions for Layer 2 in various approaches, including plasma, state channels, valium, optimistic rollups, zero knowledge rollups, and zero knowledge rollups.
We might discuss many different topics to explain how Layer 2 functions. The creator of Ethereum says, “In the short term, I just don't see rollups as being one choice among many things; I see them as the only choice”. So let's focus on rollup, especially which polygon is already used or will use more frequently in the future.
Rollups are solutions that execute as many transactions as they can outside the main Ethereum chain but subsequently send the transaction data to Layer 1. The type that is now receiving the most attention is known as a Zero-knowledge rollup (ZK-rollups).
These numerous transactions take place off the main Ethereum chain, on a different chain. Then, a validity proof that establishes the validity of these transactions is produced using cryptography. It is referred to as SNARK or a succinct non-interactive knowledge argument. The proof is then uploaded back on Layer 1 after it has been generated.
The ZK-rollup smart contract maintains the state of all transfers on Layer 2. Only the validity proof will be accepted for updating this state. As a result, all of these transactions take place on the polygon chain and are then collected into a small group of transactions that are subsequently recorded as evidence on the main chain.
The main chain then asserts that these transactions can demonstrate their validity even though they occur outside the main chain. The Ethereum main chain's security and the side chain's speed and throughput are combined to create "Layer 2" solutions. So that is how polygons function.
The Hermez team has been working on these ZK rollups. We can observe that L2 Hermes is quite affordable compared to Ethereum's high price on the website. We have validity proof for more than 2000 transactions per batch of processing.
The procedure demonstrates the generation of a zero-knowledge proof, which is subsequently posted to the main Ethereum chain to demonstrate the validity of these transactions. All of those transactions are valid on the main chain once Ethereum accepts them. So that's how the Layer 2 polygon solution functions. NFTs are based on Ethereum, which operates in the same manner.
NFTs, as I mentioned, can be created on various blockchains, with Ethereum being the most widely used. We'll visualize it using Python, and then we'll convert the picture or PNG file into an NFT. Additionally, we'll use a polygon to post it to the Ethereum blockchain.
Let's begin by launching my genome file. In essence, it consists of every single one of my genes, each of which has a location, a chromosome, an allele one, and an allele two. Using the AancestryDNA service, genotypes are sequenced by both of these alleles.
We want to visualize all of these features in a single image. So here's what we're going to do.
We're going to use Python to do this. I'll import pandas
and csv
. So let me run this code. We will use pandas
to read csv
files.
py
import pandas as pdimport csvpath = 'genome.txt'csv_file = "detail.csv"with open(path, "r") as txt_23andMe:# Skip the first 19 lines of the text file (just header information)for x in range(19):txt_23andMe.readline()in_txt = csv.reader(txt_23andMe, delimiter = '\t')with open(csv_file, "w") as csv_23andMe:out_csv = csv.writer(csv_23andMe)out_csv.writerows(in_txt)data_csv = pd.read_csv(csv_file)
Assume we want to combine both of those alleles into a single genotype to visualize it in a three-dimensional graph. Therefore, we will take that genotype and combine both features into a single column.
py
import pandas as pdimport csvpath = 'genome.txt'csv_file = "detail.csv"with open(path, "r") as txt_23andMe:# Skip the first 19 lines of the text file (just header information)for x in range(19):txt_23andMe.readline()in_txt = csv.reader(txt_23andMe, delimiter = '\t')with open(csv_file, "w") as csv_23andMe:out_csv = csv.writer(csv_23andMe)out_csv.writerows(in_txt)data_csv = pd.read_csv(csv_file)data_csv["genotype"] = data_csv["allele1"] + data_csv ["allele2"]data_csv.head()
Let me see what that looks like.
Here, we will add a new column called genotype that combines both alleles. We can also use SEABORN (statistical data visualization) to plot one of the alleles and see what it looks like.
py
import pandas as pdimport csvpath = 'genome.txt'csv_file = "detail.csv"with open(path, "r") as txt_23andMe:# Skip the first 19 lines of the text file (just header information)for x in range(19):txt_23andMe.readline()in_txt = csv.reader(txt_23andMe, delimiter = '\t')with open(csv_file, "w") as csv_23andMe:out_csv = csv.writer(csv_23andMe)out_csv.writerows(in_txt)data_csv = pd.read_csv(csv_file)data_csv["genotype"] = data_csv["allele1"] + data_csv ["allele2"]data_csv.head()import seaborn as snssns.hisplot(data_csv["allele1"])
It's a bar graph of all the collections of T, G, C, and A's, which is the language of DNA.
Now, we can also turn all of this into a scatter plot. Here is the code for doing that:
py
import re, seaborn as snsimport numpy as npfrom matplotlib import pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom matplotlib.colors import Listedcolormap# generate datax = data_csv["genotype" ]y = data_csv["chromosome"]z = data_csv["position"]# axes instancefig = plt.figure(figsize=(6,6))ax = Axes3D (fig)fig.add_axes (ax)# get colormap from seaborncmap = ListedColormap(sns.color_palette("husl", 256).as_hex())# plotsc = ax.scatter(x, y, 2, s=40, c=x, marker='o', cmap=cmap, alpha=1)ax.set_xlabel('genotype')ax.set_label('chromosome')ax.set_zlabel('position')#legendplt.legend(*sc.legend_elements(), bbox_to_anchor=(1.05,1), loc=2)#saveplt.savefig("scatter_hue",bbox_inches='tight')
We'll take the genotype
as the X coordinate. The chromosome
is the Y, the position
is a Z axis. Here is genotype presented in three-dimensional form.
This image will be saved as my genome on the desktop and converted into an NFT. So the first thing I want to do is create a new directory called polygon-nft
, then cd
into that directory, and install a tool called Hardhat.
To get started, let's create a new Hardhat sample project. Execute these commands:
sh
npm install --save-dev hardhat && npx hardhat
Hardhat is a toolkit that offers a number of tools to make Ethereum development simpler. We can use Hardhat with Polygon in a manner that is almost identical to how we would use Ethereum because Polygon is an Ethereum EVM compatible layer 2.
Once that process is finished, you'll have several new files in your project folder. Let's have a look at what we have by opening the complete project folder in the code editor of your choice. You ought to have a directory that seems as follows:
An example Greeter.sol
file can be found in the contracts
folder. A simple script file in the scripts folder generates and deploys the contract's code. It's really that simple. Our current test file validates that our contract can be deployed and called.
We won't use much of this, but it's a good starting point as we learn to incorporate Polygon into the mix.
We’ll need to get some MATIC tokens in our wallet to do anything. So, the first step is ensuring you have an Ethereum wallet. Simply go to Metamask’s website, install the extension and follow the process of creating a new wallet. Of course, if you already have a wallet, you can skip this step.
You must obtain your private key after creating your wallet. To deploy your NFT contract and communicate with the layer 2 chain, you will require this key. By selecting the three-dot menu icon next to your wallet account in the Metamask extension, you can export your private key:
Selecting Account Details will allow you to export your private key. When you possess the private key, you will perform two actions:
Create a file called .env
at the root of your polygon-nft
project and add this to it PRIVATE_KEY=YOUR_EXPORTED_PRIVATE_KEY
. Replace YOUR_EXPORTED_PRIVATE_KEY
with your actual private key.
In your project’s .gitignore
file, add a line that simply says .env
. This will ensure you don’t accidentally commit the .env
file to source control and expose your key.
We now need to add another dependency to our project to make it simpler to interact with these variables because we are using an environment variable file. Run the following command at the project directory's root:
sh
npm i dotenv
Let's retrieve some MATIC tokens from the testnet right away. Visit the testnet faucet by clicking here. You will choose the MATIC token and put your wallet address into the area provided.
You will be asked to confirm your submission. Once you do that, MATIC tokens will soon be available in your wallet.
Ok, now let’s update the hardhat.config.js
file so that it knows we’re using the Polygon network. At the top of that file above the first require
statement, add:
js
require('dotenv').config();const PRIVATE_KEY = process.env.PRIVATE_KEY;
This instructs the file to import our environment variables using the dotenv
package. The second line creates a variable that makes use of the environment variable for our private key that was saved in the file .env
.
Next, search the file for the module.exports
object. Probably all that will be included is a definition of the Solidity version. Let's substitute this code for everything in the module.exports
file:
js
require('dotenv').config();const PRIVATE_KEY = process.env.PRIVATE_KEY;module.exports = {defaultNetwork: 'matic',networks: {hardhat: {},matic: {url: 'https://rpc-mumbai.maticvigil.com',accounts: [PRIVATE_KEY]}},solidity: {version: '0.8.0',settings: {optimizer: {enabled: true,runs: 200}}},paths: {sources: './contracts',tests: './test',cache: './cache',artifacts: './artifacts'},mocha: {timeout: 20000}};
Although a lot is going on, things are not as bad as they seem. We are letting Hardhat know that we are utilizing Polygon, the location of the RPC address (the API that communicates with the network), and the location of our private key. Beyond that, only a few configurations aren't particularly crucial for you to comprehend.
Before we do anything else, it’d be good to test our configuration. Let’s deploy our sample Greeter.sol
contract to the Polygon testnet. Run the following:
sh
npx hardhat run scripts/sample-script.js --network matic
This specifies the network to use while pointing Hardhat to the script to execute. In hardhat.config.js
, the matic
network was defined. You should observe the following output in your terminal after a short while:
sh
Compiling 2 files with 0.7.3Compilation finished successfullyGreeter deployed to: 0x790a1c9a212A13Fce5C1cfA4904f18bD3540E1e8
This indicates that the configuration file is functioning as intended, even though your contract address will differ from mine.
Since we didn't need to, we skipped running our example test. Since we'll be completely changing the smart contract, we don't need to test it. We had to ensure that our hardhat.config.js
file was functioning as it should.
We’ll use Open Zeppelin to help us get started on our contract. Our NFT contract will be ERC-721 based. So, we need to install Open Zeppelin’s contract library. From your project directory in the terminal, run:
sh
npm install @openzeppelin/contracts
Create a new file inside the contracts
folder called NFT.sol
(or anything else you like as long as it has a .sol
extension). I'll paste the contract below and go over each line with you because it's going to be quite straightforward:
We will install the smart contract library known as open Zeppelin right now. For minting an NFT, we will construct a highly specialized smart contract. So reopen that and start a new script.
pragma solidity ^0.8.0;import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol";contract MyNFT is ERC721, Ownable { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private _tokenIds; mapping (uint256 => string) private _tokenURIs; constructor() ERC721("MyNFT", "MNFT") {} function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { _tokenURIs[tokenId] = _tokenURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; return _tokenURI; } function mint(address recipient, string memory uri) public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(recipient, newItemId); _setTokenURI(newItemId, uri); return newItemId; } }
Since we are leveraging Open Zeppelin’s ERC721 contract, we have less code to write. Let’s run through this.
The Solidity version that we're using is specified in the first line. We are utilizing the most recent version. The ERC-721 contract, which is the most crucial, is included in the following three lines together with the Open Zeppelin contracts that we require. It takes less time to build smart contracts when these contracts are written for us.
The next step is to define our contract class and giving it the very creative name of MyNFT
. Our class definition extends the existing class definitions of the ERC721 contract and the Ownable contract provided to us by Open Zeppelin.
Following that, we define some variables. Counters and Strings are tools that assist in counting and converting data to strings. Following that, we define a variable to store the next token ID. Finally, we have a token ID to token URI mapping.
With all of our variables defined and imports included, we can get down to business. We have a constructor that does nothing more than define the token name and symbol. Again, I'm being extremely creative with my token name MyNFT
and the symbol MNFT
.
The most recent Open Zeppelin update reveals that their ERC-721 contracts no longer include a setTokenURI
function. The decision appears to be aimed at lowering deployment gas costs for users who do not require that function. That function is required.
But that's fine. We can reintroduce it. That is what our first function accomplishes. The function _setTokenURI
accepts a token ID and a token URI and adds them to the mapping.
We can now return a token URI from our tokenURI
function as a result of this. This is significant because the token URI points to all of the NFT's metadata. That includes the asset's name, attributes, and the asset itself. We must ensure that the URI is both saved and accessible to anyone who is interested.
Finally, there is the mint
function. It performs exactly as stated. This function accepts a wallet address as well as a token URI. The token ID is incremented when the token URI is used in the _setTokenURI
function. The new token is delivered to the recipient's email address.
Before we can mint an NFT, we need to create an asset and pin it to IPFS. We will need to get this onto the IPFS network. We’ll use Pinata for this. Sign up for an account or log in. Once you’ve signed up for an account, head to the Pin Manager and upload your file.
When you upload it, you’ll see it in the Pin Manager table:
You must copy the IPFS CID for your file by clicking the copy button next to it. After you've copied it, save it somewhere safe for later use.
We've uploaded the asset, but we still need to add a JSON file containing the metadata for our NFT. This may appear difficult, but it is actually quite simple. In this post, I'll show you how to do it.
In a text editor, create a new file (this can be notepad or any other simple text editor on your computer). Add the following to that file:
json
{"name": "My NFT","description": "This is my NFT","image": "ipfs://QmQRDYPTprDPknn3zE2ZSpc8DjnUKfYztyaeMBYdR8GDdw"}
You can name your NFT whatever you want and provide any description you want. The image
property must point to the CID returned by the previously uploaded asset. You can copy it from the Pin Manager if you need it again. To ensure that the asset can be loaded from any IPFS gateway, we will format the asset URI as ipfs:/YOUR CID
.
Save the file as metadata.json
once you've finished. After you've saved it, return to the Pinata Pin Manager and upload the file. When you do this, you will receive an IPFS CID, which you should copy because it will be used when we mint our NFT.
We'll edit the sample-script.js
file in our scripts
folder to accomplish this. In fact, let's rename that file to 'deploy-script.js.' Replace everything in the file with this:
js
const hre = require('hardhat');async function main() {const NFT = await hre.ethers.getContractFactory('MyNFT');const nft = await NFT.deploy();await nft.deployed();console.log('NFT deployed to:', nft.address);}main().then(() => process.exit(0)).catch(error => {console.error(error);process.exit(1);});
To deploy this to the testnet, we need to update our hardhat.config.js
file again. Change the defaultNetwork
back to “matic”. Now, uncomment the matic section that we commented out earlier.
In your terminal, run the following command:
sh
npx hardhat run scripts/deploy-script.js --network matic
If everything goes as planned, your NFT contract will now be minted. The contract address will be displayed in your terminal output. Make a copy of that because we'll need it to make our first NFT.
To create a token, we'll write a new script. Create a file called mint-script.js
within the 'scripts' folder. Add the following to that file:
js
const hre = require('hardhat');async function main() {const NFT = await hre.ethers.getContractFactory('MyNFT');const URI = 'ipfs://YOUR_METADATA_CID';const WALLET_ADDRESS = 'YOUR_WALLET_ADDRESS';const CONTRACT_ADDRESS = 'YOUR NFT CONTRACT ADDRESS';const contract = NFT.attach(CONTRACT_ADDRESS);await contract.mint(WALLET_ADDRESS, URI);console.log('NFT minted:', contract);}main().then(() => process.exit(0)).catch(error => {console.error(error);process.exit(1);});
This is a straightforward script. It requires the URI for the Pinata metadata, your Ethereum wallet address, and the contract address you received when you deployed the NFT contract.
Save the file, and you're all set to mint! In your terminal, type the following command:
sh
npx hardhat run scripts/mint-script.js --network matic
You just minted an NFT for the asset you created earlier, assuming no errors. You have it in your wallet. We can run one more script to demonstrate this. Make a new file called get-token-script.js
in the scripts
folder. Add the following to that file:
js
const hre = require('hardhat');async function main() {const NFT = await hre.ethers.getContractFactory('MyNFT');const CONTRACT_ADDRESS = 'YOUR_CONTRACT_ADDRESS';const contract = NFT.attach(CONTRACT_ADDRESS);const owner = await contract.ownerOf(1);console.log('Owner:', owner);const uri = await contract.tokenURI(1);console.log('URI: ', uri);}main().then(() => process.exit(0)).catch(error => {console.error(error);process.exit(1);});
This script inquires who owns the first token generated by our NFT contract. We know we only made one token. It also retrieves the token URI associated with that token ID. This script can be run with the following command:
sh
npx hardhat run scripts/get-token-script.js --network matic
You’ll see something like this in the terminal:
sh
Owner: 0xd7220ab26a887a60Af3a11178eF4A48BE8DncbA6URI: ipfs://QmZu6UUMHo2bHLiRMZCoQf7hiSmnFVVzWqnEAyF9SJwxhx
Your owner's address and URI will differ, but the idea is the same.
This was a difficult way of doing things. Now we will see a simple method of minting an NFT that does not require any code.
The first and most straightforward method is to go directly to OpenSea and create your own NFT. Normally, this would be very expensive, but because OpenSea uses polygon, we can do it for free because it is so inexpensive.
Assume I have an image (a gene expression image), which we can call genes. In a supply option, we have Ethereum, but it will be somewhat expensive. Hence, we will select polygon, so it's actually going to be free for us.
We create and have an NFT that is minted on the blockchain, and it's available for anyone to buy on OpenSea.
We can look at RapidAPI Hub as a way of viewing different NFTs visually. RapidAPI is a collection of different APIs, and if we search for an NFT API, we can see that there is a way to search for NFTs using images visually.
Python may be used to test this API in the browser, and the returned JSON can also be viewed. The parameters would be the URL, the image we want to return, and a list of existing NFTs.