Exploring zk Rollups and zk DEXes: A walkthrough of Deposit and Withdrawal Mechanisms with a Focus on Exodus Mode

Paradigm
Paradigm
Published in
16 min readFeb 14, 2024

by the DeGate team

Abstract

In the ever-evolving realm of blockchain technology, this comprehensive study delves into the intricate dynamics of Zero-Knowledge (zk) rollups and decentralized exchanges (DEXes). Specifically, we shine a spotlight on the deposit and withdrawal mechanisms, with a keen focus on platforms like DeGate, Loopring, and StarkEx, notably exploring their Exodus mode or Emergency Exits.

Our analysis transcends the surface, uncovering the complexities of transferring assets between Layer-1 (L1) and Layer-2 (L2) networks, while highlighting the pivotal role played by smart contracts in facilitating these transactions.

The investigation culminates in an exhaustive exploration of withdrawal mechanisms within DeGate, Loopring, and StarkEx, effectively distinguishing these platforms within the zk rollup landscape. With this study, our goal is to equip readers with a profound comprehension of deposit and withdrawal mechanisms, empowering them to navigate the intricate blockchain terrain and contribute to the realization of a more interconnected and efficient decentralized financial ecosystem.

Motivation

Bridges have consistently captivated interest due to their ostensibly simple goal of “transferring tokens from an L1 chain to a rollup.” This directive prompts deeper inquiries into the destination of these tokens and the foundational security assumptions governing bridging protocols. A pivotal aspect of this exploration is the Exodus mode, also referred to as Forced withdrawal, notably featured in certain rollup DEXes like Loopring, DeGate, or StarkEx.

Significance of Deposit and Withdrawal Mechanisms in Layer-2 (L2) Solutions:

Understanding the intricacies of deposit and withdrawal mechanisms is paramount in the realm of L2 solutions. These mechanisms serve as the backbone, influencing the efficacy and trustworthiness of the entire L2 ecosystem.

Advantages of a Well-Designed Mechanism:

  • Trustlessness: A well-designed mechanism ensures trustlessness, eliminating the need for participants to rely on centralized entities.
  • Permissionless Transactions: Effective mechanisms enable permissionless transactions, fostering inclusivity and accessibility.
  • Security: Robust designs enhance security through cryptographic proofs and smart contract verifications, safeguarding user funds.
  • Efficiency: Well-structured mechanisms contribute to efficient L2 solutions, facilitating swift and seamless deposit and withdrawal processes.

Risks of an Inadequate Design:

  • Trust Issues: Poorly designed mechanisms may introduce trust issues, leading to user hesitancy.
  • Centralization Risks: Inadequate designs relying on centralized entities contradict the decentralized ethos of blockchain technology.
  • Vulnerabilities: Insufficient security exposes L2 platforms to exploits or unauthorized access.
  • Operational Inefficiencies: Poorly conceived mechanisms can result in delays, errors, or complications in deposit and withdrawal processes.

Background

When you deposit tokens into a rollup, you effectively lock a certain quantity of tokens that can be withdrawn later, subject to specific conditions outlined by the contract or the protocol itself. This article delves into the workings of these systems in some of the most renowned rollup implementations available.

Polygon ZK-Evm

Polygon zkEVM is a decentralized Ethereum Layer 2 scalability solution that uses cryptographic zero-knowledge proofs to offer validity and quick finality to off-chain transaction computation, also known as a ZK-Rollup.

The ZK-Rollup executes smart contracts transparently, by publishing zero-knowledge validity proofs, while maintaining opcode compatibility with the Ethereum Virtual Machine.

Polygon ZK-Evm is currently in its mainnet beta phase, with bridge smart contracts deployed on both the Ethereum and Polygon ZK-Evm networks. To bridge tokens between these networks, users are required to provide specific data, from which a merkle leaf is computed and subsequently verified during the claiming process. Notably, one intriguing feature in the design of the Polygon ZK-Evm bridge is its capability to facilitate the transfer of tokens that do not exist on the target network. These non-existent tokens are wrapped when users claim them on the target network. In essence, the bridge contract can deploy, mint, and burn wrapped tokens for tokens that are absent on either ZK-Evm or Ethereum.

