Introduction
Non-Fungible Tokens (NFTs) have exploded in reputation over the past yr. And with NFTs getting used for art, PFPs, way of life manufacturers, sports activities, video games, the metaverse, and extra, they gained’t be going away anytime quickly. However the present state of NFTs has a number of issues – notably, minting on Ethereum could be prohibitively costly and the metadata behind these NFTs is usually centralized.
On this article, we’ll have a look at one strategy to clear up these points by creating and deploying an NFT to the Polygon Community and utilizing IPFS to retailer the metadata. In our instance, we’ll use Truffle as our improvement surroundings and Infura to attach and work together with the blockchain and IPFS.
A Fast Overview of NFTs
Fungible tokens are cryptographic tokens that may be exchanged for another of the identical token (1 == 1). These embody cryptocurrencies reminiscent of Bitcoin (BTC) or ETH. One Bitcoin is strictly the identical as another Bitcoin.
In distinction, NFTs are not fungible – one token is not replaceable by one other, they usually might have various values (1 != 1). An NFT is an undisputable illustration of digital possession. It may be used to signify any method of digital property reminiscent of photographs, movies, music, and a lot extra.
NFTs on Ethereum and Layer Two
Most NFTs are created on the Ethereum Network, because it permits for the best sense of safety and decentralization. Nonetheless, for the common particular person, there’s a main situation: Transacting on Layer 1 of the Ethereum Community is pricey.
Over the course of 2021, a number of options to this drawback have gained reputation. Layer 2 options reminiscent of Arbitrum, zkSync, and the Polygon Network are right here to supply a extra user-friendly expertise. Transaction charges on these networks are a fraction of what they’d be on Layer 1, and most often, considerably quicker.
One other present drawback with NFTs is that the metadata they comprise isn’t at all times saved in a decentralized method. If the group internet hosting the metadata disappears, so does the worth of your NFT. The very best resolution is to host the metadata utilizing a world, peer-to-peer file system reminiscent of InterPlanetary File Storage (IPFS).
Combining applied sciences reminiscent of Polygon and IPFS creates an economical technique to deploy and retailer your NFT in a extra decentralized and everlasting method. Though we may use no-code companies reminiscent of these offered by ConsenSys, it’s extra enjoyable to really deploy one your self and you’re going to get a greater understanding of the way it all works behind the scenes.
So let’s have a look at how one can create and deploy an NFT to the Polygon Community. We’ll use Truffle as our improvement surroundings and Infura to attach and work together with the blockchain, and to retailer the metadata with IPFS.
Earlier than deploying, we are going to check on a neighborhood occasion of a blockchain with Ganache. When it’s able to go dwell, we are going to deploy to the Polygon Mumbai Take a look at Community and can confirm the NFT on OpenSea, the world’s hottest NFT platform.
The Venture
What You Will Study
- Add the NFT picture and metadata to IPFS through Infura
- Arrange the Polygon Community in MetaMask and get check funds
- Arrange Truffle Improvement Setting
- Write an NFT good contract
- Take a look at deployment regionally utilizing Ganache
- Deploy to Polygon testnet utilizing Truffle console and Infura
- Confirm the NFT on opensea.io
What You Will Want
Extra Assets
Setting Up Accounts
Earlier than we get to the enjoyable components like constructing and testing, let’s arrange our accounts and get all the pieces in place. It will guarantee the remainder of the method goes easily.
Get an Infura Account
Infura is an Ethereum node supplier and API. It can enable us to simply hook up with the Polygon Community and in addition offers an easy-to-use technique for using IPFS.
The very first thing we have to do is head to infura.io and arrange a free account. After verifying our e mail tackle, we are able to entry the dashboard, the place we are able to make new tasks. The Polygon Community isn’t enabled by default, nevertheless.
We are able to add Polygon to our plan by choosing the “Add-Ons” tab on the left-hand facet of the display screen and scrolling right down to “Community Add-Ons”. Subsequent, we choose “Polygon PoS Add-On” and undergo the immediate so as to add it.
Now we’re able to create a brand new challenge. Let’s head again to the dashboard and click on on the “Create New Venture” button. We’ll choose Ethereum because the product and identify our challenge Polygon-NFT.
As soon as our challenge is created, there are a number of issues to notice:
- The Venture ID
- The challenge secret
- Endpoints choice
- Our endpoint hyperlink
Let’s change our Endpoint from MAINNET
to POLYGON MUMBAI
, which is the Polygon testnet. Our Endpoint hyperlink will then change. We’ll want the values on this web page later, however for now, we’re achieved with the challenge web page.
IPFS through Infura
Since we’re already in our Infura account, let’s go forward and create one other challenge. This one will probably be for using IPFS to retailer the picture and metadata of our NFT. This time once we create a brand new challenge, we are going to choose IPFS because the product. Let’s identify this one Polygon-NFT-Metadata.
For the following steps we are going to want the Venture ID, challenge secret, and endpoint URL, however first, we want a picture for our NFT.
Good-click and save this to your machine 😉
Be happy to make use of your personal picture shifting ahead. OpenSea recommends the picture dimension to be 350 x 350 pixels.
Now let’s add the picture to IPFS!
Utilizing a command terminal, we are going to cd
into the folder the place our picture is saved.
To add the picture, kind the next command:
curl -X POST -F file=@myfile -u "PROJECT_ID:PROJECT_SECRET" "https://ipfs.infura.io:5001/api/v0/add"
Be aware:
-
@myfile
needs to be the identify of the picture file within the present folder. So in our case@polygon-nft.jpg
. -
PROJECT_ID
andPROJECT_SECRET
would be the keys offered within the settings for our Infura challenge.
The output from the command ought to look one thing like this:
Crucial a part of the output will probably be our “Hash”. We are able to truly confirm the picture was uploaded efficiently by pasting that Hash into the next URL: https://ipfs.io/ipfs/YOUR_HASH_HERE
It’s necessary to notice that Infura pins our knowledge to IPFS by default. If we ever wish to take away an merchandise from IPFS we’ve to unpin it. Now that our picture is saved on IPFS, let’s get the metadata saved there as nicely. In keeping with standards by OpenSea, we are going to need our metadata in JSON format like so:
{
"identify": "My Candy Polygon NFT",
"description": "Our wonderful NFT deployed to the Polygon Community",
"picture": "ipfs://YOUR_HASH_HERE"
}
So let’s create a brand new textual content file in the identical folder on our native machine as our NFT picture. We are able to use any textual content editor for this; it doesn’t must be something fancy.
We’ll add the metadata in the identical format as above. Nonetheless, relatively than utilizing YOUR_HASH_HERE
we’ll insert the precise Hash for our picture that we simply verified. We’ll save the file as nft-metadata.json
. We additionally want to verify there is no such thing as a comma after the final merchandise in our JSON file. If there’s a comma, then OpenSea won’t show the NFT correctly.
Now we are able to add this file to IPFS utilizing the identical command as final time; we simply want to switch the file identify with @nft-metadata.j
.
Wonderful! We now have our metadata pinned to IPFS which has a hyperlink that factors to our already pinned picture. We’ll copy the Hash within the output to make use of later.
Setting Up MetaMask
With a view to work together with the Polygon Community and to pay any transaction charges, we might want to arrange a Web3 pockets. We’ll use MetaMask to do that. It’s put in as a browser extension and permits us to connect with Decentralized Apps (dApps).
Let’s head over to metamask.io and obtain the extension for our browser. When utilizing a crypto pockets like MetaMask, it’s a good suggestion to know wallet safety.
Keep in mind: By no means share your seed phrase with anybody! Whoever has your seed phrase can withdraw your tokens.
We might want to use the 12-word seed phrase when organising our Truffle challenge. So make sure to write that down and put it aside for later. As soon as we set up MetaMask and open it to the dashboard, we have to add Polygon to our Networks dropdown.
Once we click on the dropdown, it reveals a button so as to add new networks to the listing. So we’ll press the “Add Community” button, and add both the Polygon Mainnet and Mumbai Testnet.
We might want to enter within the following data:
Mumbai Testnet
Polygon Mainnet
Now we’ve the Polygon Community added to our MetaMask, but when we change to the Mumbai Testnet, there’s no MATIC! Let’s change that. We’ll want to repeat our pockets tackle, which is listed below the identify of our Account. It begins with 0x…
Subsequent, we’ll head over to https://faucet.polygon.technology/ which is a faucet that gives check funds for improvement. We have to choose the Mumbai Community after which paste our tackle into the textual content subject. As soon as we hit “Submit” we must always see some MATIC tokens in our MetaMask pockets after a minute or two.
Be aware: When you’ve got a number of accounts in your MetaMask pockets, Truffle makes use of the primary one by default. So make sure to add the check MATIC tokens to the primary account in your listing.
Now that we’ve loaded our pockets with some check tokens, we’re prepared to maneuver on.
Set up Truffle and Ganache
Truffle
Truffle is a improvement surroundings that gives instruments to make constructing on the blockchain a lot simpler. With a view to set up it through the command line, we are going to want NodeJS v8.9.4 or later and Node Package deal Supervisor (npm). If it’s not already put in, check out this link.
As soon as it’s put in on our machine, we are able to set up Truffle utilizing this command within the terminal:
npm set up -g truffle
We are able to kind the command truffle model
afterward to make sure it was put in appropriately. If there are any errors, make sure to add the npm modules to your path.
Ganache
Subsequent we’ll set up Ganache, a neighborhood blockchain occasion used for testing earlier than deploying to the Mumbai Testnet.
Ganache has a GUI model that may be downloaded here, however we are going to use the terminal model for the remainder of this tutorial. It may be put in utilizing this command:
npm set up ganache --global
Once more, we are able to confirm correct set up by checking the model: ganache --version
Setting Up Our Venture
Now that our accounts are arrange and all the pieces is put in correctly, let’s begin placing all of it collectively. Step one is to navigate in our terminal to the place we wish to create our challenge and make a brand new listing.
mkdir polygon-nft-project && cd polygon-nft-project
One extremely helpful factor about Truffle is they provide a full suite of “boxes” for getting began shortly. They’re basically boilerplates that embody useful modules, pre-made good contracts, frontend views, and extra. For this challenge, we are going to make the most of Truffle’s Polygon Box. Set up is straightforward; we simply must kind this command:
truffle unbox polygon
After set up, we are able to see there are a number of new information in our challenge folder. Crucial ones we will probably be working with are the README.md
file, truffle-config.polygon.js
, the 1_deploy_simple_storage.js
below the migrations
folder, and SimpleStorage.sol
information, which could be discovered within the contracts
folder.
You’ll probably see an ethereum
and polygon
folder below contracts
. It’s because sometimes when a challenge is deployed to Polygon, it also needs to be deployed to Ethereum so customers can simply bridge their property forwards and backwards. We are able to delete the SimpleStorage.sol
contracts since we gained’t be utilizing them.
Taking a fast look by the README.md
file, we are able to see that so as to deploy to the Polygon Community, we should add two issues:
- The Mnemonic phrase (seed phrase) of the pockets we’re utilizing
- The Infura Venture ID
We’ll wish to retailer these in a .env
file and ensure it’s added to our .gitignore
so we don’t unintentionally add these secrets and techniques if storing our challenge on a public repository.
Downloading the Polygon Truffle Field additionally put in the .dotenv
bundle for us. All we have to do is create a .env
file in our root folder.
The mnemonic phrase for our pockets could be present in our MetaMask settings below the “Safety & Privateness” heading. The Venture ID could be discovered below the “Keys” heading in our Infura challenge settings. Our .env
file will look one thing like this:
MNEMONIC="your twelve phrases right here ..."
INFURA_PROJECT_ID="challenge ID # right here"
The following factor we must always do is replace Truffle to make use of the newest model of Solidity. In our truffle-config.polygon.js
file, we are able to add the compiler model we want to use.
Beneath the compilers
part, throughout the solc
curly braces, we’ll add the next: model: “0.8.11”
(the newest model of Solidity on the time of this writing).
It ought to seem like this:
// Configure your compilers
compilers: {
solc: {
model: "^0.8.11"
}
},
Be aware: For those who didn’t delete the SimpleStorage.sol
contracts, then you’ll need to replace their Solidity model so as to compile correctly. Merely change the pragma line to the next: pragma solidity >=0.4.21 <0.9.0;
The final little bit of prep work is simply to put in the OpenZeppelin contract library, as we are going to import a number of contracts. We are able to set up it by typing this command within the root listing of our challenge:
npm set up @openzeppelin/contracts
We’re using the OpenZeppelin library to make writing our good contract simpler and far safer. The contracts we are going to use have had thorough safety audits and it ensures we’re adhering to the business normal for NFTs.
With our challenge arrange correctly, we’re able to get to the very best half… Creating the NFT!
The Good Contract
We’ll open up our most well-liked code editor from our challenge root folder. (I’m utilizing vscode so the command is code .
.) Create a brand new file below the contracts
folder named PolygonNFT.sol
.
Be aware: If that you must brush up on the Solidity coding language, try my Solidity Basics Series.
We’ll be utilizing the next good contract for our NFT:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
// Import the OpenZeppelin contracts
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/entry/Ownable.sol";
// Declare our contract and inherit from the OpenZeppelin ERC721 and Ownable contracts
contract PolygonNFT is ERC721, Ownable {
// Helpers for counting safely and changing knowledge to strings
utilizing Counters for Counters.Counter;
utilizing Strings for uint256;
// State variable for storing the present token Id
Counters.Counter non-public _tokenIds;
// Map token Ids to token URI
mapping (uint256 => string) non-public _tokenURIs;
// ERC721 requires a reputation for the NFT assortment and an emblem
constructor() ERC721("PolygonNFT", "PNFT") {}
// Set the URI (metadata) for tokenId
perform _setTokenURI(uint256 tokenId, string reminiscence _tokenURI)
inner
digital
{
_tokenURIs[tokenId] = _tokenURI;
}
// Return the Token URI - Required for viewing correctly on OpenSea
perform tokenURI(uint256 tokenId)
public
view
digital
override
returns (string reminiscence)
{
require(_exists(tokenId), "Token doesn't exist");
string reminiscence _tokenURI = _tokenURIs[tokenId];
return _tokenURI;
}
// Mint the NFT to the offered tackle, utilizing the offered metadata URI -- solely the pockets tackle that deployed this contract can name this perform
perform mint(tackle recipient, string reminiscence uri)
public
onlyOwner
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.present();
_mint(recipient, newItemId);
_setTokenURI(newItemId, uri);
return newItemId;
}
}
Fairly quick, proper?! That’s the attractive factor in regards to the composability of Web3. OpenZeppelin is doing many of the heavy lifting right here with their ERC721 normal.
Principally, we’re merely defining the NFT assortment and image, supplying the NFT metadata through the _setTokenURI()
perform, placing it along with our mint()
perform, after which offering a method for OpenSea or anybody else to retrieve the NFT metadata by our tokenURI()
perform.
Testing Deployment With Ganache
Deploying to the blockchain is fairly easy, however earlier than we are able to try this, we have to modify the 1_deploy_simple_storage.js
file below the migrations
folder. We simply want to switch each occasion of SimpleStorage
with no matter we named our NFT good contract. In our case: PolygonNFT
. We also needs to rename the file to 1_deploy_polygon_nft.js
to remove any confusion.
Our migration file ought to now seem like this:
const PolygonNFT = artifacts.require("PolygonNFT");
module.exports = perform (deployer) {
deployer.deploy(PolygonNFT);
};
Earlier than deploying our challenge to a dwell blockchain, it’s common follow to check it on a neighborhood blockchain occasion. We’ll use Ganache to do that. In a brand new terminal window, we are going to use this command to get it up and operating:
ganache
The terminal ought to output some Out there Accounts, their Personal Keys, and so forth.
To deploy our challenge to Ganache, open up the unique terminal window. Within the root listing of our challenge, kind the command:
truffle migrate --config=truffle-config.polygon.js --network=improvement
Since there are two config information in our challenge, we have to specify which one to make use of. Truffle will use the truffle-config.js
file by default. After hitting enter, we are able to see that Truffle compiles our contracts after which begins the migration. If all goes efficiently, you’ll obtain a transaction receipt that can look one thing like this:
Be aware of the contract tackle
Now that our contract has migrated efficiently to our native blockchain occasion, we are able to use the Truffle Console to work together with it. The Truffle Console is a strong software that permits us to make use of javascript to work together immediately with our contract with out having to arrange a frontend. To make use of it, kind the command:
truffle console --config=truffle-config.polygon.js --network=improvement
Discover how the command immediate modifications to truffle(improvement)>
. We are actually prepared to start out interacting with our good contract.
First, we have to get an occasion of our contract. Copy the contract tackle from our transaction receipt for use on this line of code:
let occasion = await PolygonNFT.at("YOUR_CONTRACT_ADDRESS_HERE")
It can return undefined but when we kind occasion
it ought to output our contract ABI. Now we are able to name the mint perform. We’ll want a contract tackle during which to ship the NFT and our IPFS URI from earlier within the format: ipfs://YOUR_HASH_HERE
await occasion.mint("YOUR_WALLET_ADDRESS", "YOUR_METADATA_URI")
It’s necessary to notice that the mint perform is being referred to as by the tackle that deployed the contract as a result of that’s the one we logged into the Truffle Console with by default. The tackle we positioned within the code above is the recipient of the NFT.
If all went nicely with our code above, we shouldn’t see any errors after we hit enter! We now know our contract works and we’re capable of mint an NFT from it. Sadly, since it is a native blockchain occasion, we don’t have OpenSea or PolygonScan to confirm that our NFT truly exists. For that, we are going to deploy to the Mumbai Testnet.
Deploy to Polygon Testnet
The method to deploy to the Mumbai Testnet is similar to launching on our Ganache blockchain occasion. We simply must exit the Truffle console by typing ctrl+c
twice after which observe the very same steps as above. The one distinction is we are going to exchange the community= improvement
with polygon_infura_testnet
.
Earlier than shifting ahead, we want to verify our Mnemonic phrase
and Venture ID
are arrange correctly in our .env
file in any other case, the following steps gained’t work. (See the steps within the Setting Up Our Venture part.) With these in place, our instructions will now seem like this:
truffle migrate --config=truffle-config.polygon.js --network=polygon_infura_testnet
The migration will take somewhat bit longer than our Ganache occasion. As soon as it’s full it can output a transaction receipt that appears just like our final one. This time we are able to confirm that our contract was efficiently migrated to the Mumbai Testnet by coming into our contract tackle to https://mumbai.polygonscan.com/tackle/YOUR_ADDRESS_HERE
Wonderful! Our contract is dwell on the Mumbai Testnet! Now let’s work together with it and truly mint our NFT!
We’ll entry the Truffle Console utilizing the identical instructions as earlier than, once more, changing the community= improvement
with polygon_infura_testnet
.
truffle console --config=truffle-config-polygon.js --network=polygon_infura_testnet
Get an occasion of our contract utilizing the contract tackle that was output on our Mumbai Testnet transaction receipt:
let occasion = await PolygonNFT.at("YOUR_CONTRACT_ADDRESS_HERE")
And now, for the second we’ve been constructing in the direction of this complete article! Mint our NFT to our desired tackle utilizing our IPFS URI within the format: ipfs://YOUR_HASH_HERE
await occasion.mint("YOUR_WALLET_ADDRESS", "YOUR_METADATA_URI")
If there are not any errors, we are able to examine our contract on mumbai.polygonscan
once more and see that our mint()
perform was referred to as! This time, we are able to confirm that our NFT truly exists by checking it out on OpenSea.
Confirm Our NFT On OpenSea
We are able to simply try our new NFT on OpenSea by copying our contract tackle into the search bar at https://testnets.opensea.io/. Ethereum addresses have two versions, one that’s checksummed and one that isn’t. The distinction being the non-checksummed model is all lowercase. We might have to make use of the non-checksummed model to seek out our NFT on OpenSea. We are able to get this tackle by clicking on the Txn Hash on mumbai.polygonscan
after which copying the tackle throughout from Interacted With (To):
Your contract tackle will probably be totally different
If our metadata was entered appropriately we must always now see our lovely, new NFT dwell on OpenSea!
Conclusion
Congratulations! You could have efficiently deployed an NFT to the Polygon Mumbai Testnet! You uploaded your NFT picture and metadata to IPFS utilizing Infura’s API, arrange your Truffle challenge and wrote a sensible contract to create an NFT, examined deployment regionally utilizing Ganache, deployed to the Polygon Testnet with Truffle, Infura, and MetaMask, and at last, verified your NFT on OpenSea.
You now have the data to deploy to the Polygon Mainnet, simply ensure you have actual MATIC tokens in your MetaMask pockets. Moreover, when deploying, make sure to use community=polygon_infura_mainnet
as an alternative of polygon_infura_testnet
.
Your subsequent steps could be to deploy to the Ethereum Mainnet to have the ability to bridge your NFT from Layer 2 to Layer 1. That’s the matter for an additional article so make sure to try the Polygon Docs within the meantime.
Thanks for following together with this tutorial! Take care, and glad constructing!
(The code for this challenge could be discovered right here: https://github.com/paul-mcaviney/polygon-nft-project)