March 18, 2022

How OpenSea Trades NFTs Without Gas Fees

Table of Contents

In this article, we’re going to take a closer look at a simple Web3 project to illustrate how OpenSea trades NFTs without gas fees. If you’d like, you can skip right to the code explaining gasless NFT trading on OpenSea by visiting the following GitHub repository:

Complete Gasless Metaverse Documentation –  https://github.com/DanielMoralisSamples/31_Gasless_Metaverse 

If you’re familiar with the crypto space, you know that all blockchain interactions require gas fees. Furthermore, the gas requirement can result in high costs if you’re operating any metaverse platform since they usually facilitate a high number of transactions. However, to make it more lucrative to operate a Web3 platform, it’s possible to push the transaction costs onto the buyers of, for example, NFTs. A successful platform utilizing this strategy is OpenSea. Herein, we’re going to discover how OpenSea trades NFTs without gas fees. 

To demonstrate how gasless NFT trading on OpenSea works, we’ll look closer at a Web3 project developed using Moralis. The project will allow us to generate coupons for in-game items that can be distributed to users. The users can, in turn, claim a coupon in our UI to receive the item. As such, we’re pushing the transaction – and, therefore, the gas fee – to when the users claim their coupon.

Through Moralis, the process of creating this project becomes relatively accessible. In fact, the backend infrastructure of the operating system does most of the heavy lifting. This allows us to cut our blockchain project’s development time by an average of 87%. Moreover, tools such as the Moralis NFT API allow you to build dapps quickly and easily. 

If you have ambitions to become a blockchain developer, sign up with Moralis right away and begin your Web3 journey! 

What is OpenSea? 

Before we take a deep dive into the project of this tutorial, it’s a good idea to gain a better understanding of OpenSea. As such, we’re going to initiate this tutorial by explaining what OpenSea is, as this will provide a good foundation for understanding how the platform trades NFTs without gas fees. So, with no further ado, what is OpenSea? 

OpenSea is a centralized service that utilizes a decentralized blockchain. Further, it’s an NFT (non-fungible token) marketplace for creating, selling, buying, and trading NFTs. Moreover, OpenSea brands themselves as the first and largest NFT marketplace in the world for digital assets. 

The platform was founded in late 2017, suggesting that the NFT marketplace concept is relatively new. Since its formation, OpenSea has seen tremendous growth and is increasingly becoming known to the average person. In fact, OpenSea surpassed the $3.5 billion in Ether trading volume in January of 2022 alone, suggesting that the platform is hotter than ever before. 

Furthermore, the platform features large and well-established collections of NFTs such as Bored Ape Yacht Club, Mutant Ape Yacht Club, CryptoPunks, and many more. This suggests that OpenSea is a great platform if you want to get into NFT collectibles. Moreover, if you’d like to learn more about creating your own NFT collection, check out our article on how to mint 10,000 NFTs

So, now that we have an idea of what OpenSea entails, we can move on to the next section, where we’ll discuss why gas fees matter for NFTs and how gasless NFT trading works on OpenSea.

Why Do Gas Fees Matter for NFTs?

Metaverse platforms often facilitate a high number of blockchain transactions. These can come in the form of, for example, NFT trading or whenever a user creates a new token. With the high quantity of transactions and high Ethereum gas fees, the operational costs for running a platform can make it economically unviable. As it can become extremely expensive, this issue highlights the importance of why gas fees for NFTs matter. So, how can we avoid this problem? 

Let’s take OpenSea as an example. The platform allows you to list NFTs without paying any gas fees. This is achieved by pushing the blockchain transaction forward to when someone purchases the token. But, when listing an NFT on OpenSea, the seller’s MetaMask – or any other wallet – will trigger. However, this is only to sign a parameterized off-chain order message. As such, OpenSea stores the parameters of a sell order, the hash of those parameters, and the signature of the hash. 

This suggests that no blockchain transactions occur before the point of purchase. By utilizing this strategy, the seller of an NFT along with the platform is free from the burden of paying any gas fees. Instead, it’s the buyer of the NFT that pays for the transaction, which only makes sense as they receive the most value. 

Now, this is the strategy allowing for gasless NFT trading on OpenSea. As such, we’ll take the remainder of this article to discover more about how OpenSea trades NFTs without gas fees by delving deeper into the code.

Gasless NFT Trading on OpenSea – How Does it Work? 

We’ll show you how OpenSea trades NFTs without gas fees in the following section. To illustrate, we’ll break down the code for a project that allows us to create coupons for in-game items that users can redeem to acquire the items themselves. By doing so, we’re pushing the actual blockchain transaction to when a user claims an item through a coupon. As such, the users will pay for the gas fees when they receive their item. 

Through this process, we’re able to lower the operating costs of our project, making it more economically sustainable to operate the platform. Moreover, this process isn’t limited to gaming platforms and can be utilized when creating any metaverse project. 

