đź’¬ Join ourBerachain DE/AT/CH Telegram Channel

Sei: Revolutionizing DeFi with Parallel Execution

Published:
Last updated:

Introduction

The decentralized finance (DeFi) revolution has ignited a global movement towards financial empowerment and disintermediation. Yet, the promise of instant, peer-to-peer transactions often gets bogged down by sluggish blockchains. Imagine the frustration of waiting for a trade confirmation, or facing agonizing delays that expose you to volatile price swings. This is the exact friction Sei aims to eradicate.

Key Takeaways

  • Sei is a Layer 1 blockchain with optimized architecture for diverse trading applications, ensuring peak performance.
  • Native order matching engine built directly into the Layer 1, enabling seamless order execution and superior scalability for exchange dApps.
  • Sei's Twin Turbo Consensus achieves sub-second finality, offering near-instantaneous trade confirmations.
  • Sei takes a nuanced approach to market-based parallelization, which caters specifically to high-frequency trading needs.
  • Fairer playing field by order batching prevents frontrunning, a malicious practice exploited by bots.
  • Sei V2 Upgrade - Parallelized EVM, Optimistic Parallelization, and SeiDB.

Sei overview

The current generation of mainstream blockchains, serving as the foundation for many crypto projects, presents a significant hurdle. The Sei Labs team argues that existing infrastructure simply can't keep pace with the demands of DEXes. They often struggle with limitations in throughput (the number of transactions processed per second) and finality times (the time it takes for a transaction to be considered complete and irreversible). This translates to sluggish performance, a major roadblock for both high-frequency trading strategies and high-volume trading activity.

Sei aims to smash through this barrier by meticulously optimizing every layer of the blockchain stack specifically for exchange needs. The team offers a single, crystal-clear value proposition: no matter the type of trading application – be it a DeFi, an NFT marketplace, or a gaming – it will run smoother and faster on Sei than on any other Layer 1 network.

With this innovative solution, Sei positions itself as the ultimate game-changer for DeFi landscape, aiming to become the go-to infrastructure provider for exchanges seeking a platform specifically tailored for the fast-paced world of digital asset trading.

Leveraging the interoperable Cosmos SDK framework, Sei boasts a specialized Layer 1 blockchain equipped with a synergistic set of features designed to enhance the trading experience.

Its native order-matching engine streamlines exchange operations by eliminating external dependencies, while the innovative Twin-Turbo consensus mechanism delivers sub-second finality for near-instantaneous trade confirmations. Security and developer experience remain paramount, with features like frontrunning prevention and Native Price Oracles ensuring a robust and user-friendly environment.

Let's delve into the key features that position it as the turbocharged engine of DeFi trading.

Twin-Turbo Approach

Sei relies on Proof-of-Stake (PoS) protocol based on a modified Tendermint consensus mechanism, aptly named Twin-Turbo Consensus.

Validators play a crucial role in processing transactions and confirming changes in the network's state. These validators are chosen based on their total stake, which comprises both self-bonded and delegated SEI tokens. Presently, only the top 39 validators, ranked by total stake, participate in the consensus process, earning transaction fees and staking rewards.

SEI tokenholders have the option to delegate their SEI tokens to an existing validator, thereby contributing to network security. Delegators also receive a share of the validator's SEI rewards, after deducting the validator's chosen commission rate.

Speaking of consensus, Tendermint offers a solid foundation, ensuring transactions are finalized, and irreversible once added to the blockchain (single slot finality). However, its base block time of 6 seconds wasn't ideal for Sei's high-speed trading vision.

With the improvements introduced by the Twin Turbo consensus, Sei Labs had reduced Tendermint's 6-second block times to <400 ms, with single slot finality.

This was made by two key optimizations made towards Tendermint are known as  “Intelligent Block Propagation” and “Optimistic Block Processing”. Both produce the ultimate result that Sei presents today – transaction processing that takes just milliseconds during consensus.

Intelligent Block Propagation mechanism departs from the traditional approach of transmitting entire blocks with full transaction details to validators. Instead, block proposers initiate the process by sending a proposal containing a unique identifier and a hash for each transaction within the block.

