Dynamic NFT: Web3 Game Changer

2023-11-03

What Are Dynamic NFTs?

Non-Fungible Tokens (NFTs) have emerged as a revolutionary concept in the digital world. Enabling unique digital assets to be owned and traded on the blockchain. However, static digital assets are only the tip of iceberg in the evolution of NFTs. Enter Dynamic NFTs (dNFTs), a new breed of NFTs that can evolve and interact with real-world data.

Unlike traditional NFTs, which have fixed metadata once they're minted, dNFTs have the ability to change over time. They are encoded with smart contract logic that enables them to update their metadata based on external inputs or conditions. This dynamism allows dNFTs to represent digital assets that can change and evolve, reflecting real-world changes or the progression of virtual events.

Dynamic NFTs: Redefining Digital Experiences

Dynamic NFTs are redefining digital experiences across various industries by unlocking new potential for engagement and innovation. Let's explore some examples of how dynamic NFTs are transforming different sectors:

  1. Digital Art: An artist could design an NFT that adapts to the time of day or weather, shifting from a bright day scene to a starry night as sunset approaches.
  1. Web3 Social: Lens Garden is a dynamic NFT in the Lens Protocol ecosystem, rewarding users with XP points for activities like staking, governance participation, or community contributions. As XP accumulates, the NFT unlocks new features.
  1. Gaming: Around 2,127 web3 games have failed from 2018 to 2023, or 75% of the games that were launched. To improve that, DNFTs in gaming can evolve with player use. For example, a sword NFT might begin basic and level up, gaining abilities or changing appearance as players advance.
  1. Real World Assets (RWA): The real estate sector can use dNFTs to uniquely represent properties. An NFT could show a property's value changes and auto-update with market prices, features, or virtual tours after renovations.

These examples demonstrate the transformative power of dynamic NFTs across digital art, social interactions, gaming experiences, and real estate transactions. By embracing dynamic NFTs, industries can create immersive and engaging experiences that push the boundaries of traditional digital interactions.

What Challenges Are Holding Dynamic NFTs Back?

Dynamic NFTs hold immense potential, but their implementation faces significant challenges due to the inherent limitations of blockchain technology. These include: 1. Immutable metadata: Once minted, an NFT's metadata becomes unchangeable. This poses challenges for Dynamic NFTs which need adaptable metadata. 2. Deterministic Nature and External Data: Blockchains can't directly access external data, crucial for Dynamic NFTs. Additionally, without a secure method to integrate real-world data, the trustworthiness of Dynamic NFTs could be compromised. Maintaining off-chain data integrity is vital for their reliability. 3. Challenges in Onchain Gaming: Designing incentivized onchain games is problematic due to their deterministic nature. Solutions like seasonality and novel governance methods need more exploration and development.

How to Build Dynamic NFTs

Building Dynamic NFTs requires a combination of smart contract development, data integration, and front-end implementation. Here are the key steps involved in creating Dynamic NFTs:

1. Design the NFT Contract: Begin by designing and implementing the smart contract that will govern the behavior of the NFT. 2. Off-Chain Computation: Perform off-chain computation using external data sources to generate new metadata based on real-time or dynamic data. This could involve retrieving data from APIs, oracles, or other external sources. 3. Upload New Metadata to IPFS: Once the new metadata is generated, upload it to IPFS (InterPlanetary File System) or a similar decentralized storage system. This ensures that the updated metadata is accessible and can be associated with the NFT. 4. Update the Hash in the Contract: Finally, update the hash of the metadata in the smart contract to reflect the newly uploaded metadata on IPFS. This allows users to retrieve and verify the latest metadata associated with the dynamic NFT.

By following these steps, you can create compelling Dynamic NFTs that evolve and respond to real-world data, providing an engaging and interactive experience for collectors and users.

Phat Contract: The Future of Dynamic NFTs

Phat Contract, developed by Phala Network, presents a solution to these challenges by bridging the gap between on-chain and off-chain environments. It is an off-chain program that developers can use to implement a broad range of features for their decentralized applications (dApps).

How Phat Contract Solves the Problem

Phat Contract is a powerful smart contract framework that provides a range of key features to help developers build dynamic NFTs with ease. Here are some ways that Phat Contract's features benefit dynamic NFTs:

  1. Dynamic Data Integration: Phat Contract's dynamic data integration feature allows developers to easily integrate external data sources into their smart contracts. This enables dynamic NFTs to retrieve real-time data from APIs or oracles and use it to update their metadata or attributes, creating a more engaging and immersive experience for users.
  1. Flexible Logic: Phat Contract's flexible logic feature allows developers to define complex rules and calculations within their smart contracts. This makes it easy to create dynamic NFTs that respond to changes in real-world data, such as market prices or weather conditions.
  1. Secure and Scalable: Phat Contract is built on top of secure and scalable blockchain technology, ensuring that dynamic NFTs built with Phat Contract are secure and can scale to meet demand. This is crucial for NFTs that require high levels of security and reliability, such as those representing high-value assets like real estate or collectibles.