Nonetheless, to make the process more comprehensible, we’ll break down the tutorial into three different parts. In each part, we’re going to take a close look at some of the essential components making this all possible. As such, these are the three parts of this guide on how gasless NFT trading on OpenSea works: 

  1. Creating the Coupon Generator
  2. Developing a Smart Contract
  3. Creating the UI

So, without further ado, let’s take a closer look at the initial section, where we take a closer look at the coupon generator of the project! 

Part 1: How OpenSea Trades NFTs Without Gas Fees – Creating the Coupon Generator

As was mentioned in the preceding section, the project we’re taking a closer look at consists of three parts. Moreover, we’ll dedicate this section to explaining the first part, which will be the coupon generator. The coupon generator will be a simple application made up of two files: ”index.html” and ”logic.js”. You’ll be able to find the complete code for these files in the GitHub repository. 

The HTML file is relatively straightforward and contains the code for the fields and buttons of the coupon generator’s UI. The code is quite self-explanatory, meaning we won’t be diving any deeper into this file. However, this is what it looks like once the platform launches: 

The JavaScript file is more interesting to look at as this is where we find the logic for generating the coupons. First up, we have the ”login()” function, which simply initializes the Moralis SDK. This is important as the kit provides access to some essential functions that are ready to use ”out of the box”, one of which is a message hashing function. 

async function login(){
    Moralis.Web3.enableWeb3().then(async function (){
        const chainIdHex = await Moralis.switchNetwork("0x2A");
    });
}

The message hashing function executes when we call the second function of the JavaScript file: ”grantCoupon()”. Further, this function creates an object using the input elements from the UI. This object is then stringified and hashed. Following the hashing of the object, we utilize the hash to create the signature. The signature and the hash are then combined into the complete coupon, which is returned to the UI: 

async function grantCoupon(){
    const objectType = document.getElementById("objectType").value;
    const objectRank = document.getElementById("objectRank").value;
    const damagePoints = document.getElementById("damagePoints").value;
    const object = {"objectType":objectType,"damagePoints":damagePoints};
    const hash = ethers.utils.hashMessage(JSON.stringify(object));
    const signature = await ethereum.request({
        method: "personal_sign",
        params: [hash, ethereum.selectedAddress],
      });
    const coupon = hash+signature;
    document.getElementById("coupon").value = coupon
}

Part 2: How OpenSea Trades NFTs Without Gas Fees – Developing a Smart Contract

With a better idea of how the coupon generator works, we can move on and take a closer look at the smart contract for the project. We will in this section cover the most critical parts of the contract; however, you’ll be able to find the full contract code in the GitHub repository: ”verify.sol”. Also, you can read more about smart contracts and how to create smart contacts at Moralis. 

If you are somewhat familiar with Web3 development, you’ll likely have no trouble understanding what the contract does. However, as the contract is written in Solidity, some proficiency in this programming language will be beneficial. Moreover, the contract was developed using the Remix IDE. As such, if you haven’t already, you might need to familiarize yourself with Remix to better follow along in this section. 

The main point of the contract is to verify that the correct admin account signed the message and the signature. If this happens to be the case, it will trigger some form of on-chain action. Moreover, the contract consists of two main functions: ”verifyMessage()” and ”claimCoupon()”. 

Gasless NFT Trading on OpenSea – Smart Contract Functions: “verifyMessage()” and “claimCoupon()”

The first function is ”verifyMessage()”, which compares the account that signed the message to the admin address. By doing so, we can ensure that the admin address creates all redeemable coupons so not anyone can create new items in our game. In this instance, we have hard-coded the admin address initially in the contract. Nonetheless, this is what the function looks like: 

