Optimizing NFT Smart Contract Event Tracking for Genuine Undead

In the rapidly evolving landscape of Web3, Non-Fungible Token (NFT) projects often rely on robust infrastructure to bridge on-chain events with off-chain application logic. This case study details an infrastructure challenge faced by the team behind the Genuine Undead NFT collection on Ethereum. The core issue involved inconsistent event log fetching for their "engraving" service, leading to data discrepancies and potential user experience concerns. This document outlines the problem, the implemented solution, and the notable benefits achieved through a strategic technology migration and code refactoring.

Client Background: Genuine Undead and the "Engraving" Service

The client, the team behind the popular Genuine Undead NFT collection, offers a service called "engraving." By default, the visual assets for their NFTs are hosted on traditional servers. However, users have the option to "engrave" their NFTs. This process involves front-end code encoding the NFT's SVG image data into a base64 format, and this data is then submitted to their Ethereum smart contract for on-chain storage. Crucially, this on-chain action emits a TokenEngraved event, which is vital for off-chain systems to track the engraving status.

The client's Next.js site includes a backend system designed to monitor these engraving events. A cron job regularly triggers code that polls the Ethereum blockchain for new TokenEngraved events emitted by the contract. Upon detection, the event data is stored in a MySQL database. To ensure continuity and prevent redundant processing, the system uses the block number of the last saved event as an index, searching for new events up to the current Ethereum block number.

The Problem: Inconsistent Event Log Fetching with Moralis

The primary challenge encountered was an inconsistency in fetching these crucial TokenEngraved event logs. Despite verifying the presence of these events on Etherscan by directly inspecting the contract logs, the backend system, which utilized the Moralis API for blockchain services, was failing to retrieve them reliably. This suggested either a misconfiguration of Moralis's usage or an inherent issue with its querying capabilities for these specific contract logs.

Beyond the core event fetching problem, Moralis's integration also presented a minor technical hurdle:

  • When querying the current Ethereum block number via a Moralis node, the returned value was a BigInt type, which sometimes led to subtle comparison issues with standard Number types in the application's logic.

The Solution: Migrating to Alchemy

To address these issues, the core of the solution involved migrating the blockchain service provider from Moralis to Alchemy. This strategic shift aimed to leverage Alchemy's robust and reliable API for all blockchain interactions.

The migration encompassed several key areas:

  • Event Log Fetching: The most critical aspect was re-implementing the event log polling mechanism to use Alchemy's API. This directly resolved the issue of missing TokenEngraved events, ensuring that all on-chain engraving actions were accurately tracked and recorded in the database.
  • NFT Ownership Checks: Other blockchain-related functionalities, such as verifying NFT ownership, were also successfully migrated to Alchemy's more streamlined API.
  • Simplified Data Types: Alchemy consistently returned the current Ethereum block number as a standard number type, eliminating the BigInt comparison issues previously encountered.

Implementation Details & Further Improvements

Iterative Event Log Querying

The existing code for querying event logs and transactions was originally written recursively. While functional, recursive approaches can sometimes be harder to read and debug for deep call stacks. The entire event log/transaction querying logic was refactored to use an iterative approach. This improved code readability, maintainability, and ease in debugging.

Smart Contract Analysis

A thorough analysis of the Genuine Undead smart contract was undertaken to fully understand the mechanics of the engraving process. This involved using tools like Etherscan to examine relevant transactions and event logs directly on the blockchain, confirming the expected behavior and data structures emitted during an engraving. This deep dive provided a clearer understanding of the on-chain side of the engraving service, aiding in the robust implementation of the off-chain tracking.

Addressing Metadata Inconsistencies

A particularly noteworthy issue was identified and resolved concerning the display of the "Engraved" trait in the NFT metadata. When an engraving event for a specific token ID is saved in the database, a boolean value in another database table was updated to reflect the "Engraved" status. This database value was then intended to be included when the NFT's metadata was queried.

However, the existing system had a flawed approach:

  • File System Interaction: The code attempted to update a local JSON file (which held other static traits like background color and headwear) to include the engraving status. This was problematic because the site is hosted on Heroku, where file system changes do not persist beyond the current deployment and cannot be altered without a Git commit. Consequently, any changes made to these JSON files at runtime would be lost.
  • Caching: A caching mechanism was in place that relied on fs.stat() to check when the metadata JSON file was last modified. If a certain time had not passed since the last modification, the system would serve the "stale" JSON directly from the repository, bypassing a fresh database query. This led to a suboptimal user experience where users who had just engraved their tokens might not see the "Engraved" trait update due to these timing and caching issues.

The code attempting to interact with the file system for metadata updates was entirely removed. The correct approach, which was implemented, ensures that the engraving trait is queried from the database when metadata is requested and then merged with the static JSON traits before being served. This decreases the time until the correct data is available.

Results and Benefits

  • Cost Savings: A direct and tangible benefit was the substantial reduction in operational costs. Alchemy's free tier proved sufficient for the client's needs, saving them $199 per month that was previously spent on Moralis's Pro plan.
  • Reliable Event Tracking: The core problem of missing TokenEngraved event logs was completely resolved, ensuring accurate and timely tracking of all engraved NFTs.
  • Improved Data Consistency: The database now reliably reflects the true on-chain engraving status, leading to better data integrity.
  • Enhanced User Experience: The fix to the metadata caching issue ensures that users who engrave their NFTs see the "Engraved" trait update faster, providing a more seamless and accurate experience.
  • Increased Code Maintainability: The refactoring from recursive to iterative event polling improved the readability and ease in debugging of the backend code.
  • Streamlined Development: The consistent data types returned by Alchemy simplified development and reduced the likelihood of subtle type-related bugs.

Conclusion

It is important to select robust and appropriate blockchain infrastructure for Web3 applications. By identifying and addressing the limitations of the previous setup, and by implementing strategic migrations and code improvements, the Genuine Undead team now benefits from a more reliable, cost-effective, and user-friendly system for tracking their NFT engraving service. This project highlights how targeted technical interventions can lead to significant operational efficiencies and enhanced user satisfaction in the decentralized ecosystem.

About the Author

Marc Hamilton profile picture

Marc Hamilton

Blockchain & Mobile Developer

Marc is a razor-sharp developer at puzzl with a deep empathy for users and teammates alike. In a short time, he's made a big impact, diving headfirst into Web3, writing smart contracts, and building migration platforms from the ground up. Marc consistently brings his best to everything he touches.

About the Client

Genuine Undead logo

Genuine Undead

Bluechip NFT

genuineundead.com ↗
“Their incredibly quick turnaround time and detailed explanations of potential solutions make them an invaluable partner for our project.”
- Mittens, Project Manager