Given that validators typically possess the most recent transactions in their local memory pool, they can reconstruct the complete block, avoiding unnecessary bandwidth consumption and reducing wait times associated with retrieving redundant data. This optimization fosters overall network efficiency, ultimately translating to faster transaction processing for users.

Optimistic Block Processing further accelerates transaction processing by bypassing “Prevote” and “Precommit” rounds. The goal was to streamline the process by allowing consensus steps to occur concurrently, resulting in significant time savings. This approach leads to faster block validation and voting, a stark contrast to the often-sequential processes found on other blockchains.

Harnessing the synergy between Optimistic Block Processing and Intelligent Block Propagation, the consensus mechanism is propelled forward with remarkable efficiency.

Upon receiving the initial block proposal at a given height, the system run sanity checks and start processing it simultaneously during “Prevote” and “Precommit”. The Optimistic Block Processing will then write the candidate state to a cache.

This innovative approach empowers validators to process transactions optimistically upon the reception of a valid block proposal, bypassing the delay until the “Precommit” phase concludes. The rationale behind this strategy lies in the observation that, in most scenarios, the first proposed block at a particular height emerges victorious post-voting. Thus, initiating transaction processing from the outset maximizes the likelihood of capitalizing on this trend.

Should the block garner acceptance, the optimistically processed candidate state cache seamlessly integrates into the blockchain. Conversely, if the block faces rejection, the cached data is discarded, and subsequent rounds of the same block height eschew optimistic block processing. Validators reset their stance, preparing to tackle the next block proposal. This concept cleverly exploits the predictability of block acceptance to significantly enhance transaction processing speed, all while mitigating the risk of block reject, translates to a significant increase in throughput compared to conventional solutions.

This results in a smoother user experience for traders by minimizing confirmation times and reducing risks for market makers, two major pain points in current DeFi ecosystems.

Parallelization

In chains like Sei, operating on the Cosmos SDK, validators follow a structured three-step process upon receiving a block: "BeginBlock," "DeliverTx," and "EndBlock." Sei customizes the latter two steps to introduce parallel processing.

Traditionally, transactions in the DeliverTx phase are processed sequentially. However, Sei modifies this approach to allow simultaneous processing, employing a concept of Directed Acyclic Graph to manage transaction order and avoid conflicts.

Moreover, Sei implements parallel processing for order execution at the block's conclusion, particularly for independent orders tied to its native order-matching engine. These orders are deemed independent if they involve distinct markets within the same block, with developers empowered to define market dependencies.

Sei's native order matching engine allows decentralized exchanges to create their own orderbooks. We're going to look at this in more detail below.

Hidden cost of Tendermint

While Sei leverages modified Tendermint consensus, known for its fast block finality, it comes with a hidden cost: Quadratic Communication Complexity. This principle states that the number of messages required for communication between validators grows quadratically with the number of validators in the network.

Imagine a conference call – with a small group, communication flows smoothly. But as the number of participants increases, managing the conversation becomes exponentially more complex. Similarly, in a blockchain with Tendermint, a growing validator set leads to a surge in message traffic, potentially straining network bandwidth and validator processing power. This can hinder scalability, making it difficult to add many validators without compromising performance.

As the current validator set steadily expands, Sei remains committed to tackling this challenge head-on by intensifying its decentralization initiatives. The goal is to uphold network performance by fostering a globally distributed network of validators, complemented by light clients for trustless verification.

Order Matching Engine

Sei integrates an order matching engine at the chain level, allowing developers to create order book-based exchanges on top of the Sei blockchain.

This feature enables the development of central limit order book (CLOB) systems , commonly used in traditional centralized trading platforms. Sei also supports automated market maker (AMM) systems that are commonly used in decentralized exchanges (DEXs) within the DeFi space.

How it works

