Elektrik V2 Security Case Study

PUBLISHED ON
Sep 23, 2024
WRITTEN BY
Jarir
DURATION
5 min
CATEGORY
Case Study

Elektrik is the first lightning-fast DEx on the LightLink Network to feature gasless transactions. The Elektrik V2 marks a major upgrade to the pre-existing DeFi solution that brought swap and liquidity provisioning on the LightLink blockchain. V2 brings many efficient trading solutions to the DeFi industry, notably Limit Orders- handled via an Advanced Order Matching Engine, Stop Loss/ Take Profit functionality, and TWAP Orders. This case study explores the security strategies employed in ElektrikV2’s Order Matching Engine and the Staking Program, highlighting the state-of-the-art measures that ensure robust operation and safeguard user assets.

This article sheds light on Elektrik’s partnership with BlockApex towards the secure development lifecycle for the ElektrikV2 DEx and Staking protocol at multiple stages throughout the lifecycle.

The security researchers from BlockApex commended Elektrik for their strong commitment to security and exceptional code quality. Throughout the review process, the team was noted for their thorough handling of big and small issues. This demonstrated Elektrik’s deep commitment to detailed discussions and their serious approach to every security detail.

Elektrik V2

The Elektrik DEX is a modern DeFi orderbook solution that leverages a cutting-edge order-matching engine to enable direct peer-to-peer trading, supporting various order types such as Limit orders, Stop Loss/ Take Profit, and TWAP Orders. This engine is fortified with oracle integrations to provide precise and secure trading operations.

Core Features

Enhanced Order Flexibility

  • Variety of Order Types: Supports a range of orders, including Time-Weighted Average Price (TWAP), stop loss, and take profit orders.
  • Customizable Conditions: Users can define unique conditions for each order type using predicates, allowing for more tailored trading strategies.

Facilitation by Liquid Markets

  • Integration with Multiple Facilitators: Enables access to various liquid markets and DEX liquidity pools to provide order matches.
  • Dynamic Order Matching: Leverages the order books of multiple facilitators to optimize order execution.

User-Centric Control

  • Executor Restriction: Users can specify which Externally Owned Addresses (EOA) can execute their orders, enhancing control over order execution.
  • Advanced Trading Options: Allows for applying various advanced trading strategies without compromising user security or trust in the protocol.

Security and Trust

  • User Fund Security: Maintain user funds’ security through stringent protocols and smart contract mechanisms.
  • Trust in Execution: The solution’s design ensures that the integrity and intention of every order are preserved, fostering confidence in the system.

Security Features

  • EIP-712 Compliance: Enhances transaction integrity and prevents repudiation by utilizing advanced cryptographic signature standards for order authentication.
  • Operator-Only Order Processing: Implements strict access controls that restrict critical trading functions to authorized operators, significantly reducing the risk of unauthorized access and manipulation.
  • Token Whitelisting: Employs a rigorous token vetting process to permit only pre-approved tokens in the trading ecosystem, mitigating risks associated with low-quality or malicious tokens.
  • Advanced Fee and Predicate Handling: Integrates sophisticated mechanisms to verify and enforce trading conditions, ensuring that all transaction prerequisites, such as fee payments and predicate conditions, are satisfied before order execution.

System Invariants

Following a robust approach while handling the states of an Order in Elektrik’s order book, several properties were identified by the ElektrikV2 engineering and the BlockApex security team. Specifically for the order-matching engine, the invariants represent the system-level bounds of interactions to implement a first-of-its-kind intent-based DeFi solution. 

This set of invariant, major pointers included only, listed below, states that “All orders must be fulfilled/ executed/ reverted in the following conditions:

  • Fill orders must only be called by the Operator.
  • All orders must be fulfilled at a specified price.
  • After the orders are matched, the balance must be updated correctly.
  • The vault must not keep funds after the fulfillment of orders.
  • Facilitator interactions must not result in loss of funds.
  • Funds should be returned within the transaction if the facilitator leverages a false-loan facility.
  • Pre and post-interactions must not result in loss of funds.
  • In the case of any predicate calldata, the specified condition must be met correctly.

Invariants Testing

During the development of Elektrik’s DEX, a critical goal was to implement an intent-based order-matching system that significantly enhances user outcomes through optimized price execution. This system employs a network of solvers, aka facilitators, to compete in providing the best execution prices, which inherently disincentivizes any participant’s submission of disadvantageous prices. This dynamic creates a naturally self-regulating marketplace where only the most competitive and fair prices survive. The following are the results of research conducted by the security team to complement the Elektrik engineering team’s marvelous work.

Solver Engagement Strategy:

  • The design ensures that only qualified solvers participate, using a stringent verification process that evaluates their historical accuracy and reliability.
  • Solvers are incentivized to offer the best prices under the threat of losing their place in the system, ensuring a high-integrity price discovery mechanism. Including this, the solver also earns a surplus in the order, attracting more solvers to create effective strategies.

Price Invariant Enforcement:

  • Discussions between the engineering and security teams led to a strict price invariant, rigorously enforced by the smart contract to ensure that every trade adheres to the user’s specified conditions.
  • This approach minimizes the risk of slippage and unfair order fulfillment, anchoring the system’s credibility and user trust.

Robust Testing Regime:

  • Extensive testing focused on the order-matching engine’s ability to handle various order types and scenarios, ensuring resilience against unusual market conditions.
  • The test suite included stress tests simulating extreme market volatility to validate the system’s robustness and ability to maintain order integrity under pressure.

Security-First Innovations

