Deploying Regenerative NFTs on Polygon
Tags: javascript, ethereum, solidity, tutorial
Published: 2021-11-14 16:32:17

In my [previous blog post](https://dev.to/yournewempire/deploy-nfts-with-truffle-ipfs-opensea-polygon-5581), I put together a truffle project that could deploy ERC-721 token contracts to Polygon's Mumbai test network for compatibility for OpenSea. Today, I am ready to improve on this and show you devs and artists a couple of repositories that will help when deploying NFTs. Since my first post, I have been talking to a client about the power of regenerative art. Where artists can save time designing thousands of NFTs. I did some digging, and with some help from [Moralis YT](https://www.youtube.com/watch?v=VglTdr0n5ZQ) and [HashLips GitHub](https://github.com/HashLips/hashlips_art_engine), I conjured up a couple repos. Unfortunately, I have not configured an ERC-1155 example yet, but it is not too dissimilar from this code. So let's see what improvements I have made from the previous ERC-721 boilerplate.

### The improvements
* Migration from Truffle to Hardhat.
* All of the benefits that come with Hardhat. Including straight-forward contract testing, more frequent updates, a larger community and much more.
* Enabled Meta-transactions to allow gas-less transactions when assets are bought on OpenSea.
* In addition to the Hardhat environment, I have also added a fork of [HashLips](https://github.com/HashLips) to generate art metadata (purely optional)
* The HashLips art engine fork includes code for uploading NFT metadata to IPFS via a Moralis endpoint

The Repos: 
* [Forked HashLips art engine for IPFS uploads](https://github.com/YourNewEmpire/hashlips_art_engine)
* [Hardhat ERC-721](https://github.com/YourNewEmpire/Hardhat-OpenSea-ERC721)

My Working Example:
* [OpenSea](https://opensea.io/collection/arch-regen-nfts)
* [PolygonScan](https://polygonscan.com/address/0xe659d2a4d136d3f12c815304fa928fdaa43c17ba)

**You will need funds on Polygon mainnet/testnet if you are to deploy any contracts** (I have used mainnet to test meta tx's)

Firstly, I will show you the HashLips art engine fork to generate and upload NFTs. Lastly, I go through the Hardhat setup for deploying the contracts to Polygon.

## HashLips art engine

To get started clone the HashLips fork. If you want to deploy contracts too, then get both. They have readme files that you can follow as well:
* [Forked HashLips art engine for IPFS uploads](https://github.com/YourNewEmpire/hashlips_art_engine)
* [Hardhat ERC-721](https://github.com/YourNewEmpire/Hardhat-OpenSea-ERC721)

### Moralis IPFS setup
You will need to an account at [Moralis](https://www.moralis.io) to get an API key. Then you may send your metadata in POST requests to https://deep-index.moralis.io/api/v2/ipfs/uploadFolder.

Once logged in, find the WEB3 API in the sidebar and copy the api key:
![copymoralisweb3key](https://github.com/YourNewEmpire/hashlips_art_engine/raw/main/common/moralisweb3api.png)

Paste it into new .env file for `MORALIS`. 

### OpenSea Collection Metadata
If you want to test OpenSea Collection metadata, then replace (or use) the image and json files in `moralisIPFS/collection#1` and use the names I have used to keep the scripts working. You can edit `scripts/collectionImage.js` or `scripts/collectionJson.js` to read the collection metadata on lines 15 or 17.

Then, run `node moralisIPFS/scripts/collectionImage.js` in the console. If no error occurred, then copy your uri link from the console log. Mine looks like this:
`{path:'https://ipfs.moralis.io:2053/ipfs/Qmbd46WBvCK33kuGcEb7LtQkWcXW3ygDEgBv5rdFvnJ7RX/collection-1/image.gif'}`

You can change how your deployed IPFS url trails in the `collectionImage.js` at line 18.

You will need this link in your `collectionJson.js` scripts to complete the collection metadata. If you look in the json script at line 25, you can see the format of IPFS image link: 
```
{
                  path: `collection-1/collection.json`,
                  content: {
                        ...parsed,
                        //! here
                        image: `ipfs://Qmbd46WBvCK33kuGcEb7LtQkWcXW3ygDEgBv5rdFvnJ7RX/collection-1/image.gif`
                  }
            }
```
So copy your link from the hash trail and up and swap mine for it: Qmbd46WBvCK33kuGcEb7LtQkWcXW3ygDEgBv5rdFvnJ7RX/collection-1/image.gif

Now you can run `node moralisIPFS/scripts/collectionJson.js` to finalise your collection metadata. Copy the json uri link from the console and, open `GameItem.sol` in your Hardhat project. Paste it here at line 232 after '/ipfs/':

```
  function contractURI() public pure returns (string memory) {
        return "https://ipfs.io/ipfs/yourhash/path/to/file.json";
    }

```
### NFT Metadata

Before generating your art, be sure to check `moralisIPFS/scripts/numOfItems.js`. This is a variable for the upload scripts that we need to run shortly. 

If you look in the project folder you can see the **layers** folder. Each folder in the layers folder is each layer/piece in the final output. When you inspect the layers folder further, you notice that each layer folder will need multiple variations of that layer, to have more combinations of NFTs. For editing the rarity, you can change the '#1-99' on each layer file for the percentage chance of it appearing in outputs. However, I shall be using the helpful boilerplate from HashLips.

If you navigate to the src/config.js file, you can see theres a few bits to configure here. One is the `layersConfigurations` variable. Here you can set the number NFTs outputted, and the order of the layers that are placed in the image. I only minted 5 but, with the boilerplate layers you can make up to 15 or more. 

Now, onto the NFTs. After running `node index.js` the NFTs will be generated and you can see the console logs to confirm. These json/image outputs can be found in the `moralisIPFS/build` folder.

**Before going any further**: Ensure to edit my `moralisIPFS/scripts/numOfItems.js` to match the number of editions you have set in the HashLips config. This number will be read by the upload scripts to upload the correct amount.

You can now run `node moralisIPFS/scripts/images721.js`. If successful, this will upload the files and log your image IPFS links. You will need the long hash from one of those image links:
``` 
[
  {
    path: 'https://ipfs.moralis.io:2053/ipfs/QmVgGeRfv1e4EMi6a4A7UEAAcZuESiNQbGBeX7kJaNLYKy/images/1.png'
  }
],
[
  {
    path: 'https://ipfs.moralis.io:2053/ipfs/QmVgGeRfv1e4EMi6a4A7UEAAcZuESiNQbGBeX7kJaNLYKy/images/2.png'
  }
]

//and so on
```
Just as you did with the collection metadata, you will paste the IPFS hash from the upload logs into your `metadata721.js` script at line 23, replacing my dummy hash like so:

```
{
    path: `metadata/${i}.json`,
    content: {
        ...parsed,
        image: `ipfs://PASTE-YOUR-HASH-HERE/images/${i}.png`
    }
}

```

This metadata script will read the JSONs generated by HashLips, but replaces the image value to what you see above. So, now you have your metadata script ready, you should run `node moralisIPFS/scripts/metadata721.js` to upload the metadata to IPFS. Copy full uri from the console log, open your Hardhat project, and navigate to `scripts/mint.js`:
 
```
for (var i = 1; i <= NUM_ITEMS; i++) {
            await gameItem.mintItem(OWNER_ADDRESS,`your-metadata-uri`);
}
```
Paste the uri in to the mintItem function parameters to match the following format:
`https://ipfs.io/ipfs/bafybeickmuro374jjqidtotrxhvqubfdwpby3sm4k4ydurv4c3h4l4buni/metadata/${i}.json`

With that done, our NFT metadata is ready and we can deploy and mint the NFTs.

## Hardhat Contracts
For a quick start, you can check the readme file. In detail, you will need to run `npm i` and add a `.env` file with the following: 
```
MNEMONIC=privatekey. not the seedphrase
MATIC_APP_ID=appid_from_maticvigil
POLYGONSCAN=apikey_from_polygonscan
```

We need the POLYGONSCAN var when running `npx hardhat verify` to verify contracts on polygonscan. This part is **optional** but recommended if you need your source code verified.

You can set your own name and ticker in the `scripts/deploy.js` file, if you need a specific name and ticker.

**Before minting, be sure to find NUM_ITEMS in scripts/mint.js and set it to the number of JSONs you deployed.**

After successfully running `npx hardhat run --network matic scripts/deploy.js`, the console will log your contract address. Copy that, and paste it into line 8 contract.attach function in `mint.js`.

In `mint.js` you will see an OWNER_ADDRESS variable. Paste your deployer account address in there for the mintItem function to execute and mint to yourself. 

Now that your minting script is ready, you can run that with `npx hardhat run --network matic scripts/mint.js`. 

And thats it. Now you should check PolygonScan and OpenSea for your .

## Final notes

So there you go. You can now deploy ERC-721 regenerative NFTs for OpenSea on Polygon/Matic. With help from Filip at Moralis, I was able to add bulk IPFS uploads. The setup is still a bit cumbersome, because you are still required to do the images first then copy the uri for the json scripts.

### Possible Improvements
* Automate the scripts so that the dev does less copying and hard-coding.
* Fill in the hardhat.config.js for other networks.
* Add external/proxy contracts for more flexibilty and upgradeability.
* Move the HashLips project into the Hardhat project for 1 repo.

Any more improvements? Go ahead and suggest them! 

You can find my working example [here on OpenSea](https://opensea.io/collection/arch-regen-nfts) and [here on PolygonScan](https://polygonscan.com/address/0xe659d2a4d136d3f12c815304fa928fdaa43c17ba)

### Check these out: 
* [HashLips](https://github.com/HashLips)
* [Sign up at Moralis](https://admin.moralis.io/register) + [Docs](docs.moralis.io)

Hope you learn't something new and enjoyed it. I am looking forward to seeing success & errors :D.