All transactions involving the matching engine will execute atomically within a block's scope. These transactions are directed to the DEX module, with each transaction potentially containing multiple orders. Upon submission, the transaction handler adds the orders from each transaction to the DEX module's internal MemState. During block processing, the DEX module's EndBlocker hook consolidates orders recorded in the MemState in bulk. This consolidation involves aggregating orders by market (e.g., all orders for a BTC perpetual), resulting in a single smart contract call for each specific market.

Transaction Order Bundling

Sei introduces various layers of order bundling to enhance user experience and optimize performance:

  • Client Order Bundling: Sei enables transactions comprising orders for multiple trading markets, including those spanning smart contracts (e.g., orders for both a BTC/USDC spot pair and a BTC perpetual exchange). During block processing, Sei accurately directs orders to their respective smart contracts, helping market makers minimize gas costs associated with position updates.
  • Chain Level Order Bundling: Instead of instantiating the virtual machine (VM) separately for each matching engine-related transaction, Sei consolidates all orders across transactions (per market) and initiates only one VM instantiation. This significantly reduces latency by approximately 1ms per order, particularly during periods of high throughput.

Hook Integration

Sei enables contracts to establish "hooks" within the network. These registered hooks are triggered every block, facilitating actions such as flash loan repayments alongside trade settlements within the same block. Contracts can define two types of hooks: one executed at the block's onset to prepare for potential trades, and another at the block's conclusion, after order matching and settlement, enabling contracts to execute any necessary post-trade logic.

Asset Agnostic

The matching engine operates without the necessity for tokens to be directly traded. Instead, it provides a versatile interface allowing decentralized exchanges the freedom to determine how assets are represented. For instance, rather than tokenizing positions, decentralized exchanges can choose to track positions as a list within their smart contract state.

Frequent Batch Auctioning

Sei has introduced a method called “frequent batch auctioning” to counteract a phenomenon known as "MEV" (maxima (or miners)l extractable value), thus ensuring fair market conditions. MEV arises when validators prioritize their own transactions to maximize profits, potentially at the expense of other participants.

To mitigate this, Sei consolidates all market orders and executes them at a consistent clearing price. For instance, if there are two sell orders (asks) at prices P1 and P2, and two incoming buy orders (bids), Sei calculates a uniform clearing price—simply the average of P1 and P2. Subsequently, both buy orders are executed at this uniform clearing price.

By sidestepping individual transaction sequencing, Sei eliminates the incentive for validators to manipulate transaction order for personal gain, thus fostering a more equitable trading milieu.

Price Oracle

In order to facilitate the pricing of assets, SEI implements native price oracles. Validators act as oracles, ensuring the reliability and accuracy of asset pricing. To maintain the freshness of oracle pricing, voting windows can be as short as one block, leading to rapid updates and current asset pricing.

During the voting step within a voting window, validators propose exchange rates. At the end of the voting period, all exchange rate votes are aggregated, and a weighted median (weighted by validator voting power) is computed to determine the accurate exchange rate for each asset. Penalties are imposed for non-participation and for providing inaccurate data.

Validators are subject to a miss count, tracking instances where they fail to provide data or provide data significantly deviating from the weighted median. If a validator's miss count exceeds a certain threshold within a specified number of voting periods, they face slashing penalties for prolonged misbehavior.

Sei V2 Upgrade

In November 2023, Sei unfurled the blueprints for Sei V2, heralding three transformative enhancements for the network: Parallelized EVM, Optimistic Parallelization, and SeiDB.

Through a clever fusion of parallel execution and EVM compatibility, Sei V2 tackles performance and usability issues in one stroke, offering users and developers the ability to escape Ethereum's constraints while retaining the familiar surroundings of EVM ecosystem. This groundbreaking method enhances transaction processing efficiency, substantially mitigating the bottlenecks prevalent in Ethereum during high-demand periods, while still providing a seamless experience for EVM veterans.

The deployment of the upgrade to the mainnet is anticipated to unfold within the first half of 2024. Meanwhile, in February 2024, Sei opened its Public Devnet as a Sei V2 innovation testing ground.

Source Source