The iterative security discussions solved present issues and set the groundwork for future enhancements. Ideas like integrating more advanced cryptographic techniques for order security and exploring new order types that can adapt to evolving market dynamics were proposed. The collaboration led to several innovative security solutions tailored specifically for Elektrik’s unique trading environment:

  • Conditional Order Encryption: This feature encrypts orders until execution conditions are met, preserving trade intentions from premature exposure.
  • Pre-execution Integrity Checks: Orders undergo multiple layers of validation before they are executed, ensuring they have not been tampered with and comply with the current market conditions and user stipulations.

These discussions are expected to guide the next development phases of Elektrik, ensuring the platform remains secure and ahead of market trends.

Elektrik Staking

The Elektrik Staking Program introduces mechanisms for liquidity staking, governance, and rewards distribution, fostering community involvement and secure asset management. Borrowing a set of functionalities from Velodrome Finance and significantly customized thereafter, the Elektrik Staking Program incorporates complex smart contracts to provide a refined experience for voters and stakers by introducing governance features via voting escrowed tokens and incentivizing them with rewards distribution.

Key Components

  • The Staker Contract: Forked from the Pancake Swap, this contract enables liquidity staking within the Elektrik ecosystem, which allows users to deposit and manage LP tokens effectively.
    • Liquidity Management: Supports seamless liquidity operations by allowing users to deposit and withdraw LP tokens, automatically adjusting stake shares and user balances.
    • Reward Calculation: Utilizes dynamic algorithms to calculate staking rewards based on active stake duration and total staked amounts, promoting equitable reward distribution.
    • Stake Tracking (off-chain): A detailed ledger of all staking activities allows users to effortlessly monitor their staking histories and financial returns.
  • The Voter Contract: Grants governance power to token holders, facilitating informed decision-making on protocol direction such as emissions rates and pool additions.
    • Proposal Management: Manages the entire lifecycle of governance proposals, from initiation to resolution, ensuring that all activities are conducted transparently and securely.
    • Voting Mechanism: Implements a robust voting system that appropriately weights the voting power of stakeholders based on their token stakes and lock durations.
    • Governance Security: Incorporates comprehensive security measures to guard against vulnerabilities such as flash loans, securing the integrity of the voting process.
  • The Voting Escrow Contract: Manages token locks that align governance incentives with the long-term success of the protocol.
    • Token Locking: Allows for lock tokens for set periods, granting them increased voting power and potential for enhanced rewards. Locking a token secures the user a share of the weekly distributed protocol fee. 
    • Decaying Voting Power: Features a decay mechanism for voting power, incentivizing continuous engagement and participation from stakeholders.
    • Flexible Lock Management: Offers versatile options for managing token locks, including rebasing, extensions, additions, and early withdrawals, balancing security for voting dilution with user autonomy.
  • The Rewards Distributor and Minter Contract: These contracts manage the minting of new tokens and the distribution of rewards (specifically, the rebase rewards), aligning with governance decisions to maintain controlled supply expansion.
    • Reward Distribution: Calculates and disburses rewards to stakeholders based on predefined criteria and governance inputs, ensuring timely and accurate reward payments.
    • Token Minting: Oversees the minting of new tokens, strictly adhering to governance directives to regulate token supply and prevent inflation.

Security by Design

The staking module’s design incentivizes long-term participation, achieved through a sophisticated time-weighted scoring system. This approach not only encourages prolonged staking but also aligns participant incentives with the overall health and stability of the protocol.

  • Dynamic Staking Score Calculation:

  • Implementing a dynamic scoring system for staking introduces a novel method to calculate rewards, where longer commitments are rewarded with greater influence and returns.
  • This mechanism discourages short-term speculative behaviors and fosters a stable and committed community base.
  • Staking Boost Mechanism:

  • The boost feature provides additional incentives for liquidity providers by increasing their rewards when they stake the platform’s native token, ELTK. This not only enhances liquidity but also secures the protocol by locking in funds that support its governance and operability.
  • The technical implementation ensures that the boost calculations are precise and tamper-proof, safeguarding against exploits that could manipulate reward distributions.

Challenges

Throughout the development phase, several challenges were identified and meticulously addressed:

Voting Power Imbalances:

  • The introduction of a mechanism to prevent last-minute voting power changes was crucial. It ensures that the voting results reflect a fair and stable representation of the community’s consensus, preventing manipulation through sudden stake changes.
  • A minimum participation threshold was set, requiring that significant decisions have backing from a substantial portion of the voting power, thus reflecting a broader agreement within the community.

Election Timing and Voter Retention:

  • To counter the impact of retiring voters on ongoing proposals, safeguards were implemented to ensure that votes cast are counted within the epoch they were intended to influence, maintaining the integrity of voting outcomes.
  • Restrictions were placed on vote retraction to stabilize the voting process, ensuring that once a vote is cast, it significantly contributes to the decision-making process until the proposal’s conclusion.

Innovative Testing Approaches

The testing phase was as rigorous as the development phase, with a focus on ensuring that the staking system behaved as expected under various scenarios:

Comprehensive Testing Framework:

  • The suite included automated tests to verify the correct calculation of staking scores and the proper distribution of rewards based on these scores.
  • Stress tests simulated scenarios with high volumes of concurrent staking and unstaking, as well as rapid changes in token values to ensure system resilience.

Edge Case Analysis:

  • Special attention was given to edge cases such as the impact of last-minute staking changes and voter retirement scenarios. These cases were critical in refining the voting mechanisms to ensure they are resistant to manipulative practices and align with the intended democratic governance structure.

Conclusion

Elektrik sets a benchmark in DeFi by melding advanced trading functionalities with robust staking and governance mechanisms. Through thorough design, comprehensive testing, and ongoing oversight, Elektrik ensures it remains a secure, efficient, and user-focused platform in the dynamic DeFi ecosystem.

related reports

Subscribe to our Newsletter!