An important functionality of the bridge system is the ability to transition into an emergency state, which effectively blocks all bridging assets, including deposits and withdrawals. The Emergency State suspension includes halting operations such as sequencing of batches, batch verification, and forced batches. This state can be triggered by either the owner of a smart contract or, in the case of Polygon ZkEVM, by a Security Council multisig. The Security Council possesses the authority to invoke the Emergency State if specific conditions are met, like the pending state timeout or the identification of a critical vulnerability.

So, what exactly is the Security Council? The Polygon ZkEVM Security Council is essentially a multisig group responsible for making decisions related to the security of Polygon ZkEVM during its initial phase. Their primary role is to halt the system in the event of an Emergency State being triggered. The Security Council comprises a consortium of well-known Ethereum developers and researchers.

A noteworthy feature of the ZkEvm system is the existence of Forced Batches. These are L2 batches incorporated within an L1 transaction, and they must be included by the Trusted Sequencer. This mechanism allows users to ensure that they can withdraw their funds even in cases where they may face censorship from the Trusted Sequencer. This property is vital for the system’s censorship resistance.

For those interested in a more technical exploration, you can inspect the smart contracts used in Polygon ZK-Evm at the following GitHub repository: Polygon ZK-Evm Contracts.

Inspected smart contracts at commit here:

StarkNet

StarkNet is a decentralized and permissionless Validity-Rollup (ZK-Rollup) system that functions as a layer-two network on the Ethereum blockchain. Developed by StarkWare, StarkNet’s purpose is to empower decentralized applications (DApps) to achieve unlimited scalability without compromising the security and composability of the Ethereum network. This ZK-Rollup solution leverages STARK Proofs to create a scalable environment for developers to build and deploy DApps on the Ethereum mainnet.

In the context of StarkNet, there are distinct contracts and processes for bridging assets. The Starknet Core contract on Ethereum serves as an extension of the StarkNet messaging system, implementing the messaging bridge for the entire protocol. Separate contracts, such as Stargate Ethereum Contract Bridging and Stargate USDC Token Bridge, are responsible for asset bridging.

Notably, the availability of bridged assets on StarkWare is contingent on whether the network supports these assets, meaning there must be a token bridge already deployed on L2. Each of these token bridges communicates with the StarkNet messaging contract to transmit messages to L2, where the corresponding L2 token bridge receives the messages and proceeds to mint tokens for the intended L2 recipients. You can find a sample token bridge for reference here.

It’s important to highlight that the bridge contracts in StarkNet are not pausable, including the main messaging contract implemented in StarkNet Core. This means that, unlike some other blockchain networks like Polygon ZK-Evm, StarkNet token bridges cannot be paused. Once the contract is active, it continues to accept deposits continuously.

Starknet’s approach keeps the smart contract storage cleaner by avoiding the need to store tokens within the contract. It also provides a predefined set of tokens for users and any tokens outside this predefined set must be managed by the user. To bridge a token not initially supported by StarkNet, a user must follow these steps: 1) Deploy a corresponding token in Cairo on L2, 2) Deploy a token bridge for the token in Cairo on L2, and 3) Implement their token bridge contract on L1 to interact with StarkNet Core messaging. The source code for these processes is available for developers to use when deploying their own tokens and token bridges.

It’s worth noting that StarkNet contracts do not feature an emergency mode or Exodus mode, unlike some other blockchain networks. Some bridges on StarkNet, like the Maker DAO DAI bridge, have implemented full withdrawal mechanisms. In the event a user believes they are censored, a forceWithdraw helper method exists on L1DAIBridge to initiate a withdrawal from L1. If the withdrawal request is not processed, the user can request the DAO to initiate an evacuation procedure, which verifies the request using the L1toL2 message queue. However, it’s essential for L2 users to set up allowances for the L2_dai_bridge and register their L1 reimbursement address before using forceWithdraw. This should be done before receiving DAI on L2, as it may not be possible to set up in the case of malicious behavior on the L2 network.

StarkEx

StarkEx is a STARK-powered scalability engine designed for crypto exchanges. It leverages cryptographic proofs to verify the validity of a batch of transactions, including trades and transfers. These proofs are used to update a commitment to the state of the exchange on the Ethereum blockchain.

The primary objective of StarkEx is to enable exchanges to provide non-custodial trading with scalability, high liquidity, and reduced costs. There are two versions of StarkEx implemented: one for spot trading, known as StarkExchange, and another for derivatives trading, named StarkPerpetual.

