Learn How To Build An NFT Marketplace On-Chain
Table of Content
- What is an NFT?
- What is an NFT marketplace?
- Building your marketplace
- Building your Smart Contract
- Marketplace functionality
- FInal thoughts
The popularity of NFTs has grown exponentially since the launch of OpenSea, an online marketplace specializing in NFT collectibles. Since the launch of Bitcoin in 2009, blockchain technology has quickly pushed to the forefront of technology and has paved the way for the evolution from Web2 to Web3. From cryptocurrency to the virtual artwork of Donald Trump, blockchain is pushing its way into the spotlight of every consumer and business.
If you wonder what an NFT marketplace is and how you can develop one, you’ve come to the right place. This blog covers the basics of NFT and an NFT marketplace, the design process for a marketplace, and looks at the technologies you can use. If an NFT marketplace is on your business roadmap, the experts at QudaraByte, LLC can help accelerate your roadmap to launch with a fully customized solution.
What is an NFT?
So you’ve decided you want to build an NFT Marketplace as your next project or perhaps at the request of your boss or manager. Building a marketplace is relatively straightforward so long as you understand the underlying mechanics, architecture, and terminology. If you have found your way to this blog, it probably means you have had some level of exposure to blockchain and crypto. If this is you, you have probably at least heard the term NFT. So what exactly is an NFT?
In the crypto world, NFT stands for ‘non-fungible token.’ The meaning behind non-fungible comes from the concept of something having fungibility. Wikipedia defines fungibility as the property of a good or commodity whose individual units are essentially interchangeable and each of whose parts is indistinguishable from another part. An example of fungibility is to look at gold. If you have a block of pure gold with weight X, you can exchange that block for another block of the same weight. Thus, we define the two as being equivalent.
So if fungibility means you can trade one asset for another identical asset, what is non-fungible? Look around you and pick anything that you currently see in your home. FOR EXAMPLE, when I look around my office, I see a plant. My living, growing plant is a non-fungible asset that I own. I can not trade it for the exact same plant. That is not to say that I own a one-of-kind rare species of plant, but instead means I could not go out and find another plant with the exact weight, length, number of leaves, root structure, color pattern, and so on. My plant is unique, and there is no other plant like it. This applies to everything that you own. You couldn’t go out and get my exact same iPhone because my iPhone has a very specific scratch on the back of it. Or, to be more technical, the cellular module in my iPhone is unique from any other because of the hardware-level identifier built into it.
While a non-fungible asset may seem like a foreign concept, the reality is that you might consider everything around you to be non-fungible. The list of examples we could name for something fungible is minimal in comparison, making fungibility the more foreign concept.
Now that you understand the difference between both terms let’s take a closer look at NFTs. The NFT exploded into popularity in 2020 and has become increasingly popular within the crypto community. NFTs are simply a token, similar to a token from Bitcoin or Ethereum, that equates to something unique and rare. This is where the similarities stop. You can exchange a cryptocurrency token, such as from Ethereum, for another because we consider them equal value. You can exchange a single U.S. dollar bill for another because, once again, the value of both dollar bills is the same. However, you cannot exchange an NFT token for another because each token has a specific value based on the unique attributes that comprise it.
As a final note on the topic, we should understand why an NFT has value. An NFT is a token that represents ownership of something else. Your value is not in the token itself but the asset that the token represents. This could be a digital asset such as artwork or a movie or a physical asset such as real estate or a car.
A full explanation of NFTs is beyond the scope of this blog, but continue to check back as I am working on a post that will take a deep dive into the world of NFT.
What is an NFT marketplace?
To put it simply, an NFT marketplace is an online platform that enables you to create, trade, or sell NFTs. I hesitate to show my age with this analogy, but some of the most popular marketplaces are like a hybrid between Amazon and Neopets. You can use a marketplace to store your digital assets, display them like an online gallery, or list them for sale to others on the marketplace.
To use a marketplace, a user typically needs three things: a crypto wallet, the correct cryptocurrency in the wallet to make a purchase, and an account on the marketplace. While these are the minimum requirements, users might also have several created assets to upload to the marketplace. If these assets are not tokens being transferred or listed on the marketplace, the process of uploading them and making the NFT is referred to as minting.
We will stop our explanation of an NFT marketplace here, as I will assume you already have some level of understanding on this topic if you are exploring launching your marketplace.
Building your marketplace
The following sections will detail what is needed to build your NFT marketplace. While we have provided an overview of NFTs and an NFT marketplace, the remainder of this post assumes you have a more intermediate understanding of blockchain and NFT. We will detail topics specific to building your marketplace, but we will assume you understand the underlying blockchain technology.
For this article, we will focus on the Ethereum blockchain. Ethereum is the most popular blockchain currently supporting NFTs, but you could also use other chains such as Binance Smart Coin or Flow. Deciding on your blockchain of choice will define how your marketplace works and the audience you can reach. For example, you can purchase Ethereum NFTs with Ethereum-based tokens such as DAI, LITH, BNT, etc. However, you could not build your marketplace on Flow and use ETH or LITH to buy an NFT. Therefore, I urge you to think about what you want from your marketplace to select a suitable chain.
Building your Smart Contract
A marketplace is just a pretty concept if it does not have NFTs to interact with. NFTs are created on-chain through the use of Smart Contracts. Smart Contracts follow a standardized set of rules, which makes them the ideal choice for an NFT. Smart Contracts ensure that an NFT will always act in a specific way and define how you can execute interactions with those assets.
Ethereum uses two standards for NFT Smart Contracts: ERC721 and ERC1155.
ERC721 was the pioneer of the NFT frontier, creating the first standardized smart contract for developers to develop NFT-compliant contracts. When a new asset is uploaded, an instance of the ERC721 is created (instantiated), and an NFT token is minted. This token belongs to the individual who minted it and can be transferred to a new owner the same as you might send crypto tokens from one person to another. Each token stands on its own, and the concepts are relatively basic.
ERC1155 is the newer smart contract format and allows you to define assets into classes. We can look at sticks of gum to explain the difference between the two formats. If our gum factory follows the ERC721 format, each stick is owned and sold as an individual unit. When you go to the store to buy 20 sticks of gum, you must pick up each stick and make a separate purchase. After you complete 20 unique purchases, you will own those 20 sticks of gum. With ERC1155, you can buy a gum pack containing 20 sticks. When you buy or sell the pack of gum, you lose the history of each stick of gum, but the transaction becomes much more straightforward.
Since ERC1155 inherits the functionality of ERC721, you can have assets that you process at an individual level. This means I can sell a pack of 20 sticks, or I can sell individual sticks of gum. Because of this, the ERC1155 format has become increasingly popular for NFT marketplaces.
Once you decide on the standard you will use, we will use ERC1155 as the standard for the remainder of this post, you need to develop the Smart contract. The basic ERC1155 functionality that we recommend in a smart contract are:
- Batch transfer of multiple assets in a single transaction.
- Get the balance of an entire batch of assets with a single query.
- Allow for batch approval of all tokens sent to an address.
- Support interfacing with EIP-165.
- Create token hooks, similar to the concept of webhooks.
- Built-in NFT support.
- Built in secure transfer of tokens to protect assets.
Single Transaction Transfer of Batches
Transaction batching within an ERC1155 smart contract is similar to creating transactions within an ERC20 contract. ERC1155 defines a transferFrom function that accepts a from address, a to address, an array of IDs, and an array of values. It will also accept an arbitrary block of data which you can later capture using your token hooks.
ERC-1155 Code Example
function transferFrom(address _from, address _to, uint256 calldata _ids, uint256 calldata _values, bytes calldata _data) external;
Retrive The Asset Batch Balance
With an ERC20 contract, we can use the balanceOf function to return the balance of an address (0x1428). With ERC1155, we can pass an array of owners and an array of token ids to the batchBalance function.
ERC-1155 batchBalance Code Example
function batchBalance (address calldata _owners, uint256 calldata _ids) external view returns (uint256 memory);
Allow For Batch Token Approvals
Unlike ERC20, where you approve a set amount of tokens, the ERC1155 contract uses an all-or-nothing approach. Two functions are used for batch approval functionality: setApproval and isApproved.
function setApproval (address _operator, bool _approved) external; function isApproved (address _owner, address _operator) external view returns (bool);
To have an ERC1155 smart contract, you must supply the supportsInterface function and return it as true for the contract. Implementation of this interface allows for the use of token hooks. These magic hooks give you a lot of the same type of functionality as you might expect from a traditional webhook and will provide our marketplace with critical functionality.
One example of a token hook that I recommend you create for your marketplace is the onBatchRecieved hook. This is how we track the successful transfer of an ERC1155 token to a receiving contract.
function onBatchRecieved (address _operator, address _from, uint256 calldata _ids, uint256 calldata _values, bytes calldata _data) external returns(bytes4);
Remember when we said that the ERC1155 smart contract inherits many of the same properties as the ERC721? This is where the concept of a unique asset, a non-fungible token, comes together with smart contracts. If a token given is one and only one, it is considered an NFT. Since an NFT exhibits the primary properties of an ERC721 token, the ERC1155 smart contract will handle the token in much the same way using the properties it inherits.
Secure Token Transfers
To securely transfer tokens and ensure that assets are not forged or stolen, you need to implement rules for secure transactions. If moving NFT assets around within the same owner, you must check that the caller and the _from address are identical. If they are not, the owner of the _from address must approve the transaction the caller has initiated. Other considerations to give are reverting a transfer if the _to address is 0, there are more ids than there are values supplied in the arrays, the _from balance is lower than the values being sent, or in the event of errors.
While we can abort a transaction with a _to address of 0, please note that there is no guaranteed method to ensure a _to address is valid. Therefore, it is vital that your marketplace or UI handles this validation by asking the user to double-confirm the correct address. Once the token is transferred to an address, it cannot be retrieved whether it is valid or not. While this may seem like a flaw, many token minters will have a “burn wallet” to burn tokens and lower their circulation. A burn wallet has no owner, meaning anything sent to the burn wallet is lost forever.
Many YouTube and Medium tutorials will guide you towards designing your UI as the next step. While it might seem like the logical place to go, I firmly believe in backend development before frontend development. Many development environments have an out-of-the-box UI that works great for testing purposes. While you would like to think you’ve considered all elements of your marketplace and where they will live, the reality is that your implementation will evolve as you begin coding your functionality. Things that might have made sense in the abstract have now changed, and you end up with an entirely different implementation of a feature than how you originally envisioned it.
In the abstract, I always approach platform development, following a process that I believe creates a great foundation. Once this foundation is in place, I start to expand upon it by layering on the features specific to the platform I am building. At QuadraByte, we have boilerplate packages in most major languages (PHP, Ruby, Python, Node, etc.) that can be spun up and deployed within a few hours. This takes the overhead cost of standard functionality out of the development process and allows us to focus on delivering the unique platform experience quickly.
Taking this approach, the first feature we implement is the User Management system. How your users interact with the platform can define the entire paradigm of your platform-specific features and design. Most platforms offer some level of User Management, so this can be an excellent way to implement the DRY methodology (Don’t Repeat Yourself). Almost all of our boilerplate packages utilize the following features for User Management:
- User Registration, Login, and Logout
- User Groups with default group assignment upon registration
- Access Control LIsts (ACL) that can be applied to groups or individual users
- User Private Messaging
- User API Keys
A few of the unique ones that many people might not consider are ACL and API Keys. ACL is simply a method for controlling access to functionality within your system. The granularity of the ACL follows CRUD (Create, Read, Update and Delete). In this way, we wrap every controller in our platform with the ACL logic and give our Administrators the ability to assign permissions to every aspect of the platform without requiring them to write a single line of code. Furthermore, we often develop so that our backend and frontend are disconnected due to differing tech stacks or even being on entirely different servers. Since the frontend would logically interact with the backend via APIs, we might expose those APIs to the end-user. If and when that becomes the case, the offering is ready to go without additional coding.
Next, we will look at integrating a crypto wallet into our marketplace. Many wallets are out there, but perhaps the most popular wallet for integration is MetaMask. MetaMask has gained rapid popularity in the crypto world, it has a lower barrier of entry than most wallets for setup, and their development API is very well documented. You can support any wallet you want and even support multiple wallets, but for now, we will focus on the wallet with the highest level of adoption to capture the most number of users at our initial launch.
All NFT Marketplaces integrate some type of wallet to allow users to store, send and receive NFTs and cryptocurrency. Some businesses, especially those on closed blockchains such as Flow, will typically create their own wallet. There are many advantages to creating your own wallet, but your barrier of entry might be lower unless your wallet is cloud-hosted. While much easier to use, the downside of these wallets is their propensity to be less secure though you can mitigate many of those security risks.
Other popular wallet choices include MyEtherWallet and Coinbase.
Now that our users can log into the marketplace and attach their MetaMask wallet, we have to give them something to do. Since this is a marketplace for NFTs, the next logical step is to publish their NFT. You can approach NFT Minting in two ways, single-mode through the use of ERC721 or multi-mode through ERC1151. If you opted to implement an ERC1151 smart contract, you could offer both modes to your users as ERC1151 is functionally compatible with many of the same protocols as ERC721.
In short, an ERC721 NFT is unique, and the asset can not be copied, whereas an ERC1151 NFT can be copied.
Just like any other data you work with, NFTs have metadata. Metadata is data about the data. In the case of an NFT, it describes the traits, or “attributes,” of an NFT. This might be the name of the NFT, the current owner, an image URL, a description, or anything else you want to track on an NFT. More importantly than what metadata you want to track is your decision on where to store that metadata. Your two options are going to be on-chain and off-chain. These are exactly how they sound, and we will review both of them as viable options for your marketplace architecture.
We will start with looking at off-chain storage as it is the one you are probably most familiar with. Traditional off-chain storage solutions are servers or cloud storage that store the metadata in a database, file system, or other data medium. To link the metadata back to the NFT it belongs to, the metadata is usually stored alongside a token URI (or token ID) that allows the two to be associated.
The downside to using these storage mediums is that anyone can change metadata with proper access to the server. If the server goes offline, then metadata will become unavailable, and there is a risk that the metadata could be lost in the event of a data failure. One way that developers are combating these weaknesses in off-chain storage is through InterPlanetary File system (IPFS) storage.
IPFS still stores data off-chain, but it stores it in a peer-to-peer fashion. This means that the data is replicated across multiple computers participating in the peering network allowing the metadata to be immutable and persistent.
The alternative to off-chain storage is to store the data on-chain. Where off-chain storage has its failings, on-chain storage makes up for it. An NFT meant to hold value long-term, such as the NBA artwork, would need to ensure that its metadata is immutable and persistent, or the NFT would lose its value. In addition, on-chain storage means that metadata can change alongside any token changes.
Another consideration for on-chain logic is the ability for smart contracts to interact with the metadata. Similar to my Neopets comment earlier in this article, a wildly popular website called CryptoKitties uses on-chain storage to execute the logic of the “game.” It is very similar to Neopets in that each NFT represents a kitten, and the metadata is attributes about the kitten (name, breed, unique markings, gender, and so on). The smart contract behind these NFTs interacts with the metadata to determine breeding (how quickly does breeding happen, what does breeding two kittens yield, what generation is the result of two identical or two different generations, and more). Since all metadata is stored on-chain, the logic can interact directly with the metadata.
Listing Your Collections
Now that we have all of the underlying components to allow users to participate in the marketplace, we can do something with our NFTs. Up to this point, users have been able to mint an NFT on the marketplace and provide metadata about the NFT. It would be great to provide a gallery for users to show off their NFT collection, but we want users to participate in the marketplace actively.
Listing an NFT is precisely like it sounds. You take an NFT that you own and put it up for sale. There are two types of listings you can implement. I firmly believe you should implement both and give your users options, but your unique business needs may call for one over the other. The two types are list price and bidding. When you select list price, you tell other users how much you want for your NFT. This price is static, and it is first-come, first-served.
The second type is bidding. In this scenario, you put the minimum amount you’ll accept for the NFT and a bid close date. At the end of the bidding period, the user who has submitted the highest bid will be awarded the rights to the NFT.
Up until this point, we have finalized our listing functionality. There is still one more point to be decided, which could mean revisiting this code, but we will discuss it in the Funding A Purchase/Bid section.
Regardless of the type of listings you allow, it is still common to refer to the act of buying an NFT as bidding. The reason for this will be covered in more detail in the section on Acceptance, but, briefly, the reason is that no purchase is final until the owner gives final approval. Users are very protective of their NFT, and they also might later decide they want to unlist it or change the list price, which means they have to retain ownership of the item. Since our marketplace will not hold intermediary ownership of the NFT, we have to gain secondary approval from the owner once a bid is finalized.
Implementing only the list price functionality makes the bidding process is easy. A user navigates to an NFT of interest, clicks the purchase button, and moves into the funding phase of the process. If you have allowed your users to set up bidding, the user will follow a very similar flow, but the funding process will be slightly different. Let’s look at the funding process now.
Funding A Purchase/Bid
In the world of digital assets and digital currency, a business has no way to guarantee or back the assets being exchanged. To mitigate the risk to the company and prevent theft and other dishonest practices, a user funds every purchase or bid that comes through. It is up to the business how they wish to proceed at this point, and we will discuss why.
A fee accompanies every transaction on the Ethereum blockchain. This fee, known as gas, is required for the nodes to process the transaction. A full explanation of blockchain and why node computation is expensive goes beyond the scope of this post. In some instances, a business may choose to consume this fee as a “cost of doing business,” and in other cases, they may wish to pass this fee onto the end-user of the marketplace. Some scenarios involve handling these fees, and they all tie into funding.
The first and most common is soft fund the purchase or bid. This means that the bid is only accepted if the user making it has the funds available in their wallet. While the funds may be present at the bid time, this might not be the case once the NFT is confirmed for transfer. This means that a purchase request could fall through if the funds leave the wallet before the transfer is processed. However, no gas fees are paid in this instance because it is simply a check.
The second situation is to fund the transfer to a wallet held by the marketplace. This means that the funds are taken out of the buyer’s wallet and transferred to the marketplace wallet until the final NFT transaction is processed. Whether or not the NFT transfer goes through determines if those funds are later transferred to the seller or back to the buyer. Either way, a total of two transactions has occurred on the Ethereum network, and both transactions have their gas fees attached.
At this point, we should discuss gas fees and the possibility of revisiting our listing code. There are three ways you can choose to handle gas fees. As a business, you can take that cost on yourself. This means you do not charge either user any fee to list on your marketplace, which would mean you operate at a loss unless you are making up costs elsewhere or you pass on a flat fee. The advantage to a flat fee is that you could take advantage of transacting when gas fees are low, allowing you to keep the difference, but you would have to balance that with the fact that you could transact at gas fees higher than your flat rate.
The other method is to pass the gas fee off to the user. Doing this can be done in one of two ways. You can pass the gas fee to the seller, requiring them to pay a non-refundable “listing price” to list their NFT, take a percentage of the final price at transfer, or pass it to the buyer. In either instance, you still have the in-between fee for the funding wallet owned by the marketplace. Because of this, many businesses choose to tack on an additional fee. Example: (list price or final bid price) + (current gas fee) + (market fee). The market fee could be a flat fee, a percentage, or a variable fee (2% or flat fee, whichever is greater).
In all of the points we covered from the previous section, we assumed that the seller must approve a bid/purchase request. When we start looking at solutions such as tying NFTs to physical assets or creating real-world encryption of tokens, we recommend that you have a double-confirmation process in place. This prevents the seller from doubling back on the transaction during the transfer stage and the buyer losing both their funds and the ownership of the NFT.
This is why the funds would be pushed to a market-held wallet until the final transaction is ready to be processed. It ensures that the buyer doesn’t gain ownership of the NFT and retain their crypto and ensures that the seller doesn’t get paid and then pulls back on the sale.
You could also opt to auto accept the bid/purchase request. If this is the case, you’d altogether skip coding your Acceptance logic and move straight into the Fund & NFT Transfer logic.
Fund & NFT Transfer
Whether you choose to enable double-acceptance or have auto-acceptance, it is time to fund the transfer and process the transaction. This is pretty straightforward, and the steps involved are simple:
- The funds leave the buyers wallet, or the market wallet if you went through a funding and accpetance process, and transfer to the sellers wallet. At the same time, the NFT token leaves the sellers wallet and transfers to the buyers wallet. This is a one-to-one transaction.
- During the funding process, some value of the cryptocurrency might be diverted to a market-held wallet to cover the cost of gas and other agreed upon fees.
- Lastly, the transaction is pushed to the blockchain.
Being able to buy and sell on your marketplace is great, but users have to find NFTs. Amazon conducts 65% of its business through its landing page, or storefront, from users who visit the site. A storefront shows all of the metadata you need about assets that are for sale: ownership, price, preview or thumbnails, and the value history.
You can choose to make your storefront more advanced by adding algorithms that decide how to serve up assets to each user based on viewing history, purchase history, values on their user profile, cookies, and more. The sky is the limit, and you’ll quickly find that your marketing team will get very excited with the different ways in which they can encourage users to make a purchase.
NFT Searching & Filtering
A storefront is excellent, but if your storefront is basic or your algorithms fail to capture my attention, then I need another way to purchase an NFT. This is where searching and filtering come in. We live in the age of Google, Amazon, online shopping, and e-commerce. I won’t spend much detail here as this functionality is very similar to other online search engines. The metadata is already present for each NFT on your marketplace, so feel free to get as creative as you would like.
Rate A User
Finally, we should allow our buyers to rate a seller. Seller ratings tell us how trustworthy a user was in previous transactions, were they liable to pull the listing and raise the price during the buying process, and were they responsive to user inquiries. Having a feedback system allows buyers to check the credibility of a seller and incentives a seller to behave in a trustworthy manner.
Your UI/UX design is your chance to make the first and a lasting impression on your users. There are many directions that you can go with UI/UX design, and design practices are constantly changing. I always recommend that you separate your frontend and backend logic, and it is entirely reasonable to assume that the two codebases will not share the same technology stack. One popular combination is to build a Python backend with a React.js frontend.
Whether you choose to write test cases or do manual QA testing, you’ll need to be able to test the functionality of your market without investing a lot of money into cryptocurrency and gas fees. Ethereum has created two types of networks for their blockchain: Mainnet and Testnet. Mainnet is the production blockchain of Ethereum and deals with the actual exchange of tokens that have value. Testnet functions similarly and is token-based, but the value of tokens on Testnet is none. A popular Testnet is Ropsten, but there are others you can use. At the time of this writing, there are four Ethereum Testnets.
Once you have ensured that your marketplace functions the way that you expect, you can move it off of Testnet and onto Mainnet. This should coincide with your production deployment process, as you do not want to run a testing environment on the Ethereum Mainnet.
During the design and development of your marketplace, there will be many decisions you need to make as a business. I tried to call out most of them in their relevant sections, but I wanted to touch on some important considerations here. This is far from an exhaustive list of decisions you will need to make, but I hope it will help you start thinking through some less obvious development tasks.
First, as a business, you need to consider your monetization program. Unless your marketplace is an investment to draw customers into other parts of your business, think about a costly Google Ads campaign. You will have a goal of making money off your marketplace. One way, which we mentioned earlier, is to add a platform fee to every transaction in addition to the gas fee. Passing the gas fee off to the user (buyer or seller) is one less line item your business has to pay for and allows you to take more of the platform fee into the business. A popular model we see at QuadraByte is a variable fee that requires the user (most commonly the buyer) to pay a flat fee or a percentage, whichever is greater.
Second, you will want to give a lot of those to security. Multi-factor authentication, integration with more secure wallets like MetaMask, and even built-in smart contract security are all security features you should consider implementing. Your users need to feel safe and secure trading on your platform. If a user loses a valuable NFT they were trying to sell, or a buyer gets ripped off thousands of dollars in ETH, they will not only refuse to do further business with you, but you could lose other users as a result.
Finally, your marketplace should be as transparent as possible to your users. This isn’t just listing what security you have in place to protect their assets but also providing a transparent audit trail of all transactions performed. This allows buyers to research an NFT, builds trust in both the platform and the seller, and works to improve the buying experience. The entire premise of blockchain is to provide a transparent, decentralized, and uncensored method for transmitting data.
The world of blockchain and crypto is changing and evolving every day. It seems that I can’t open my news feed on any given morning without seeing the emergence of a new token, a new marketplace, or some cool dApp (decentralized application). Even now, we are hearing the term “metaverse” used more often in conjunction with blockchain, and the world is excited to see who will enter the spotlight with the first actual implementation of metaverse and blockchain.
Apart from building your own NFT Marketplace, you could choose to white label it. Many providers will create a white label solution, and I would urge you to give full consideration to the functionality and control you have over those solutions before you travel that path. Those solutions are still costly in time and money to implement, and it is not a fun experience to stand one up only to find that you should have built your marketplace from scratch.
Are you interested in building a marketplace for your business? QuadraByte, LLC specializes in blockchain, dApp development, and data and analytics. Reach out to them today to speak with one of their experts and get a customized quote and solution.