Sei is taking a major leap forward with Sei V2, its first significant upgrade. This upgrade unlocks the power of the Parallelized Ethereum Virtual Machine (EVM) with hyperoptimized execution layer for developers, and enhanced state storage efficiency.

Moreover, a new component will be introduced to accommodate EVM smart contracts. These contracts will leverage the advancements in consensus and parallelization while seamlessly interacting with existing Cosmwasm smart contracts.

Source Source

This upgrade will result in Sei having the following functionality:

  • Backwards compatibility of EVM smart contracts
  • Optimistic parallelization
  • SeiDB - improvements to the storage layer
  • Interoperability - composability between EVM and any other execution environments

Backwards compatibility

With this update, all existing and audited smart contracts from EVM-compatible chains can be seamlessly deployed on Sei, eliminating code changes and leveraging familiar tools such as Foundry, Remix, and Hardhat.

Sei nodes will integrate Geth, a Go implementation of the Ethereum Virtual Machine, which will handle Ethereum transactions. And any subsequent updates (such as state modifications or invocations of non-EVM contracts) will occur through a specialized interface created by Sei specifically for the EVM.

Source Source

Optimistic parallelization

Optimistic parallelization will apply to all transactions that are run on Sei, including Sei native transactions, Cosmwasm transactions, and EVM transactions.

Source Source

In Sei V2, developers will no longer need to manually define state access. Instead, the chain will adopt an optimistic approach, executing transactions in parallel.

When conflicts arise — such as transactions affecting the same state — the chain will monitor which storage areas each transaction interacts with. Transactions involving different storage areas will be rerun concurrently, while those involving the same state will be rerun sequentially.

This process will iteratively continue until all conflicts are resolved. As transactions within a block are ordered, this method ensures determinism, streamlining the developer workflow while preserving parallelization at the chain level.

Additional technical implementation specifics can be found here.

SeiDB

Increasing transaction processing leads to the creation of more blockchain state, necessitating consideration not only for parallelizing the runtime but also for managing the state. Sei v2 introduces SeiDB as a major component, fundamentally altering the mechanisms of state access, state commitment, and state storage.

Source Source

The current implementation of Sei utilizes a database layer, which is composed of an IAVL tree data structure. However, this structure proves to be less efficient in terms of storage and latency due to its schema and additional metadata, resulting in increased write amplification and slower disk access.

Building upon the foundation set forth in ADR-065 (Architecture Decision Record), the Sei Labs engineering team has developed SeiDB. The primary strategy employed involved avoiding the storage of all data within a single large database. Instead, the data was decoupled into two distinct layers:

  • The State Commitment employs a highly optimized in-memory IAVL tree to commit data swiftly, enabling validators to achieve consensus more rapidly by minimizing disk access.
  • The State Storage facilitates low-latency direct access to raw key-value pairs, enhancing the ability of RPC nodes to handle queries efficiently.

Schematic representation of SeiDB’s distinction of State Commitment and State Storage - Source

The segregation of active state and historical data significantly boosts performance for all node operators in the Sei ecosystem. This architectural decision empowered the Sei Lab’s engineering team to represent the current chain state as a memory-mapped IAVL tree using MemIAVL. As a result, validator nodes can track blockchain state via mmap, slashing state access time from hundreds of microseconds to mere hundreds of nanoseconds. This remarkable advancement yields substantial improvements in state syncing times and read/write amplification.

Storing raw key-value pairs in the State Storage layer with minimal metadata improves locality in LSM trees, and asynchronous pruning prevents nodes from falling behind. These changes have reduced state storage requirements by at least 60% and decreased total data growth rate by 90%, leading to significant long-term disk savings as nodes continue to operate.

Moreover, Sei has conducted thorough benchmarking on various leading databases in the industry. As a result, Sei V2 will transition to using PebbleDB instead of GoLevelDB. This transition promises significantly enhanced read/write performance, particularly for multi-threaded access.

The key takeaways of SeiDB:

  • Reduces active state size by 60%
  • Reduces historical data growth rate by ~90%
  • Improves state sync times by 1200% and block sync time by 2x
  • Enables 287x improvement in block commit times
  • Provides faster state access and state commit resulting in overall TPS improved by 2x
  • All while ensuring Sei archive nodes are able to achieve the same high performance as any full node.
