NFT.JS - A Javascript library to implement NFTs

NFT.JS - A Javascript library to implement NFTs

ยท

10 min read

๐Ÿ‘‹ Hello world ! This is Santhosh Reddy, a web3 developer and the solo developer of NFTJS. What's NFT.JS ? Today I'm launching NFT.JS to the world of web3 developers. Now let's talk what, why and how about NFT.JS

Intro... ๐Ÿ™‹โ€โ™‚๏ธ

Remember that, this is about the initial version of NFT.JS and to use NFT.JS you need to use the NFT.JS 2.0. You can checkout it here

If you're a web3 developer, you will definitely know what NFTs are and might have also implemented them somewhere in your previous projects or Dapps right?

Usually, implementing NFTs in the Dapps includes the work of creating an ERC721 contract using solidity, testing them and deploying to the network using Truffle & Ganache or Remix IDE and then interacting with the contract from the Dapps using web3js.

Not done yet! You need to use IPFS to store metadata as well as files in the metadata like images, videos or other media content.

Have you ever thought of using a single library that can perform all these tasks! NFT.JS has taken birth here :)

Let's move on to the detailed talk on NFT.JS

Before moving on, I have a small request. If you found NFT.JS interesting and useful please consider upvoting it on Product Hunt

20220404_085105_0000.png

Visit : NFT.JS

What's NFT.JS... โ€ผ๏ธ

Long story short, NFT.JS is a Javascript library that does all the above discussed tasks to implement NFTs in the Dapps.

Building a NFT marketplace ? Developing a Decentralized social platform or any other Dapps that needs to implement NFTs ? If "yes", using NFT.JS is a cool thing that you can do.

Using NFT.JS, you can deploy a ERC721 contract that can perform all the required functions without writing a single line of Solidity. You can easily interact with the contract by calling the functions and sending transactions to the contract with just 1-2 lines of NFT.JS and it also removes the usage of IPFS.

You can simply provide the input file into the metadata object and NFT.JS uploads all the files provided in the metadata to IPFS and lastly uploads the metadata.json file to IPFS and mints the NFT.

Have you heard of lazyMinting ? NFT.JS also provides that cool feature. In lazyMinting, the user can mint a NFT where the token data is stored off-chain(ipfs) to avoid gas fee and in future, if a buyer is ready to buy that NFT, the data moves on-chain by minting the NFT to the buyer. Here the user can get rid of gas-fee which is a big entry barrier.

Planning to build your Opensea ? Don't reinvent the wheel and consider using NFT.JS.

Tech Stack used... ๐Ÿ‘จโ€๐Ÿ’ป

  1. Javascript (programming language of the library)

  2. Solidity (to create a ERC721 contract)

  3. Web3.JS (to deploy and interact with the contract)

  4. Moralis (for RPC nodes and IPFS gateway)

The technologies mentioned above are used to develop NFT.JS

Why use NFT.JS... โ“

The 3 main benefits that you can enjoy using NFT.JS are...

1. Low code development

NFT.JS completely diminishes the usage of Solidity to create smart contracts.

Not only that, using web3.js to interact with a contract also requires 4-5 lines of code right? NFT.JS does that same thing in just 1-2 lines of code.

2. Integrated IPFS

Need to use a 3rd party IPFS node and gateways like Infura, Alchemy? No need, Moralis IPFS gateway is integrated to NFT.JS and doesn't even need to code to use IPFS.

Using Moralis IPFS that is integrated to NFT.JS gives you a cool experience and can handle files that are as large as 1GB and that's the maximum limit.

3. Implement lazyMinting

LazyMinting is a cool experience that you can give your Dapp users. NFT.JS also provides the feature of implementing lazyMinting.

Not only that, getting started with NFT.JS is very simple and implementation & usage is super easy.

Isn't it cool...?

How to NFT.JS โš™

(deprecated. see NFTJS 2.0 here)

Now let's jump into a deep talk on how to use NFT.JS by exploring its usage and implementations.

Install NFT.JS

The first thing you need to do to get started with NFT.JS is to install it by adding a simple script tag in the <head> section of your index.html file.

