Client Overview
Heaven1 is a pioneering blockchain platform focused on creating a secure and reliable environment for users and developers in the Web3 space. With a mission to eliminate risks such as on-chain hacks, scams, and rug pulls, Heaven1 connects verified users with trusted builders, fostering a safe ecosystem for innovation and interaction.
The platform emphasizes user protection and trust, making it an appealing choice for those seeking a secure blockchain experience. By implementing unique safety guardrails, Heaven1 ensures that participants can engage in transactions with complete peace of mind, ultimately aiming to enhance user confidence in the rapidly evolving digital landscape.
Solution Implementation and Development Approach
Our work on the Heaven1 Perpetual Dex involved a range of specialized tasks to deliver a customized, fully functional decentralized trading platform. The development process was organized into distinct components to ensure robust, secure, and reliable trading features on the Haven1 blockchain:
GMX Fork
To meet the client’s requirement for a perpetual decentralized exchange, we initiated a codebase fork of GMX.io. While GMX’s architecture served as a foundational framework, extensive customizations were required to adapt it for Haven1’s unique environment. This adaptation included carefully removing governance-related logic, as Heaven1 did not issue a governance token. This logic was meticulously stripped from the codebase without compromising other trading functionalities. Additionally, we integrated customized transaction fees in Haven1’s native H1 coin to align with the client’s tokenomics.
Subgraphs
We created custom subgraphs to track and index key trading and liquidity data across the platform. By developing these subgraphs, we facilitated faster data retrieval for user interfaces, allowing users to view real-time data on positions, price movements, and historical transaction records. The subgraphs were optimized for performance to ensure a seamless and responsive trading experience.
Smart Contracts
Our team deployed a suite of smart contracts essential to the core operations of the Perpetual Dex. These contracts encompass liquidity provisioning, order management, collateral management, and liquidation mechanics. Recognizing that the GMX model relies heavily on smart contracts for execution, we made careful adjustments to support Haven1’s architecture. This included implementing robust logic for long and short positions, leverage, collateral reservations, and liquidation price tracking, all tailored for the specific requirements of the Haven1 blockchain.
Backend
The backend layer was designed to support both off-chain and on-chain functionality, acting as the bridge between user commands and on-chain contract execution. Backend services managed price data (sourced initially from backend data and later integrated with Redstone oracles), tracked order conditions, and supported complex order types like Stop-Loss and Take-Profit. The backend also managed price updates and calculations by interfacing with the PriceFeed and Keeper systems to maintain trading integrity across the platform.
Frontend
The frontend interface was developed to ensure an intuitive, seamless user experience. Users can initiate trades, manage their positions, set Stop-Loss and Take-Profit levels, and monitor real-time data on open orders and market prices. The interface also dynamically reflects available trading options, with checks on available pairs, token swaps, and order types to provide users with a comprehensive trading toolkit. A primary focus was placed on clarity and user guidance to enhance usability for both novice and experienced traders within the Web3 environment.
Through this structured and componentized development approach, we delivered a customized and resilient Perpetual Dex tailored to the distinct environment and requirements of Heaven1.
Solution Overview. Platform Modules
The Heaven1 Perpetual Dex was developed as a modular platform, with each module responsible for distinct yet interconnected functionalities. Below is an overview of the primary modules, highlighting their roles and interactions within the system.
1. Core Protocol (Smart Contracts)
At the foundation of the Heaven1 Perpetual Dex lies a robust suite of smart contracts designed to manage trading logic on-chain. These contracts handle the primary trading mechanisms, including:
- Order Management: Supports Market, Limit, Stop-Loss, and Take-Profit orders, enabling precise control over order execution and risk management. Order conditions are tracked through smart contract logic, enhancing both flexibility and automation.
- Collateral and Leverage Management: Contracts ensure that collateral levels are properly maintained, with leverage ratios displayed and managed per position. Collateral remains pegged to its USD value snapshot, stabilizing against volatility after initial deposit.
- Position Management: Users can modify open positions by adding or withdrawing collateral, which dynamically adjusts liquidation thresholds. Smart contracts track each modification and update margin requirements as needed.
- Liquidation Mechanism: Ensures the platform’s solvency by liquidating positions that breach margin requirements, with logic to calculate the liquidation price based on cumulative fees, collateral depletion, and leverage. A $5 fee is charged per liquidation.
2. Pricing and PriceFeed Module
Accurate, reliable pricing is maintained by a custom PriceFeed and Keeper system:
- PriceFeed Contract and Keepers: A two-tiered keeper system provides ongoing price updates and specific price checks for position fills. The PriceFeed takes a median of prices from leading exchanges (Binance, Bitfinex, Coinbase) to determine an accurate rate.
- Chainlink Integration: Chainlink data serves as a fallback and benchmark to cross-verify prices. A threshold mechanism ensures prices remain within a permissible range of Chainlink, with automatic spread activation for added security.
- Watcher Nodes: An additional layer of security to prevent price manipulation. These nodes validate the PriceFeed data against calculated medians and can trigger spread adjustments if discrepancies are detected.
- Stablecoin Handling: In cases of stablecoin depegging, the module applies calculated spreads to prevent front-running, safeguarding the stability and integrity of the platform’s pricing.
3. Data Layer and Subgraphs
The data layer provides efficient indexing and retrieval of trading data:
- Custom Subgraphs: Deployed for tracking key data points, such as trade history, user positions, price changes, and liquidity pool statuses. These subgraphs ensure fast and reliable data access, allowing for responsive user interfaces and real-time analytics.
- Data Integrity: Subgraphs support not only live data but also historical record-keeping, allowing users to monitor and analyze performance and market trends over time.
4. Backend Services
Backend services bridge user actions with on-chain execution:
- Order and Position Routing: The backend processes incoming trade requests and routes them to the appropriate contract, handling token wrapping, slippage checks, and multi-part transaction flows for opening and closing positions.
- Transaction Management: Integrates with the PositionRouter to handle two-stage transactions for secure execution, reducing the risk of front-running and ensuring accurate price fills.
- Oracle Transition Management: Initially deployed with backend-managed token prices in the absence of native oracles, the backend was later updated to incorporate Redstone oracle data upon availability.
5. Frontend Interface
The frontend provides a comprehensive user experience, integrating core functionalities in an accessible interface:
- Trading Dashboard: Enables users to place trades, set Stop-Loss and Take-Profit triggers, and track open positions. Key trading data, including leverage, margin, and collateral, are displayed in real time.
- Position and Order Management: Allows traders to monitor and adjust positions, manage collateral, and receive visual indicators of liquidation risks. Both position modification and collateral management are made intuitive and accessible.
- Swap and Price Tracking Features: A built-in swap interface facilitates token exchanges with live pricing and commission updates, giving users a seamless transition from wallet management to trading.
- User Guidance and Security Warnings: The interface includes tailored notifications for price spreads, depegging risks, and transaction status updates, ensuring users have a full understanding of each trading action.
Each of these modules contributes to the stability, performance, and user experience of the Heaven1 Perpetual Dex, delivering a secure and versatile trading platform suited to both institutional and individual users within the Web3 ecosystem.
6. Referrals Module
The referrals module incentivizes user growth by rewarding traders who bring new participants onto the platform. This module is designed with flexibility to allow for customized referral rewards in Heaven1’s native H1 token, strengthening the ecosystem through community-driven engagement. Key features of the referrals module include:
- Reward Structure: Referrals can be configured with different reward tiers based on trading volume or milestones achieved by referred users. The module enables Heaven1 to adjust reward rates dynamically to match market conditions and user acquisition strategies.
- Tracking and Transparency: Using smart contracts, the referrals module ensures transparent and accurate tracking of referral-based rewards. Every referral action is logged on-chain, providing a verifiable record of rewards for both the referrer and referee.
- Integration with Trading Activity: Referral rewards are calculated based on trading fees generated by the referred user. This ensures that rewards are aligned with platform usage, encouraging quality engagement rather than passive sign-ups.
- User Interface Integration: The frontend interface includes a dedicated section where users can generate referral links, view referral earnings, and track the performance of their network, making it easy for users to manage and monitor their referral-based income.
By leveraging this referrals module, the platform can organically grow its user base while rewarding existing users for their network contributions, creating a community-centric growth strategy.
Key Challenges
Developing a Perpetual Dex on the Heaven1 blockchain presented a unique set of challenges. Our team navigated several technical obstacles related to the blockchain’s infrastructure, the absence of essential tools, and the constraints of a closed blockchain environment.
- Lack of Oracles and the Absence of Chainlink
A significant hurdle was the absence of Chainlink or any established oracle solution on the Heaven1 blockchain during the initial development phase. GMX’s architecture relies heavily on Chainlink for accurate, real-time price feeds, so we adapted by simulating token prices directly on the backend. Once Redstone oracles became available, we redeployed the necessary smart contracts to replace the simulated data with live oracle data. This transition required precision to maintain data integrity across all price-dependent trading functions and ensure a seamless user experience. - Limited Network Environments
Heaven1 operates as a closed blockchain, and access to test environments was tightly controlled. Since Heaven1’s mainnet was not available and testnet access was restricted, our team had to work within the devnet, which was prone to instability and frequent outages. These limitations delayed transaction processing and added layers of complexity to development and testing. As a workaround, our team created isolated environments to pre-test functionality while dealing with occasional interruptions in devnet performance. - Deployment Restrictions
Due to Heaven1’s policies, only the blockchain’s owners had permission to deploy contracts on both the testnet and mainnet. To address this constraint, we collaborated closely with Heaven1’s team, providing thorough documentation and hands-on training to ensure their team could independently deploy and manage the Perpetual Dex. This required building comprehensive guides for contract deployment and configuration, enabling them to take over this responsibility smoothly. - Custom Code Modifications for Governance
Forking GMX involved more than a straightforward code replication. The client’s decision to forego a governance token meant that related governance functionality had to be selectively removed from the codebase. This was a precise task, as we needed to preserve the platform's core features while carefully extracting all governance-related elements. The process required extensive testing to confirm that the adjustments didn’t compromise functionality or user experience, especially in modules that were interdependent with governance logic.
These challenges underscored the complexities of adapting GMX for a specialized blockchain environment. Through close collaboration and adaptive problem-solving, we were able to overcome each hurdle, ensuring a secure, fully functional Perpetual Dex on Heaven1.
Results
The project successfully delivered a fully functional Perpetual Dex on the Heaven1 blockchain, meeting both the technical and business requirements despite the inherent challenges of developing in a closed, emerging blockchain ecosystem.
- Seamless Trading Experience
With a fully integrated oracle solution from Redstone, the Dex provides accurate real-time pricing, allowing traders to execute market and limit orders confidently. The platform supports leverage, Stop-Loss, and Take-Profit features, with pricing and liquidity accurately managed by a robust combination of keeper, watcher, and Chainlink integration. - High-Precision Position and Order Management
The Dex enables users to manage open positions with dynamic collateral adjustment, secure liquidation management, and order customization. As a result, users can execute trades with confidence that their positions are accurately protected from adverse market conditions and unnecessary liquidation risks. - Stable Pricing for Volatile Markets
The pricing module adapts to market changes, providing added stability during sudden volatility or stablecoin depegging events. The Dex’s spread and depegging protocols ensure trades and collateral management remain stable, reducing slippage and front-running risks even in challenging market conditions. - Secure and Reliable Deployment
By implementing a controlled deployment process and equipping Heaven1’s team with comprehensive deployment documentation, we enabled their team to confidently manage future updates. This not only ensured efficient delivery in a controlled environment but also prepared Heaven1’s team for long-term, independent Dex maintenance. - Future-Ready Architecture
The platform’s architecture incorporates flexibility for scaling and modular updates. The platform can integrate new oracles, adjust spread mechanisms, and introduce additional features, such as opening watcher nodes for external users, paving the way for further user engagement.
Through these results, the Perpetual Dex positions Heaven1 as a strong, reliable trading platform within the Web3 ecosystem, equipped with a powerful trading engine tailored to its blockchain infrastructure. The completed project has successfully expanded Heaven1's offerings, providing users with a sophisticated trading experience on a secure and flexible foundation.