Source Source

The major upgrade to the network's storage layer, tackles data overload, optimizes performance, and streamlines onboarding for new nodes. This ensures consistent network scalability and performance.

Interoperability

The upcoming Sei v2 upgrade will bring revolutionary features, notably the cutting-edge high-performance parallelized EVM. This advancement is set to elevate user experience and open doors to innovative development possibilities.

Sei is committed to facilitating seamless composability between the EVM and other supported execution environments, promoting interoperability within the existing chain.

Source Source

Operating as an integrated blockchain, Sei will allow transactions to interact seamlessly between various Sei components (Bank, EVM, Wasm, Staking). Despite their distinct purposes, these transactions share common features such as gas, sender, and transaction body. Upon receipt, the chain treats these transactions as Sei native transactions and directs them to the relevant storage sections (e.g., CosmWasm transactions to the Wasm module for execution). This integration fosters a smooth developer experience, allowing EVM developers to effortlessly leverage native tokens and other chain functionalities like staking.

In addition, since Sei v2 will be enhanced to support two execution environments (CosmWasm and EVM), all token standards available on the Ethereum blockchain will also be available on Sei. Some users may worry that this will introduce too much complexity into the ecosystem and harm the user experience, but Sei has taken care of that.

Each token on Sei, whether an NFT (CW-721) or a standard token (CW-20), can achieve compatibility with EVM wallets and applications through a pointer contract. These contracts establish links between tokens across both EVM and CosmWasm, enabling seamless usage without the need for "wrapped" assets. This ensures the same token balance is controlled on EVM and CosmWasm simultaneously.

Pointer contracts enable wallets from either environment to access all tokens. Source Pointer contracts enable wallets from either environment to access all tokens. Source

Pointer contracts also enable the utilization of CW-20, CW-721, and native tokens in EVM apps and vice versa. However, they do not facilitate interaction with existing Sei apps using an EVM wallet, which requires another feature called a "precompile".

To address this, Sei Labs has implemented “precompiled” smart contracts directly within the Sei blockchain. These contracts act as a gateway for users and developers to access native Sei functionalities through the EVM RPC interface, ensuring interaction with smart contracts using their preferred wallet.

The available precompiled contracts on Sei include:

Developers seeking guidance on utilizing these precompiles can find instructions in the Example Usage section.

Once funds are deposited into your EVM address, you can utilize them seamlessly with your Sei address, and vice versa. This integration merges them into a single account, ensuring smooth interaction between the EVM and Sei ecosystems.

User Accounts on Sei

In Sei, each user "account" is associated with a separate public key, whereas after upgrading to Sei V2, this public key will correspond to two types of addresses:

  1. EVM Address: Beginning with 0x, this address is utilized for Ethereum-related actions.
  2. SEI Address: Starting with Sei, this address is employed for Sei-native operations.
Source Source

Despite the apparent disparity between these addresses, they are essentially linked to the same underlying account. This implies that any action performed with one token address will invariably impact the other.

Sei’s Parallel Stack

With the debut of Sei V2, the team focuses on introducing Sei’s Parallel Stack, which will serve as the entry point for Layer-2 networks into the Sei ecosystem.

Source Source

Born from the experience of building Sei V2, this open-source powerhouse will empower developers to create high-performance Layer 2 solutions and rollups that leverage the magic of parallel processing. The Parallel Stack tackles a critical challenge – the performance bottlenecks plaguing current Layer 2 blockchains within the Ethereum ecosystem.

This framework provides a robust and secure foundation upon which developers can build innovative Layer 2 solutions within the Ethereum ecosystem. Notably, the Parallel Stack offers unparalleled customization capabilities, enabling developers to tailor their creations to specific project requirements. Furthermore, projects inherently benefit from the robust security features of the Ethereum blockchain or any chosen data availability layer they integrate with. As part of the default configuration options, projects can elect to leverage the proven validator set of Sei. This integration further bolsters security while maximizing project benefits from the innovative architecture of the Parallel Stack.