function verifyMessage(bytes32 _hashedMessage, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (bool) {
        bytes memory prefix = "\x19Ethereum Signed Message:\n32";
        bytes32 prefixedHashMessage = keccak256(abi.encodePacked(prefix, _hashedMessage));
        address signer = ecrecover(prefixedHashMessage, _v, _r, _s);
        return signer == admin;
    }

The second function is ”claimCoupon()”, and the function first checks if the coupon has already been claimed. Also, the function additionally makes sure that the signer is equal to that of the admin address through the ”verifyMessage()” function. If both these prerequisites are fulfilled, an on-chain action will execute. However, as you might notice in the contract code, you’ll need to add the logic yourself, depending on what you’d like the contract to do. 

function claimCoupon(bytes32 _hashedMessage, uint8 _v, bytes32 _r, bytes32 _s) external {
        require (!claimed[_hashedMessage],"coupon already claimed");
        require (verifyMessage(_hashedMessage, _v, _r, _s),"Invalid signature or incorrect hash");
        claimed[_hashedMessage] = true;
        //your logic for the copon here
        emit CouponClaimed(_hashedMessage, msg.sender, block.timestamp);
    }

Moreover, if you’re planning on compiling and deploying the contract through Remix, you’ll first need to copy the ABI and the contract address. We need both these elements in the following part. 

Part 3: How OpenSea Trades NFTs Without Gas Fees – Creating the UI

In the final part, we’ll take a closer look at the UI where the users will be able to claim items through coupons. Much like the coupon generator, this part also consists of two files: ”verify.html” and ”logic-verify.js”.

Moreover, the HTML file contains an input field and a button for verifying the coupons. Since it is self-explanatory, we won’t dive any deeper into the code. However, this is what the UI looks like: 

Next up, we have ”logic-verify.js”, and before we dive deeper into the functions, you’ll notice that you’re going to need to implement the contract address and the ABI that we copied in the previous step from Remix. This will look something like this in the code: 

const protocolContract = ""; // your contract address here
const protocolABI = [{}]

Following this, we have the same ”login()” function used in the coupon generator. As such, you already know the essentials of this piece of code, meaning that we’ll not explain it in any further detail. 

After ”login()” we have the ”splitCoupon()” function. This function essentially splits the coupons into different parts. These parts are then used when executing the smart contract that we created in the previous step. Here is the complete function: 

function splitCoupon(coupon){
    const hash = coupon.slice(0,66);
    const signature = coupon.slice(66, coupon.length);
    const r = signature.slice(0, 66);
    const s = "0x" + signature.slice(66, 130);
    const v = parseInt(signature.slice(130, 132), 16);
    signatureParts = { r, s, v };
    console.log([hash,signatureParts])
    return ([hash,signatureParts]);
}

Then we have the most important function, which is ”verify()”. This function gets the coupon, calls the ”splitCoupon()” function, acquires the hash and the signature, and finally calls the contract with the proper parameters. As such, this is what the function looks like:

async function verify(){
    const coupon = document.getElementById("coupon").value;
    const couponParts = splitCoupon(coupon);
    const hash = couponParts[0]
    const signature = couponParts[1]
    const contractOptions = {
        contractAddress: protocolContract,
        abi: protocolABI,
        functionName: "claimCoupon",
        params: {
            _hashedMessage: hash,
            _r:signature["r"],
            _s:signature["s"],
            _v:signature["v"]
        }
    }
    try{
        const transaction = await Moralis.executeFunction(contractOptions);
        await transaction.wait();
        displayMessage("00","Transaction confirmed with hash "+transaction.hash);
    }
    catch(error){
        displayMessage("01","Transaction reverted see console for details");
        console.log(error)
    }
}

Now that’s it! If you followed along, you now know one method of how OpenSea trades NFTs without gas fees! However, if questions remain regarding the code, we recommend checking out the following video from the Moralis YouTube channel, where you’ll find a more detailed breakdown of the code:

Gasless NFT Trading on OpenSea – Summary

Blockchain interactions require gas fees which suggests that it can become quite expensive to operate a metaverse platform. Thus, it’s only logical to minimize the number of blockchain transactions to lower operational costs. One platform that has successfully implemented such a strategy is OpenSea. The OpenSea platform trades NFTs without gas fees by pushing transactions to the point of purchase.

So, how does gasless NFT trading on OpenSea work? Well, in this article, we provided a walkthrough of a Web3 project that demonstrates how this can be accomplished. When creating new items for this project, a coupon is generated, which, in turn, can be redeemed by a user. When generating a coupon, no on-chain transaction takes place. As such, the transaction costs befalls the users and not the platform operators. 

There were three parts for this tutorial on how gasless NFT trading on OpenSea works: 

  1. Creating the Coupon Generator
  2. Developing a Smart Contract
  3. Creating the UI

These three parts or components of the project allowed us to provide the same gasless NFT trading functionality similar to what is used by OpenSea. Moreover, as we’re using the Moralis operating system, we were able to accomplish this in minutes.

However, this is only one of many instances in which Moralis shines. If you have further interest in blockchain development, check out the Moralis blog. Here you’ll find additional tutorials on, for example, how to create your own NFT, how to build a Web3 Spotify clone, how to create an ERC-721 NFT, and much more! 

So, sign up with Moralis and begin your Web3 development journey today! Joining the platform is free, and you’ll receive immediate access to all the benefits of working with the Moralis operating system. 

NFT API
Unlock the full potential of your NFT projects with this industry-leading NFT API! Fast, easy, and free.
NFT API
Related Articles
November 29, 2023

List of Smart Contract Ideas and Examples for Developers

November 17, 2022

Exploring the Optimism Network – A Next-Gen L2 Blockchain for Ethereum

February 2, 2023

Aptos Testnet Faucet – How to Get Testnet APT from an Aptos Faucet

February 22, 2023

Data Availability in Blockchains – Exploring the Data Availability Layer

January 17, 2023

Polygon Mumbai Faucet – Get Free MATIC with this Mumbai Faucet

January 20, 2023

Gwei to ETH – How to Calculate and Convert Gwei to Ether

December 7, 2022

Python for Ethereum Development – Build a Web3 Ethereum Python App

November 22, 2022

Creating a Lambda Function – Learn How to Create an AWS Lambda Function

October 18, 2022

Add Dynamic Web3 Authentication to a Website