StarkEx offers two distinct services, Perpetuals, and Exchange. For example, ImmutableX employs the Stark Exchange smart contract, while DyDx uses the Stark Perpetual smart contract.

  • User Registration:

Users who wish to interact with StarkEx must register their Ethereum address. Within the exchange, users are identified by their Stark Key, which is a public key defined over a Stark-friendly elliptic curve, distinct from the standard Ethereum elliptic curve. User registration associates an Ethereum address with a Stark Key within the main contract context.

  • Deposits:

To perform a deposit on the StarkEx contract, users need to make two calls:

A call to an ERC20 contract, granting permission for the StarkEx contract to transfer funds on their behalf.

A call to the “deposit” function within the StarkEx contract, specifying the Stark Key, amount, asset type, and the target vault ID for the deposit.

The amount should be quantized according to the asset type’s specific quantization. Once a deposit is made, it may be included in a proof, resulting in the addition of the deposited amount to the off-chain vault with the specified ID. When valid proof is received, the contract deducts the transferred funds from the pending deposits associated with the specified Stark key, asset ID, and vault ID. It’s essential to note that the deposited funds cannot be moved to the off-chain vault if the Stark key is not registered in the system.

Withdrawals on Stark Exchange require a two-step process under normal operational conditions:

Users initiate the process with an initial call to the off-chain exchange API, formally requesting a withdrawal from their vault.

Subsequently, users execute a call to the on-chain “withdraw” function, facilitating the actual withdrawal of funds. This function transfers the withdrawn funds to the user’s Ethereum or ERC20 account, depending on the token type in question.

Once a withdrawal request is initiated through the API, the exchange may incorporate it into a STARK proof. This proof serves to append the withdrawn amount to an on-chain pending withdrawals account, linked to the Stark key of the respective vault owner and the corresponding asset ID. To conclude the transfer of funds from the Stark Exchange contract to the ERC20 account, users must execute the second call. It’s important to note that only users who possess the Ethereum key that corresponds to the Stark Key associated with a pending withdrawal account have the authorization to initiate this operation.

It’s important to note that a withdrawal request cannot be canceled once funds reach the pending withdrawals account on-chain. If the exchange enters a frozen state, users can use an alternative “Escape” flow to withdraw their funds, proving ownership of off-chain funds via an “escape” call to the on-chain contract.

  • Freeze State:

The contract can transition into a frozen state under specific conditions. This occurs when users request a full withdrawal on the exchange or a forced withdrawal on the perpetual contract. If, in either case, the exchange fails to fulfill the withdrawal request by neglecting to submit valid proof, the user is granted the authority to freeze the contract. This action becomes permissible after the expiration of a designated “FREEZE_GRACE_PERIOD.” Users can initiate this by invoking the “freezeRequest” function and specifying the vaultId for which the full withdrawal request remains unserviced.

DeGate

DeGate represents a decentralized exchange (DEX) trading protocol that revolves around order book trading. It operates under the protection of the Ethereum network and is governed by a Decentralized Autonomous Organization (DAO), which holds control over its financial resources. DeGate’s primary objective is to democratize and make decentralized exchange trading accessible to a broad audience. It stands out with notable features such as Order Book Trading and grid trading.

In a manner similar to other protocols, like StarkEx, DeGate efficiently manages the deposit and withdrawal of assets. The DeGate deposit contract is accessible here.

An important distinction with DeGate is that it eliminates the need for users to handle withdrawals on Layer 1 (L1). Instead, the contract autonomously processes withdrawn tokens upon block submission. You can examine an exemplary transaction here.

  • Diverse Deposit Options:

DeGate provides advanced deposit options, enabling users to make deposits by invoking the DeGate smart contract method. This method accommodates deposits of all types of assets without imposing specific limits on the deposited amounts. In addition, DeGate offers a standard deposit avenue, permitting users to directly transfer their assets to the DeGate contract address. However, the standard deposit method, while practical, does not guarantee absolute trustlessness. Users must rely on the DeGate node to accurately credit their assets to their account balance. In an effort to mitigate potential losses to users, the node operator imposes restrictions on the amount of funds and supported tokens when using the standard deposit approach.

  • Withdrawals:

Users have the flexibility to initiate off-chain withdrawal requests at any time to retrieve assets from the DeGate smart contract. This process entails the user signing a withdrawal request, which is subsequently validated by the node. Upon successful validation, the node proceeds to lock the specified amount from the available balance of the asset and transfers it to the Operator for the rollup operation. Once the rollup transaction that incorporates the withdrawal request is included in a block, the user is promptly furnished with the withdrawn assets. In the event that the node declines the withdrawal request, users have the option to recover their assets through the process of forced withdrawal and the exodus mode.

  • Withdrawal Fees:

To initiate a withdrawal request, users are required to cover gas fees. Currently, these fees can be settled with ETH, USDC, and USDT, although this does not extend to the withdrawn token itself.

  • Addressing Withdrawal Challenges:

On specific occasions, such as when a token’s smart contract enforces restrictions on the transfer function, a withdrawal transaction may encounter complications. In such cases, the assets will remain within the DeGate smart contract. Users can make another attempt to facilitate the transfer by invoking the DeGate smart contract method. It is crucial to note that neither the recipient address nor the amount to be transferred can be modified in this context.

  • Exodus Mode:

The Operator of the DeGate off-chain node is vested with the responsibility of generating zkBlocks and submitting corresponding proofs. Should the Operator cease to operate, all off-chain transactions that have not been submitted on-chain will lose their validity. To preserve the security of users’ funds, the DeGate protocol introduces an Exodus Mode. This safeguard allows users to withdraw their assets even in the absence of an operational node.

Once the Exodus Mode is activated, the DeGate smart contract will reject new zkBlock data, maintaining its state at the last block before entering the Exodus Mode. Consequently, all off-chain transactions within DeGate, including standard transactions, withdrawals, and transfers, are suspended. Importantly, the Exodus Mode is an irreversible action, and the sole permissible action for users under these circumstances is to initiate the withdrawal of their assets.

  • Activating the Exodus Mode:

The procedure to trigger the Exodus Mode unfolds as follows:

Commencing a forced withdrawal: Users can activate a forced withdrawal by calling the “forceWithdraw” method of the DeGate contract.

Unprocessed forced withdrawal: This scenario arises when a forced withdrawal request goes unanswered by the DeGate node within a predetermined timeframe. This timeframe is configured within the DeGate smart contract.

Exodus Mode activation: As long as a forced withdrawal request remains unprocessed within the specified timeframe, any user has the authority to invoke the “notifyForcedRequestTooOld” method of the DeGate smart contract. This action effectively transitions the DeGate protocol into the Exodus Mode.

Scroll

Scroll adopts a straightforward method for bridging tokens, employing a messaging bridge akin to StarkNet’s. This bridge communicates with L2 counterparts by transmitting messages. Scroll comes equipped with prebuilt gateways for several tokens like ETH, DAI, USDC, WETH, and a custom ERC20 gateway. The custom ERC20 gateway allows users to bridge any ERC20 token, provided it is pre-set on the L1 smart contract by the Owner. However, this setup restricts bridging unrecognized tokens, preventing spam bridging while sacrificing a degree of permissionlessness.

Bridging a token deployed on L2 follows a similar process, requiring the token to be mapped by the contract owner for bridging eligibility. This approach contrasts with Polygon’s, where any token can be bridged. Scroll lacks an emergency exit or exodus mode, setting it apart from certain other platforms.

Inspected at commit here.

ZKSync Era

Similar to Polygon, tokens can be sent, deploying them if absent on zkSync. However, withdrawal requires prior bridging from L1, restricting withdrawal for randomly deployed tokens on zkSync.

Bridging in the ZKSync Era involves two contracts — one on Layer 1 (L1) and the other on Layer 2 (L2) — communicating seamlessly through L1 <-> L2 interoperability.

When it comes to taking your funds from Layer 2 (L2) to Layer 1 (L1) in ZKSync Era, they’ve got an extra layer of security with a 24-hour delay during the Alpha phase. It serves as a precautionary measure to ensure everything is secure and sound. The process unfolds like this: kick off by signaling the L2 bridge through its withdrawal method. Then, it performs an operation called “burning” L2 tokens, essentially marking them for withdrawal. Following this, a specialized message (L2 -> L1) is dispatched to notify Layer 1 that the withdrawal is in progress. The L1 bridge catches wind of this, giving the green light to unlock the funds, completing the withdrawal.