Democratizing the Parallel EVM

Building a rollup from scratch can be a daunting task. The collaboration between Sei and Altlayer takes another exciting step forward, empowering developers even further in the realm of high-performance DeFi.

Altlayer's Rollup-as-a-Service (RaaS) offering eliminates the complexities of managing node infrastructure, allowing developers to focus solely on crafting innovative dApps that leverage the Parallel Stack's capabilities. This translates to significant time and resource savings for developers.

Beyond simplification, Altlayer's "restaked rollups" (set of three vertically integrated Actively Validated Services) seamlessly integrate with the Parallel Stack, adding a layer of robust security to these high-performance rollups. This translates to faster transaction finality, a more decentralized sequencing environment, and continuous verification of the rollup's state – all crucial elements for fostering trust and security within DeFi applications.

Developers gain access to a powerful toolkit that allows them to create lightning-fast, highly secure DeFi applications on the Ethereum ecosystem. This collaboration not only empowers developers but also paves the way for a more scalable and accessible DeFi landscape, ultimately benefiting the entire user base.

Future Advancements

Unifying NFTs: New xERC-721 NFT standard

The booming Ethereum ecosystem faces a challenge – fragmentation. As various scaling solutions emerge (Layer 2 rollups, high-performance EVMs), NFTs become siloed within specific platforms. This isolates communities and hinders innovation.

Sei Labs and Omni Foundation propose a solution: the xERC-721 standard. The xERC-721 NFT is introduced as a streamlined upgrade to ERC-721. It offers creators and holders of NFTs greater freedom by transcending the limitations of a single domain, opening doors to a wide array of innovation and experimentation within the Ethereum ecosystem.

Benefits of xERC-721:

  1. xERC721 tokens are able to securely move across multiple domains without introducing unnecessary risk or dependence on any privileged third party (“vendor lock-in”), such as a specific interoperability network, through the lockbox interface functions described here. In this way, it ensures that sovereignty remains in the hands of the NFT communities.
  2. xERC721 token contracts are extended with mintBatch and burnBatch function interfaces. This has been a point of pain for developers, leading to the introduction of new standards like ERC-1155. This problem is exacerbated even further when programming across multiple blockchains, as it introduces asynchrony and the cost of compensating an interoperability network for verifying and relaying the transaction.
  3. Existing NFT collections can simply upgrade to become xERC-721s through the deployment of a new portal contract that makes them accessible throughout the rest of the rollup ecosystem.

This initiative, along with EIP-7281, lays the groundwork for a standardized approach to NFTs in a fragmented Ethereum landscape. By leveraging these open standards, developers gain access to robust tooling and pave the way for further innovation in the digital asset space.

Join the discussion here: erc-7611

Sei Creator Fund: $10 million grant program

The Sei Foundation, dedicated to fostering growth within the Sei ecosystem, unveiled the Sei Creator Fund – a $10 million grant program. This initiative aims to ignite innovation by supporting both the development of entirely new projects and the expansion of existing ones focused on NFTs and social experiences within the Sei network.

Whether you're brimming with ideas for novel infrastructure or tooling, seeking to translate your creative vision into reality, or aiming to propel your existing NFT project forward, the Sei Creator Fund is here to support you.

Conclusion

Sei's steadfast commitment to resolving scalability challenges through parallel execution, optimized data storage, and future upgrades sets the stage for groundbreaking advancements, enabling projects to harness the strengths of diverse platforms to tackle complex financial challenges.

This pioneering approach heralds an era of unmatched transaction processing throughput, facilitating swift and cost-effective interactions for traders. The resulting enhancement in user experience, marked by rapid confirmations and reduced fees, holds the promise of wider DeFi adoption.

As Sei technology evolves, its impact on the DeFi landscape could be transformative, ushering in an era of unprecedented scalability, efficiency, and accessibility. By fostering a more inclusive DeFi future, Sei empowers creators and users alike to redefine decentralized finance.