<script src="https://nftjs.netlify.app/nft.js" type="text/javascript" />`

Initialize it...

After installing NFT.JS you need to initialize the NFT.JS by providing the ethereum network (mainnet/rinkeby/ropsten...) and the user's wallet address as strings in the following way.

NFTJS.start("rinkeby", accounts[0])

If you want to change the network or user's wallet address in any instance, you can easily do it by calling the same function again with different parameters.

NFTJS.start("ropsten", accounts[1])

Deploying a collection contract

The ERC721 contract is created using Solidity with all the required functions and compiled already. By calling the createCollection function, you can deploy it to the network that you have set in NFTJS.start().

The required parameters are name of the collections as a string, SYMBOL of the collection as a string, publicMintable as string ("true"/"false") and maxSupply as an integer.

publicMintable is a parameter that defines if you would like to allow others (other than owner) to mint NFTs in the collection and Default value is false and it's always false unless you give "true" as the parameter value.

await NFTJS.createCollection(
"Nftify",
"NFY",
"true",
10000
)

After the transaction receipt gives the deployed contractAddress, you can get it by calling a simple function like this.

var address = NFTJS.deployed()

This only gives the address of the collection that is most recently deployed in that web session. If either the page is reloaded or a new contract is deployed, the address of the past contract is gone.

Initiating a collection

Initiating a collection requires the address of that contract and must be deployed to the network that you have provided in the NFTJS.start()

var collection = new NFTJS.collection(address)

Functions of a collection

Now let's see how to interact with a smart contract by sending and calling the data.

1. mintNFT : Minting an NFT requires the metadata object which contains the items like name, description, image and others.

Let's discuss the role of IPFS here. The first thing that the minNFT function does is, it checks if an item in the level 1 items of the object is a file. It uploads all the files to the IPFS and replaces the file values with the file URL. It will take some to complete the whole process.

Note that, if a file input's value is given in metadata and the user doesn't upload a file, the function fails.

After uploading the files in metadata, it uploads the final metadata object to the IPFS and then sends the transaction to the metamask wallet.

await collection.mintNFT({
  name : "king",
  description :  "king of the kingdom",
  image : inputElement.files[0]
})

2. lazyMintAndTransfer : This is a function which is similar to mintNFT but is needed if you want to provide your users a gas free minting experience.

The required parameters are minter, price and metadata. Here, the buyer of the NFT is the user who is calling the function and the minter is the one who minted the NFT off-chain. The price is the amount of ETH the buyer needs to pay the minter.

The metadata of the NFT stored off-chain while minting should be given as the parameter. Dealing with metadata and IPFS is the same as in the mintNFT function.

As soon as the transaction is completed, the NFT data moves on-chain by directly minting it to the buyer and the ETH gets transferred to the minter address.

await collection.lazyMintAndTransfer(
  nft.minter, 
  nft.price,
  nft.metadataObj
)

3. updateNFT : This is a crucial function to update the NFT's metadata. This function requires the ID of the NFT that needs to be updated and the new metadata that needs to replace the old one.

Here, the user must be the owner of the NFT.

Dealing with metadata and IPFS is the same as in the mintNFT function.

await collection.updateNFT(id, {
  name : "king1",
  description :  "king1 of the kingdom1",
  image : inputElement.files[0]
})

4. burnNFT : This function is used to burn or delete the NFT. This function requires the ID of the NFT that has to be minted and the user must be the owner of the NFT.

await collection.burnNFT(id)

5. approve : This function is used to give the transfer approval to the collection contract. This function requires the ID of the NFT that has to be approved and the user must be the owner of the NFT.

await collection.approve(id)

6. setApproveAll : This function allows the user to give or revoke approval on all his NFTs to the collection contract. The parameter that you need to give is a string form of the boolean ("true"/"false").

The default value is "true" and is always the same unless you give a parameter like "false".

await collection.setApprovalForAll(bool)

7. transfer : This function is used when a user wants to transfer his/her NFT to anyone he/she wishes. The required parameters are "to" which is an address to which he/she wants to transfer and the ID of the NFT.

await collection.transfer(to, id)

8. transferFrom : This function is basically a buy function. The required parameters are from, to, price and id. As this transfer is made by the collection contract, the from/owner must give the approval to the contract before calling this function.

Usually, this function should be called by the "to". This function transfers the NFT of the given ID from "from" to the "to" and transfers the ETH of "price" from "to" to the "from". As said, it's a biy function and msg.value must be > 0.

await collection.transferFrom(from, to, price, id)

9. details : This function returns the object that includes the details of the collection like, name, symbol, owner, maxSupply, publucMintable and totalSupply. Here, totalSupply also includes the burned NFTs.

var details = await collection.details()

10. getApproved : This function takes the ID of a NFT and returns the address to which the owner has given approval of that NFT id.

Usually, it returns the address(0) if not approved and returns the address of the collection if approved.

var address = await collection.getApproved(id)

11. isApprovedForAll : This function returns the boolean value. This boolean is equal to the value given in the setApproveAll function. Its default value is false.

var bool = await collection.isApprovedForAll()

12. ownerOf : This function returns the owner's address of the given NFT id.

var owner = await collection.ownerOf(id)

13. balanceOf : This function returns the no.of NFTs holding of the given user's address.

var balance = await collection.balanceOf(address)

Hope you understand how to use NFT.JS to implement NFTs in your projects in a low-code way and save your valuable time & energy.

If you have any doubts, found any bugs or want to give a suggestion or feedback on NFT.JS you can comment down below or can reach out to me on twitter

Limitations... โ›”

The only 2 limitations of NFT.JS are...

  1. It only supports Ethereum, not other networks like Polygon and BSC and only the ERC721 standard, not ERC1155.

  2. While implementing lazyMinting, you need to store the token data off-chain right ? Unfortunately, NFT.JS doesn't provide the option to store the off-chain data and you need to set up your own space for that.

Future plans... ๐Ÿ”ฎ

As a developer and a problem-solver, the only future plan for NFT.JS is to break the above limitations...

I think it would be great if NFT.JS also supports ERC1155 as well as other networks like Polygon and BSC. Using Polygon or BSC is a great thing to reduce the gas fee.

I also feel that, ETH2.0 can also replace the positions of Solana, Polygon and BSC coz, ETH2.0 is an upgraded version of ETH and uses proof-of-stake which may result in a much lower gas fee than Polygon and BSC.

Final Thoughts... ๐Ÿ™‚

I'm so excited and happy that I also completed developing something that can help my fellow devs.

Uhhh.....

Finally, if you are to build something that requires implementation of NFTs please consider using NFT.JS...

Taking a leave for now...๐Ÿ‘‹Bye!

ย