By leveraging these features, Phat Contract provides a powerful solution for building dynamic NFTs that can transform digital experiences across various industries. With Phat Contract, developers can easily create engaging and interactive NFTs that respond to real-world data, providing users with a unique and immersive experience.

By leveraging these capabilities, Phat Contract empowers developers to create Dynamic NFTs that can adapt and evolve based on real-world data and events. This overcomes the limitations of traditional static NFTs, opening up a world of possibilities for NFT innovation.

Dynamic NFT Examples

Upgradable NFT Collection

The concept of upgradable NFTs is a revolutionary one, and Phat Contract is at the forefront of this innovation. Let's take a look at the work done by developer Paco Yang on GitHub. He created a Next.js project that lays the groundwork for an upgradable NFT collection.

For web3 builders, this use case demonstrates how you can create NFTs that are not static but can evolve over time. This opens up a new dimension of possibilities for NFT creation, making them more interactive and engaging for users.

#[ink::contract(env = pink::PinkEnvironment)]
mod phala_nft_collection {
    #[ink(storage)]
    pub struct PhalaNftCollection {
        owner: AccountId,
        name: String,
        description: String,
        total_nfts: u32,
        nfts: Mapping<u32, Nft>,
        // JS code to dynamically compute NFT metadata
        compute_formula: Option<String>,
    }

    impl PhalaNftCollection {
        #[ink(constructor)]
        pub fn create(name: String, description: Option<String>) -> Self {
            Self {
                name: name.clone(),
                description: description.unwrap_or(String::from("")),
                owner: Self::env().caller(),
                nfts: Mapping::new(),
                total_nfts: 0,
                compute_formula: None,
            }
        }

        #[ink(message)]
        pub fn mint(&mut self, token_id: u32, account: AccountId) -> Result<u32, Error> {
            // Mint NFT ...
        }

        #[ink(message)]
        pub fn levelup(&mut self, token_id: u32, account: AccountId) -> Result<u32, Error> {
            // Levelup the NFT data ...
        }

        #[ink(message)]
        pub fn get_nft_metadata(&self, token_id: u32) -> Result<NftMetadata, Error> {
            // Return the NFT metadata ...
        }
    }
}

Another interesting use case is presented by Keshav Sharma in his project PokeLens on understanding LensAPI Oracle by Phala Network. In his post, Keshav explains how Phat Contract can be used to create dynamic NFTs that change based on Lens data fetched from APIs.

The idea is to create a smart contract that rewards with an evolved NFT if you accomplish the checkpoints. There are three checkpoints - Level 0, Level 1 & Level 2.

  • Level 0: i.e. Pichu is the bare minimum that can be claimed by an account if the Lens Profile has less than 10 total followers, 50 total posts, 50 total comments, 10 total mirrors, and 10 total collects.
  • Level 1: i.e. Pikachu can evolve from the prior if the profile is in the range of 10-50 total followers, 50-100 total posts and comments, and 10-20 total mirrors and collects.
  • Level 2: i.e. Raichu can be acquired if the profile is above 50 total followers, 100 total posts and comments, and 20 total mirrors and collects.

On-Chain Games

Phat Contract is also being used to create fully on-chain games. For instance, developer Shubham Patel has used Phat Contract to create a game called "Lens-Phite". This game leverages the power of Phat Contract to perform complex off-chain computations in real-time, providing a seamless gaming experience.

For web3 builders, this use case shows how you can create immersive gaming experiences entirely on-chain. This not only provides transparency and security, but also opens up new possibilities for player interaction and engagement.

For example, the code below represents the body of the function fetchLensApiStats(lensApi: string, profileId: string) where the Lens Phite game is able to make a batchHttpRequest to get information from Lens API and Railway API to retrieve the 3 available attacks and the nature properties of the Lens Profile fighter NFTs. These dynamic properties allow for the Lens Phite game to have strong attacks based on how much the user interacts on Lens Protocol creating a progression mechanism that lives in and outside of the gaming application.

let headers = {
  "Content-Type": "application/json",
  "User-Agent": "phat-contract",
};
let query = JSON.stringify({
  query: `query Profile {
          profile(request: { profileId: \"${profileId}\" }) {
              stats {
                  totalFollowers
                  totalFollowing
                  totalPosts
                  totalComments
                  totalMirrors
                  totalPublications
                  totalCollects
              }
          }
      }`,
  });