For those intrigued by the idea of crafting something unique, developers have the flexibility to fashion their bridges using dedicated Solidity contracts. There are illustrative examples for both L1 and L2 — think IL1Bridge.sol and L2ERC20Bridge.sol — to provide a helpful starting point. Touching the priority queue, it operates as a sort of lineup where a nominal fee is required to maintain order and deter any potential mischief.

Now, let’s pivot to the process of injecting funds into L2 — it’s a bit of a distinct dance. Commence by informing the L1 bridge of your intention to deposit through its deposit method. Your L1 tokens undergo a temporary lock. Subsequently, the L1 and L2 bridges engage in a conversation, orchestrating the transformation of your tokens into a new existence in L2. If your token is novel to the zkSync network, a bespoke contract is established for it. The action is documented with a note (L2 -> L1 log) to affirm the seamless execution. As the curtain falls, the finalizeDeposit method takes center stage, ensuring your funds are securely and substantively placed in L2. Oh, and a little reminder: L2 tokens boast unique addresses distinct from their L1 counterparts, adding a layer of distinction to the whole affair!

In zkSync Lite, which featured ForcedExit (unlike the zkSync Era), the ForcedExit mechanism provided a secure way to withdraw funds in specific situations. This L2 transaction enabled the withdrawal of funds from an unowned account that lacked a signing key. Unlike Withdraw transactions, ForcedExit didn’t allow users to choose the Ethereum address or withdrawal amount. Instead, it requested the withdrawal of all available funds of a particular token from the target L2 address to the target L1 address. Users initiating ForcedExit transactions needed to cover the associated fee, which was identical to the fee for Withdraw operations. This feature was particularly useful when dealing with accounts unable to set a signing key, such as smart contract accounts, and when there existed an L2 account capable of sending this type of transaction.

Conclusion

In this comprehensive exploration of L2 solutions — Polygon ZK-Evm, StarkNet, StarkEx, DeGate, Scroll, and zkSync — we’ve traversed the diverse landscape of deposit and withdrawal mechanisms within the decentralized ecosystem.

  • Polygon ZK-Evm: Distinguished by its Emergency State and Forced Batches, Polygon ZK-Evm ensures secure token bridging and censorship resistance. The Security Council, comprised of Ethereum developers, holds authority, and the Forced Batches mechanism adds a layer of censorship resistance.
  • StarkNet: Prioritizing scalability and security, StarkNet facilitates unlimited scalability for DApps on the Ethereum network. It provides security without compromising composability. Unlike some other networks, StarkNet doesn’t feature an emergency mode, relying on its robust design to maintain operational integrity.
  • StarkEx: As a STARK-powered scalability engine for crypto exchanges, StarkEx emphasizes non-custodial trading. The freeze state, user registration, and withdrawal mechanisms contribute to its robustness, ensuring security and liquidity.
  • DeGate: Standing out with its decentralized exchange trading protocol, DeGate employs order book trading and features advanced deposit and withdrawal mechanisms. The Exodus Mode enhances security, allowing users to withdraw assets even in the absence of an operational node.
  • Scroll: Adopting a messaging bridge akin to StarkNet, Scroll simplifies token bridging. With prebuilt gateways and a focus on permissionlessness, Scroll’s straightforward approach contrasts with some limitations in emergency exits.
  • zkSync: In the zkSync Era, bridging tokens involves an extra layer of security with a 24-hour delay. Developers can craft their bridges, and the process of injecting funds into L2 is meticulously orchestrated. In zkSync Lite, the ForcedExit mechanism offers a secure way to withdraw funds from unowned accounts.

Each solution brings its unique strengths to the table, addressing various needs in the decentralized landscape. Whether it’s Polygon’s censorship resistance, StarkNet’s scalability and secure design, StarkEx’s non-custodial trading, DeGate’s democratization of DEX trading, Scroll’s simplicity, or zkSync’s layered security, these L2 solutions contribute to the evolution of a secure, interconnected, and efficient decentralized financial ecosystem. As the blockchain space continues to innovate, these mechanisms play a pivotal role in shaping the future of decentralized finance.

About the author

DeGate is a ZK-Rollup Orderbook DEX that allows you to Trade easy, Sleep easy. It is the only active Stage 2 rollup measured by L2Beat. Stage 2 represents the most advanced maturity level of Layer 2s.

DeGate DEX enables spot trading with Limit Order while being in self-custody of your funds. No fees for Maker orders and very low fees for Taker orders, with distinctive trading features — decentralized grid strategy and DCA.

--

--