let body = stringToHex(query);
// In Phat Function runtime, we not support async/await, you need use `pink.batchHttpRequest` to
// send http request. The function will return an array of response.
//
let [response1,response2] = pink.batchHttpRequest(
  [
    {
      url: lensApi,
      method: "POST",
      headers,
      body,
      returnTextBody: true,
    },
    {
      url:`https://node-api-production-bfa7.up.railway.app/api/products?lens_id=${profileId}`,
      method:"GET",
      headers,
      returnTextBody:true
    }
  ],
  10000
);

if (response1.statusCode !== 200) {
  console.log(
    `Fail to read Lens api with status code: ${response1.statusCode}, error: ${
      response1.error || response1.body
    }}`
  );
  throw Error.FailedToFetchData;
}
let respBody = response1.body;
let resBody2 = response2.body;
let aa = [];
aa.push(respBody,resBody2);

Another example comes from developer Koisose, who created a game called "Lens Contract Fighter". This game showcases how Phat Contract can be used to create immersive on-chain games with dynamic features.

This use case can inspire web3 builders to leverage the power of smart contracts to create applications that are not only fun but also leverage the unique advantages of blockchain technology.

Gamification: Weather-Based Dynamic NFTs

Another fascinating application of Phat Contract is the creation of weather-based dynamic NFTs. These are NFTs that change based on local weather conditions. This is made possible by Phat Contract's ability to fetch real-time data from wttr.in and use the formatted results to update the NFT metadata that is stored on IPFS via 4Everland S3 API. This makes it possible to have an end-to-end solution in a fully decentralized way. We can take a look at the diagram of the mint and update process of the dynamic NFT below.

This is all made possible with the following code snippets in TypeScript.

Here we fetch the weather from wttr.in API.

function fetchWeatherApi(apiUrl: string, city: string): any {
  const weatherFormat = '?format={"name":"%l","description":"Weather+in+%l","external_url":"https://wrlx-bucket.4everland.store/%l/weather","image":"%x","attributes":[{"trait_type":"timestamp","value":"%T+%Z"},{"trait_type":"city","value":"%l"},{"trait_type":"weather","value":"%C+%t"}]}';
  const httpUrl = `${apiUrl}${city}${weatherFormat}`;
  let headers = {
    "Content-Type": "application/json",
    "User-Agent": "phat-contract",
  };
  let response = pink.httpRequest({
    url: httpUrl,
    method: "GET",
    headers,
    returnTextBody: true,
  });
  let respBody = response.body;
  if (typeof respBody !== "string") {
    throw Error.FailedToDecode;
  }
  console.log(respBody);
  return JSON.parse(respBody);
}

Next, we update the off-chain storage by calling the Rust SDK Phat Contract that is connected to S3 API from 4Everland. You can see the function is called invokeContract() where the callee is the contract id of the Rust SDK Phat Contract, selector is the hex number to the function we are calling and input is the SCALE encoded parameters to the selector function.

function updateS3Storage(city: string, metadata: string) {
  let uint8Array = new Uint8Array(metadata.length);
  for (let i = 0; i < metadata.length; i++) {
    uint8Array[i] = metadata.charCodeAt(i);
  }
  const endpoint = 'endpoint.4everland.co'
  const region = 'us-west-1'
  const bucket = 'weather-bucket'
  const object_key = `${city}/weather`;
  const value = uint8Array;
  const bytes = WalkerImpl.encode([
    endpoint,
    region,
    bucket,
    object_key,
    Array.from(value)
  ], encodeS3Put)
  const decoded = WalkerImpl.decode(bytes, decodeS3Put)
  console.info(`input decoded: ${decoded}`)
  console.log(bytes);
  const delegateOutput = pink.invokeContract({
    callee:
        "0x6295f7139ce951f25037419c444348591a4c401fb37ab9e5ccc7a1e2165d6cae",
    selector: 0x4ea2cb61,
    input: bytes,
  });
}

We can visualize this process in the short video of the minting process.

Conclusion

For web3 builders, this use case opens up a whole new realm of possibilities for gamifying real-world data. By integrating real-world information into NFTs, you can create unique and engaging experiences for users.

Dynamic NFTs are not just a novel concept anymore. With the power of Phat Contract, they are becoming a reality. As we continue to explore the potential of this technology, we can expect to see even more innovative applications in the near future.

About Phala

Phala Network is a decentralized cloud that offers secure and scalable computing for Web3.

With Phat Contracts, an innovative programming model enabling trustless off-chain computation, developers can create new Web3 use cases.

Get the latest Phala Content Straight To Your Inbox.