There are many exchanges for cryptocurrency trading in the world. Most of these exchanges are centralised exchanges such as Binance, Coinbase, Kraken, KuCoin, etc. These centralised exchanges offer many trading types like spot trading, futures trading, options trading, etc.
But, in the decentralised world of cryptocurrencies, a user expects that he can access all of these trading options in a decentralised manner. Many spot trading exchanges have been created through these years. Exchanges like Uniswap, SushiSwap, PancakeSwap, etc. These exchanges are the decentralised format of spot trading. Using these exchanges, one can trade real crypto-assets. But, none of these exchanges offers derivative trading. Here, I am going to explain derivative trading for those who are not familiar with the concept, and then jump into the dYdX Project.
Derivative trading is when traders speculate on the future price action of an asset via the buying or selling of derivative contracts with the aim of achieving enhanced gains when compared with buying the underlying asset outright. Derivative trading has grown in popularity since the 1980s, and investors can now trade derivatives on a range of financial markets including stocks, currencies, and commodities.
Traders can also use derivatives for hedging purposes in order to alleviate risk against an existing position. With derivatives, traders are able to go short and profit from falling asset prices. Therefore, they can use derivatives to hedge against any existing long positions.
A derivative is a complex type of financial security that is set between two or more parties. Traders use derivatives to access specific markets and trade different assets. Typically, derivatives are considered a form of advanced investing. The most common underlying assets for derivatives are stocks, bonds, commodities, currencies, interest rates, and market indexes. Contract values depend on changes in the prices of the underlying asset.
There are many different types of derivatives that can be used for risk management, speculation, and leveraging a position. The derivatives market is one that continues to grow, offering products to fit nearly any need or risk tolerance.
There are two classes of derivative products: "lock" and "option." Lock products (e.g., futures, forwards, or swaps) bind the respective parties from the outset to the agreed-upon terms over the life of the contract. Option products (e.g., stock options), on the other hand, offer the holder the right, but not the obligation, to buy or sell the underlying asset or security at a specific price on or before the option's expiration date. The most common derivative types are futures, forwards, swaps, and options.
A futures contract, or simply futures, is an agreement between two parties for the purchase and delivery of an asset at an agreed-upon price at a future date. Futures are standardized contracts that trade on an exchange. Traders use a futures contract to hedge their risk or speculate on the price of an underlying asset. The parties involved are obligated to fulfil a commitment to buy or sell the underlying asset.
For example, say that on Nov. 6, 2021, Company A buys a futures contract for oil at a price of $62.22 per barrel that expires Dec. 19, 2021. The company does this because it needs oil in December and is concerned that the price will rise before the company needs to buy. Buying an oil futures contract hedges the company's risk because the seller is obligated to deliver oil to Company A for $62.22 per barrel once the contract expires. Assume oil prices rise to $80 per barrel by Dec. 19, 2021. Company A can accept delivery of the oil from the seller of the futures contract, but if it no longer needs the oil, it can also sell the contract before expiration and keep the profits.
In this example, both the futures buyer and seller hedge their risk. Company A needed oil in the future and wanted to offset the risk that the price may rise in December with a long position in an oil futures contract. The seller could be an oil company concerned about falling oil prices that wanted to eliminate that risk by selling or shorting a futures contract that fixed the price it would get in December.
It is also possible that one or both of the parties are speculators with the opposite opinion about the direction of December oil. In that case, one might benefit from the contract, and one might not. Take, for example, the futures contract for West Texas Intermediate (WTI) oil that trades on the CME and represents 1,000 barrels of oil. If the price of oil rose from $62.22 to $80 per barrel, the trader with the long position—the buyer—in the futures contract would have profited $17,780 [($80 - $62.22) x 1,000 = $17,780]. The trader with the short position—the seller—in the contract would have a loss of $17,780.
An options contract is similar to a futures contract in that it is an agreement between two parties to buy or sell an asset at a predetermined future date for a specific price. The key difference between options and futures is that with an option, the buyer is not obliged to exercise their agreement to buy or sell. It is an opportunity only, not an obligation, as futures are. As with futures, options may be used to hedge or speculate on the price of the underlying asset.
Imagine an investor who owns 100 shares of a stock worth $50 per share. They believe the stock's value will rise in the future. However, this investor is concerned about potential risks and decides to hedge their position with an option. The investor could buy a put option that gives them the right to sell 100 shares of the underlying stock for $50 per share—known as the strike price—until a specific day in the future—known as the expiration date.
Assume the stock falls in value to $40 per share by expiration and the put option buyer decides to exercise their option and sell the stock for the original strike price of $50 per share. If the put option cost the investor $200 to purchase, then they have only lost the cost of the option because the strike price was equal to the price of the stock when they originally bought the put. A strategy like this is called a protective put because it hedges the stock's downside risk.
Alternatively, assume an investor doesn't own the stock currently worth $50 per share. They believe its value will rise over the next month. This investor could buy a call option that gives them the right to buy the stock for $50 before or at expiration. Assume this call option cost $200 and the stock rose to $60 before expiration. The buyer can now exercise their option and buy a stock worth $60 per share for the $50 strike price for an initial profit of $10 per share. A call option represents 100 shares, so the real profit is $1,000, less the cost of the option—the premium—and any brokerage commission fees.
In both examples, the sellers are obligated to fulfil their side of the contract if the buyers choose to exercise the contract. However, if a stock's price is above the strike price at expiration, the put will be worthless and the seller (the option writer) gets to keep the premium as the option expires. If the stock's price is below the strike price at expiration, the call will be worthless and the call seller will keep the premium.
There are more derivative types, but we are not going to talk more about them. Getting familiar with these two types of derivative trading would be enough for our purpose of knowing dYdX Project. But, before diving into the project, it is better to talk about crypto derivative trading and some problems that can happen in the decentralised way of the derivative trading. In the cryptocurrency world, other than two types that have been described above, there is one more derivative trading type named perpetual or perpetual futures.
A perpetual contract, also called a perpetual futures contract or perpetual swap, is the most prolific type of crypto derivative, especially among day traders. In traditional finance, the equivalent of a perpetual contract would be contracted for difference (CFD).
The main difference between perpetual contracts vs. futures and options is that perpetual contracts do not have an expiry date. Positions can be kept for as long as the trader wants, provided they pay holding fees, called the funding rate. The account must also contain a minimum amount, called the margin.
Underlying assets typically change in price, which means that the difference between the index price and the price of perpetual futures contracts is typically huge. If, for example, the price of the perpetual contract is higher than the index, those who chose to “go long” would normally pay the funding rate to cover the price difference.
Likewise, those who chose to “go short” would pay the funding rate to cover the price difference should the perpetual futures contract price be lower than the index price.
In the cryptocurrency world, the main idea is to make everything decentralised, as much as possible. But, sometimes this can be very expensive. As you probably know, gas fees in the Ethereum blockchain can go really high. This can be a real problem for traders. Since traders, who are not trading in centralised exchanges, need to submit their transactions on-chain (on the underlying blockchain such as Ethereum), they need to pay gas fees and trading fees. If the gas fee goes up in price, which is a very common thing in the times that the blockchain gets crowded, traders will have to pay much higher fees than the centralised exchanges. This problem can be seen more in the derivative tradings which usually have more complex smart contracts. Also, in these types of trading, in contrast to spot trading, people have more frequency in their positions. Meaning that they usually open and close their trades more often. So, they have to pay more and more gas.
dYdX Project is a decentralised derivative exchange that gives you perpetual futures type of derivatives. Noticing all the above problems, this project uses a smart way to maintain the exchange. This smart way is called Layer 2. I am going to talk about layer 2s and the specific layer 2 that dYdX is using and after that, it’s time for dYdX project.
As the number of people using Ethereum has grown, the blockchain has reached certain capacity limitations. This has driven up the cost of using the network, creating the need for "scaling solutions." There are multiple solutions being researched, tested and implemented that take different approaches to achieve similar goals.
The main goal of scalability is to increase transaction speed (faster finality), and transaction throughput (high transactions per second), without sacrificing decentralization or security (more on the Ethereum vision). On the layer 1 Ethereum blockchain, high demand leads to slower transactions and nonviable gas prices. Increasing the network capacity in terms of speed and throughput is fundamental to the meaningful and mass adoption of Ethereum.
While speed and throughput are important, it is essential that scaling solutions enabling these goals remain decentralized and secure. Keeping the barrier to entry low for node operators is critical in preventing a progression towards centralized and insecure computing power.
Conceptually we first categorize scaling as either on-chain scaling or off-chain scaling.
This method of scaling requires changes to the Ethereum protocol (layer 1 Mainnet). Sharding is currently the main focus for this method of scaling.
Sharding
Sharding is the process of splitting a database horizontally to spread the load. In an Ethereum context, sharding will reduce network congestion and increase transactions per second by creating new chains, known as “shards.” This will also lighten the load for each validator who will no longer be required to process the entirety of all transactions across the network.
Sharding can help reduce the latency or slowness of a network since it splits a blockchain network into separate shards. However, there are some security concerns surrounding sharding in which shards can be attacked.
However, one of the major challenges with blockchain technology is that as additional computers are added to the network and more transactions are processed, the network can become bogged down, slowing the process—called latency. Latency is a hurdle to blockchain being adopted for widespread use, particularly when compared to the current electronic payment systems that work quickly and efficiently. In other words, scalability is a challenge for blockchain since the networks may not be able to handle the increased amounts of data and transaction flow as more and more industries adopt the technology.
One of the solutions being considered for creating latency-free scalability is the process of sharding. Sharding is designed to spread out the workload of a network into partitions, which may help reduce latency and allow more transactions to be processed by the blockchain.
Sharding can be accomplished through the horizontal partitioning of databases through division into rows. Shards, as the rows are called, are conceptualized based on characteristics. For example, one shard might be responsible for storing the state and transaction history for a specific type of address. Also, it might be possible to divide shards based on the type of digital asset stored in them. Transactions involving that digital asset might be made possible through a combination of shards.
As an example, consider a rental real estate transaction in which multiple shards are involved. These shards correspond to different entities involved in the transaction, from customer names to digital keys configured into a smart lock that is made available to the renter upon rent payment.
Each shard is still able to be shared amongst the other shards, which maintains a key aspect of blockchain technology—the decentralized ledger. In other words, the ledger is still accessible to every user allowing them to view all of the ledger transactions.
Off-chain solutions are implemented separately from layer 1 Mainnet - they require no changes to the existing Ethereum protocol. Some solutions, known as "layer 2" solutions, derive their security directly from layer 1 Ethereum consensus, such as optimistic rollups, zero-knowledge rollups or state channels. Other solutions involve the creation of new chains in various forms that derive their security separately from Mainnet, such as sidechains, validiums, or plasma chains. These solutions communicate with Mainnet, but derive their security differently to obtain a variety of goals.
Layer 2 Scaling
This category of off-chain solutions derives its security from Mainnet Ethereum.
Layer 2 is a collective term for solutions designed to help scale your application by handling transactions off the Ethereum Mainnet (layer 1) while taking advantage of the robust decentralized security model of Mainnet. Transaction speed suffers when the network is busy, making the user experience poor for certain types of dapps. And as the network gets busier, gas prices increase as transaction senders aim to outbid each other. This can make using Ethereum very expensive.
Most layer 2 solutions are centered around a server or cluster of servers, each of which may be referred to as a node, validator, operator, sequencer, block producer, or similar term. Depending on the implementation, these layer 2 nodes may be run by the individuals, businesses or entities that use them, by a 3rd party operator, or by a large group of individuals (similar to Mainnet). Generally speaking, transactions are submitted to these layer 2 nodes instead of being submitted directly to layer 1 (Mainnet). For some solutions, the layer 2 instance then batches them into groups before anchoring them to layer 1, after which they are secured by layer 1 and cannot be altered. The details of how this is done vary significantly between different layer 2 technologies and implementations.
A specific layer 2 instance may be open and shared by many applications, or may be deployed by one project and dedicated to supporting only their application.
Why is layer 2 needed?
Increased transactions per second greatly improves user experience and reduces network congestion on Mainnet Ethereum.
Transactions are rolled up into a single transaction to Mainnet Ethereum, reducing gas fees for users, making Ethereum more inclusive and accessible for people everywhere.
Any updates to scalability should not be at the expense of decentralization or security – layer 2 builds on top of Ethereum.
There are application-specific layer 2 networks that bring their own set of efficiencies when working with assets at scale.
As mentioned above, there are different types of layer 2 solutions. Here, I am going to explain Zero-Knowledge rollups. This is because only ZK-rollups are relevant to dYdX, and other kinds of layer 2s are not related to this project. But, you can find other types, their definition, and how they work here.
Zero-knowledge rollups (ZK-rollups) are layer 2 scaling solutions that increase throughput on Ethereum Mainnet by moving computation and state-storage off-chain. ZK-rollups can process thousands of transactions in a batch and then only post some minimal summary data to Mainnet. This summary data defines the changes that should be made to the Ethereum state and some cryptographic proof that those changes are correct.
Zero-knowledge rollups (ZK-rollups) bundle (or 'roll up') transactions into batches that are executed off-chain. Off-chain computation reduces the amount of data that has to be posted to the blockchain. ZK-rollup operators submit a summary of the changes required to represent all the transactions in a batch rather than sending each transaction individually. They also produce validity proofs to prove the correctness of their changes. The validity proof demonstrates with cryptographic certainty that the proposed changes to Ethereum's state are truly the end-result of executing all the transactions in the batch.
The ZK-rollup's state is maintained by a smart contract deployed on the Ethereum network. To update this state, ZK-rollup nodes must submit a validity proof for verification. As mentioned, the validity proof is a cryptographic assurance that the state-change proposed by the rollup is really the result of executing the given batch of transactions. This means that ZK-rollups only need to provide validity proofs to finalize transactions on Ethereum instead of posting all transaction data on-chain like optimistic rollups.
ZK-rollups write transactions to Ethereum as calldata
. calldata
is where data that is included in external calls to smart contract functions gets stored. Information in calldata
is published on the blockchain, allowing anyone to reconstruct the rollup’s state independently. ZK-rollups use compression techniques to reduce transaction data—for example, accounts are represented by an index rather than an address, which saves 28 bytes of data. On-chain data publication is a significant cost for rollups, so data compression can reduce fees for users.
The ZK-rollup's core architecture is made up of the following components:
On-chain contracts: As mentioned, the ZK-rollup protocol is controlled by smart contracts running on Ethereum. This includes the main contract which stores rollup blocks, tracks deposits, and monitors state updates. Another on-chain contract (the verifier contract) verifies zero-knowledge proofs submitted by block producers. Thus, Ethereum serves as the base layer or "layer 1" for the ZK-rollup.
Off-chain virtual machine (VM): While the ZK-rollup protocol lives on Ethereum, transaction execution and state storage happen on a separate virtual machine independent of the EVM. This off-chain VM is the execution environment for transactions on the ZK-rollup and serves as the secondary layer or "layer 2" for the ZK-rollup protocol. Validity proofs verified on Ethereum Mainnet guarantee the correctness of state transitions in the off-chain VM.
ZK-rollups rely on the main Ethereum protocol for the following:
Data availability. ZK-rollups publish state data for every transaction processed off-chain to Ethereum. With this data, it is possible for individuals or businesses to reproduce the rollup’s state and validate the chain themselves. Ethereum makes this data available to all participants of the network as calldata
.
ZK-rollups don’t need to publish much transaction data on-chain because validity proofs already verify the authenticity of state transitions. Nevertheless, storing data on-chain is still important because it allows permissionless, independent verification of the L2 chain's state which in turn allows anyone to submit batches of transactions, preventing malicious operators from censoring or freezing the chain.
On-chain is required for users to interact with the rollup. Without access to state data users cannot query their account balance or initiate transactions (e.g., withdrawals) that rely on state information.
Transaction Finality. Ethereum acts as a settlement layer for ZK-rollups: L2 transactions are finalized only if the L1 contract accepts the validity proof. This eliminates the risk of malicious operators corrupting the chain (e.g., stealing rollup funds) since every transaction must be approved on Mainnet. Also, Ethereum guarantees that user operations cannot be reversed once finalized on L1.
Censorship Resistance. Most ZK-rollups use a "supernode" (the operator) to execute transactions, produce batches, and submit blocks to L1. While this ensures efficiency, it increases the risk of censorship: malicious ZK-rollup operators can censor users by refusing to include their transactions in batches.
As a security measure, ZK-rollups allow users to submit transactions directly to the rollup contract on Mainnet if they think they are being censored by the operator. This allows users to force an exit from the ZK-rollup to Ethereum without having to rely on the operator’s permission.
State Commitments
The ZK-rollup’s state, which includes L2 accounts and balances, is represented as a Merkle tree. A cryptographic hash of the Merkle tree’s root (Merkle root) is stored in the on-chain contract, allowing the rollup protocol to track changes in the state of the ZK-rollup.
The rollup transitions to a new state after the execution of a new set of transactions. The operator who initiated the state transition is required to compute a new state root and submit it to the on-chain contract. If the validity proof associated with the batch is authenticated by the verifier contract, the new Merkle root becomes the ZK-rollup’s canonical state root.
Besides computing state roots, the ZK-rollup operator also creates a batch root—the root of a Merkle tree comprising all transactions in a batch. When a new batch is submitted, the rollup contract stores the batch root, allowing users to prove a transaction (e.g., a withdrawal request) was included in the batch. Users will have to provide transaction details, the batch root, and a Merkle proof showing the inclusion path.
Validity Proofs
The new state root that the ZK-rollup operator submits to the L1 contract is the result of updates to the rollup’s state. Say Alice sends 10 tokens to Bob, the operator simply decreases Alice’s balance by 10 and increments Bob’s balance by 10. The operator then hashes the updated account data, rebuilds the rollup's Merkle tree, and submits the new Merkle root to the on-chain contract.
But the rollup contract won’t automatically accept the proposed state commitment until the operator proves the new Merkle root resulted from correct updates to the rollup’s state. The ZK-rollup operator does this by producing a validity proof, a succinct cryptographic commitment verifying the correctness of batched transactions.
Validity proofs allow parties to prove the correctness of a statement without revealing the statement itself—hence, they are also called zero-knowledge proofs. ZK-rollups use validity proofs to confirm the correctness of off-chain state transitions without having to re-execute transactions on Ethereum. These proofs can come in the form of a ZK-SNARK (Zero-Knowledge Succint Non-Interactive Argument of Knowledge) or ZK-STARK (Zero-Knowledge Scalable Transparent Argument of Knowledge).
Both SNARKs and STARKs help attest to the integrity of off-chain computation in ZK-rollups, although each proof type has distinctive features.
ZK-SNARKs. For the ZK-SNARK protocol to work, creating a Common Reference String (CRS) is necessary: the CRS provides public parameters for proving and verifying validity proofs. The security of the proving system depends on the CRS setup; if the information used to create public parameters fall into the possession of malicious actors they may be able to generate false validity proofs.
Some ZK-rollups attempt to solve this problem by using a multi-party computation ceremony (MPC), involving trusted individuals, to generate public parameters for the ZK-SNARK circuit. Each party contributes some randomness (called "toxic waste") to the construct the of CRS, which they must destroy immediately.
Trusted setups are used because they increase the security of the CRS setup. As long as one honest participant destroys their input, the security of the ZK-SNARK system is guaranteed. Still, this approach requires trusting those involved to delete their sampled randomness and not undermine the system's security guarantees.
Trust assumptions aside, ZK-SNARKs are popular for their small proof sizes and constant-time verification. As proof verification on L1 constitutes the larger cost of operating a ZK-rollup, L2s use ZK-SNARKs to generate proofs that can be verified quickly and cheaply on Mainnet.
ZK-STARKs. Like ZK-SNARKs, ZK-STARKs prove the validity of off-chain computation without revealing the inputs. However, ZK-STARKs are considered an improvement on ZK-SNARKs because of their scalability and transparency.
ZK-STARKs are 'transparent', as they can work without the trusted setup of a Common Reference String (CRS). Instead, ZK-STARKs rely on publicly verifiable randomness to set up parameters for generating and verifying proofs.
ZK-STARKs also provide more scalability because the time needed to prove and verify validity proofs increases quasilinearly in relation to the complexity of the underlying computation. With ZK-SNARKs, proving and verification times scale linearly in relation to the size of the underlying computation. This means ZK-STARKs require less time than ZK-SNARKs for proving and verifying when large datasets are involved, making them useful for high-volume applications.
ZK-STARKs are also secure against quantum computers, while the Elliptic Curve Cryptography (ECC) used in ZK-SNARKs is widely believed to be susceptible to quantum computing attacks. The downside to ZK-STARKs is that they produce larger proof sizes, which are more expensive to verify on Ethereum.
Finally, after all that have been said above, it is time to understand dYdX Protocol. dYdX is the mathematical symbol of the derivative, thus the protocol name. This protocol has been created to make perpetual futures trading easier and much more accessible. As discussed above, perpetual futures trading is usually a high-frequency method of trading. High-frequency in trading in a decentralised way is equal to high gas fees. Therefore, it will be best to use a layer 2 to make everything cheaper. So, let’s understand dYdX technology and how it works, and after that, I am going to explain its tokenomics.
As mentioned earlier, dYdX is using a layer 2 solution. This layer 2 solution is a zero-knowledge rollup using ZK-STARKs as its validity proof. To be more accurate, dYdX is using StarkWare’s StarkEx. Here I am going to explain how StarkEx works, and what are its features. This explanation directly applies to dYdX Protocol, since it uses StarkEx as its main layer.
High-Level Overview
StarkEx is an Ethereum Layer 2 (L2) scalability solution that is based on validity proofs. It can make data available using either ZK-Rollup or Validium.
Every application built on top of StarkEx defines its own business logic and runs on the StarkEx Service.
StarkEx provides both spot and perpetual trading layers for applications. Also, the perpetual platform is written in 2 versions, v1.0 and v2.0. Since dYdX is a perpetual trading platform built on top of StarkEx, and it uses the latest version of StarkEx perpetual, here I will explain only the perpetual trading v2.0 actions that StarkEx provides.
The StarkEx system has an off-chain component and an on-chain component.
The off-chain component:
Holds the state of orders
Executes transactions in the system
Sends state updates to the on-chain component
The on-chain component:
Enforces the validity of state transition
Holds state commitments and system assets
(StarkEx for spot trading) Manages on-chain accounts, which are useful in the context of Layer 1 (L1) dApp interoperability and DeFi pooling.
The StarkEx Flow:
All transactions in the system are executed by the application and sent to the StarkEx Service.
The StarkEx Service batches transactions and sends the batch to SHARP, a shared proving service, to generate a proof attesting to the validity of the batch.
SHARP sends the STARK proof to the on-chain STARK Verifier for verification.
The StarkEx Service then sends an on-chain state update transaction to the StarkEx Contract, which will be accepted only if the verifier finds the proof valid.
Types of user interaction: The user submits transfers or limit orders, signed by their starkKey
, directly to the application. Limit orders are matched together and sent as a settlement to the StarkEx Service. Transfers are sent as-is. Additional logic can be enforced on different types of transfers.
To withdraw their funds, the user submits an off-chain withdrawal request to the application. This request is sent to the StarkEx Service, and the user can access their funds on-chain once the state update containing the withdrawal is accepted.
To prevent censorship, if the user’s withdrawal requests are not fulfilled, they can force the execution with forced transactions.
StarkEx components:
Application — system operator
This off-chain component receives user transactions and defines the business logic and order of execution. It passes transactions to the StarkEx Service.
StarkEx Service — batching and coordination
An off-chain component responsible for batching a set of operations and updating the state of the system according to the operations. For each batch, it sends the batch of operations (as a Cairo execution trace) to SHARP in order to prove its validity. Once the proof is verified, it publishes the new state on-chain. The state is represented by a Merkle tree in which "leaves" are vaults. The structure and content of each vault vary according to the specific business logic implemented. The Merkle tree root represents the state commitment to be submitted on-chain.
SHARP — proving
A shared proving service for Cairo programs. It receives proof requests from different applications and outputs proofs to attest to the validity of Cairo executions. The output proof can be shared among multiple proof requests.
STARK Verifier — verification
An on-chain component that receives a state update validity proof and verifies that the proof is valid.
StarkEx Contract - state updates, deposits, and withdrawals
This contract has two main functionalities:
Update the state of the system after verifying that the validity conditions are met.
Manage deposits and withdrawals to and from StarkEx in a non-custodial manner, so that in any scenario, the user is able to withdraw their funds.
StarkEx Deep Dive
Vault of off-chain state of the perpetual trading contains the following fields:
starkKey
- the public key of the vault’s owner. Transfers and trades that refer to this vault must be signed with this key.
collateralAmount
- the amount of collateral in the vault.
A list of synthetic assetId
. For each assetId
we have:
assetId
amount
(resolutionised)
cachedFundingIndex
The Flow Descriptions of Off-Chain Accounts
Deposit:
The first step taken by the user who wishes to trade is to deposit her funds into StarkEx. This is done by first depositing the funds to the on-chain StarkEx contract. A corresponding off-chain deposit transaction then updates the off-chain state.
Alice makes an on-chain transaction to deposit funds. The deposit operation supports deposits of ETH, ERC-20, ERC-721, and ERC-1155.
The off-chain app sends a deposit transaction to the StarkEx gateway.
The StarkEx service verifies that there are indeed enough funds in the pending deposits area in the StarkEx smart contract to complete the off-chain deposit.
If the deposit is valid, it is included in a batch to be submitted on-chain along with the validity proof.
As part of the state update
, the smart contract deduces the relevant amount of funds from the "pending deposits" area.
Withdrawal:
The user submits a WithdrawalToAddress
request to the off-chain application.
This request includes the user’s ethereumAddress
in addition to the user’s signature.
The off-chain app checks the validity of the withdrawal request according to its business logic and the relevant positionId
state. If it is valid, it sends the off-chain withdrawal transaction to the StarkEx service.
StarkEx verifies that the withdrawal request is valid, according to the relevant business logic statement to be proved, and the relevant positionId
state. If the withdrawal is valid, it is aggregated to a batch to be submitted on-chain along with a validity proof.
Upon performing state update, the StarkEx smart contract moves the relevant funds to the withdrawal area, under the user ethereumAddress
.
Once the funds are in the withdrawal area, every user can make an on-chain call to withdraw the funds to the ethereumAddress
the funds are belonged to. The ownerKey parameter should be the ethereum address, and not the stark key. For more info, see withdrawals
​.
Since dYdX does not support off-chain minting, I am not going to explain them here. But, if you are interested you may go to this link to understand the flow.
Transfer:
Alice sends the Application a signed Transfer request, which includes:
The receiving vaultId,
and starkKey
The vaultId
and starkKey
of the vault that funds will be taken from
The relevant ( quantized) amount
and assetId
expiration_timestamp
nonce
The Application sends the Transfer transaction to StarkEx service. StarkEx service verifies:
The signature is valid and the signing starkKey
matches the vaultId
The sender vaultId
has enough funds (according to the application business logic)
The receiver vaultId
indeed has the receiver starkKey
The Transfer has not expired
The Transfer was not executed before (checked in the ordersTree
)
For perpetual trading: the assetId
corresponds to the collateral token
If the Transfer is valid, the Transfer is included in a batch to be submitted on-chain along with validity proof.
Again, dYdX does not support Conditional Transfer and Transaction bundling in user level (the user will not see these actions through the platform). Therefore, I am going directly to Perpetual Trading action.
Perpetual Trading:
Let’s look at the following example. Alice wants to sell 1 synthetic BTC for 30000 USDC and pay a maximum amount of 5 USDC as a fee for the trade. Bob wants to sell 30000 USDC for 0.99 synthetic BTC and pay a maximum amount of 10 USDC as a fee. Both send the corresponding (signed) limit order requests to the off-chain app.
The limit order contains the user’s positionId
, the assetId
and the amount
of the traded assets (synthetic and collateral), as well as feeAmount
, an expirationTimestamp
of the order and a nonce
(to prevent replay attacks).
The application matches the limit orders of Alice and Bob and creates a Settlement transaction. This transaction includes both orders, alongside the actual transferred amounts between Alice and Bob’s vaults. In the example above, 0.99BTC will be transferred from Alice to Bob in exchange for 30,000 USDC.
Note that after the settlement Alice still has an open order with the remaining 0.01 BTC to sell (and at least 300 USDC to receive for them), and this amount can be matched against further orders.
At this point StarkEx checks the validity of the Settlement using its components that are passed to StarkEx.
If the Settlement is valid, it is included in a batch to be submitted on-chain along with validity proof.
Forced Operations:
For perpetual trading applications, there are two forced actions: Forced Withdrawal and Forced Trade.
We show an example scenario to explain why these two forced operations are required to guarantee self-custody of funds.
Alice has a position with +1 BTC and 0 USDC and BTC price is 20,000 USDC. Alice wants to withdraw all of her funds. She can submit an on-chain Forced Withdrawal request. However, due to the risk factor of the synthetic asset, she can only withdraw 19,300 USDC and not the entire amount (20,000 USDC). Otherwise, her position would fall below the maintenance margin. In order to get the entire amount, she must own only collateral. To achieve that, she can use Forced Trade operation and sell her BTC for USDC.
Forced Withdrawal:
Once Alice is registered and wants to perform Forced Withdrawal, she calls the fullWithdrawalRequest
function in the StarkEx contract. This function gets three parameters: starkKey
,positionId
and amount.
Off-chain, the request is valid only if the providedstarkKey
corresponds to the provided positionId
, and the supplied amount of funds can indeed be withdrawn without falling below the maintenance margin.
Forced Trade:
In order to submit Forced Trade, both sides of the trade must agree in advance on the trade and must be registered.
Then, one of them submits an on-chain request that contains the signature of the second party. The request contains the following parameters:
starkKey
and positionId
of both parties
collateralAssetId
and amountCollateral
to transfer
syntheticAssetId
and amountSynthetic
to transfer in return
a_is_buying_synthetic
- a flag that indicates which of them is buying the synthetics
submission_expiration_timestamp
- given in hours. This is to protect the non-submitter side from executing the trade in an arbitrary future time
nonce
- used to protect the non-submitter side in the trade against replay attack
eth_signature
- the non-submitter signature on all the parameters
premiumCost
- a parameter that determines the gas-cost of the transaction.
A Forced Trade request is considered valid at the smart contract level (i.e. it is recorded as an action item that the application must serve), only if there has been no request with the same parameters (including the nonce) before, and blockchain_time / 3600 <= submission_expiration_time
.
If this is the case, the request is moved to the application. The trade takes effect if the specified positionId
values correspond to the specified starkKey
values and the trade leaves both positions above the maintenance margin (or improve their value to maintenance margin ratio)
If this is not the case StarkEx will prove the invalidity of the request and would not execute the trade.
Now that we are familiar with dYdX technology and how it works, it is time to know its tokenomics, what utilities the token has, and what it brings to the platform.
dYdX Protocol has a token named DYDX. DYDX is a governance token that allows the dYdX community to truly govern the dYdX Layer 2 Protocol ("the protocol"). By enabling shared control of the protocol, DYDX allows traders, liquidity providers, and partners of dYdX to work collectively towards an enhanced Protocol.
DYDX enables a robust ecosystem around governance, rewards, and staking — each designed to drive future growth and decentralization of dYdX, resulting in a better experience for users.
Staking pools are designed to promote liquidity and safety on the Protocol. Rewards programs for trading, liquidity providing, and past usage of dYdX will help drive growth and adoption of dYdX.
Alongside the launch of DYDX, they also released:
A governance product at dydx.community
Liquidity Staking Pool for USDC
Safety Staking Pool for DYDX
Trading Rewards
Retroactive Mining Rewards for past users
Liquidity Provider Rewards
Governance
Active and past governance proposals can be viewed, and active governance proposals can be voted on.
Holders of DYDX and stkDYDX are granted two types of governance powers: proposing power and voting power. Via the dashboard, users may view their proposing and voting powers, and delegate them to other addresses.
Staking
Users can stake DYDX to earn staking rewards. This staking program runs for two tokens, USDC and DYDX.
Trading Rewards
Users can view their rewards earned through trading activity on the layer 2 exchange. Trading rewards are distributed every 28 days according to an epoch schedule.
Restrictions
DYDX is not available in the United States or other prohibited jurisdictions. If you are a resident of, or incorporated or headquartered in, the United States of America or another prohibited jurisdiction, then you are not permitted to receive a distribution of, or transact in, DYDX.
DYDX Allocation
A total of 1,000,000,000 DYDX have been minted, and will become accessible over five years, starting on August 3rd, 2021, at 15:00:00 UTC. The initial five-year allocation of the total supply of DYDX is as follows:
50.00% (500,000,000 DYDX) to the community as follows:
25.00% (250,000,000 DYDX) to users who trade on the dYdX Layer 2 Protocol based on fees paid (Trading Rewards). In DIP 16, the dYdX community voted in support of reducing trading rewards by 25%. As a result, trading rewards distributed in a given epoch were reduced from 3,835,616 DYDX to 2,876,712 DYDX in Epoch 15. The remaining 958,904 DYDX will accrue in the Rewards Treasury and can be used by the dYdX community with a governance vote,
7.50% (75,000,000 DYDX) to past users who complete certain trading milestones on the dYdX Layer 2 Protocol (Retroactive Mining Rewards),
7.50% (75,000,000 DYDX) to liquidity providers based on a formula rewarding a combination of uptime, two-sided depth, bid-ask spreads, and the number of markets supported (Liquidity Provider Rewards),
5.00% (50,000,000 DYDX) to a community treasury (Treasury),
2.50% (25,000,000 DYDX) to users staking USDC to a liquidity staking pool (Liquidity Module). In DIP 14, the dYdX community voted to set the rewards associated with staking USDC to 0. The 383,562 DYDX previously distirbuted to USDC stakers will accrue in the Rewards Treasury and can be used by the dYdX community with a governance vote,
2.50% (25,000,000 DYDX) to users staking DYDX to a safety staking pool (Safety Module),
27.73% (277,295,070 DYDX) to past investors,
15.27% (152,704,930 DYDX) to founders, employees, advisors, and consultants of dYdX Trading or the Foundation, and
7.00% (70,000,000 DYDX) to future employees and consultants of dYdX Trading or the dYdX Foundation.
Starting five years after launch, a maximum perpetual inflation rate of 2% per year may be utilized by governance to increase the supply of DYDX, ensuring the community has the resources to continue the development and growth of the Protocol. Inflation must be enacted via a governance proposal and is capped at 2% per year.
Although the community allocation has been established as laid out above, DYDX holders have full control via governance over how the community allocation is used going forwards.
DYDX Lockup Program
DYDX will be issued to stockholders, directors, officers, employees, and consultants of dYdX Trading and the Foundation. All DYDX distributed to these parties will initially be subject to contractual agreements, off-chain, mandating a lockup according to which:
30% of DYDX holdings will unlock after 18 months post-launch;
40% will unlock equally from month 19 through month 24;
20% will unlock equally from month 25 through month 36;
10% will unlock equally from month 37 through month 48.
All employees and consultants also will be subject to various vesting schedules that could result in them losing their rights to DYDX. No employee’s or consultant’s receipt of DYDX is, or will in the future be, based on providing services related to the Protocol or other services that may benefit the Protocol. Instead, employees and consultants may receive DYDX for services that benefit only dYdX Trading, the dYdX Foundation or another party.
Regardless of any lockup on DYDX, investors and prior employees or consultants of dYdX Trading or the Foundation may use DYDX to make proposals, delegate votes, or vote on proposals related to the Protocol. Current employees and consultants of dYdX Trading or the Foundation will initially not make any proposals or participate in any votes but may do so in the future. Current employees and consultants of dYdX Trading or the Foundation may delegate votes without attempting to influence voting outcomes.
All investors are required to comply with the transfer restriction enforced through contractual agreements with the dYdX Foundation. The dYdX Foundation tracks wallet addresses to determine whether any transfers have been made in violation of that restriction.
While investors are technically and legally allowed to stake their DYDX to the Safety Module, in the event of a Shortfall Event and slashing of DYDX, investors would get slashed like every one else. At this time, they would be in default against their obligations. Investors would be required to purchase again any tokens that were transferred as a result of slashing so that everyone is in the same position. For this reason, we ask all investors to refrain from staking and request to withdraw any funds currently staked to the Safety Module.
The dYdX Foundation has expressed its willingness to bring legal action against investors who do not comply with these requirements.
Epochs
All rewards and staking contracts operate on 28 days cycles, referred to as epochs. A new epoch automatically begins when the current epoch ends.
The following will occur at the end of each epoch:
Trading Rewards are distributed. Rewards are claimable at dydx.community approximately 7 days after the end of the epoch.
Liquidity Provider Rewards are distributed. Rewards are claimable at dydx.community approximately 7 days after the end of the epoch.
Requested withdrawals for the Liquidity Staking Pool in the ended epoch may be withdrawn.
Requested withdrawals for the Safety Staking Pool in the ended epoch may be withdrawn.
The initial epoch length is 28 days. dYdX governance can vote to modify epoch lengths, within the specified bounds. The minimum and maximum epoch lengths are 6 days and 92 days, respectively.
Retroactive Mining Rewards, Trading Rewards, and Liquidity Provider Rewards are stored in a Merkle tree, which contains the cumulative rewards earned by each user since the start of the distribution program.
At the end of each epoch, the Merkle root is updated via the ChainLink oracle system on the MerkleDistributorV1
smart contract to reflect rewards earned in the last epoch. An update is performed by setting the proposed Merkle root to the latest value returned by the oracle contract. The proposed Merkle root can be made active after a Waiting Period of 7 days has elapsed. During the waiting period, dYdX governance has the opportunity to freeze the Merkle root, in case the proposed root is incorrect or malicious. If the Merkle root is not frozen, the new Merkle root is activated and users can claim their rewards from the past epoch.
Each time the epoch changes, the following occurs in order: '
When an epoch ends, rewards data is calculated for all user activity from the last epoch.
This data is added to a data structure on IPFS, stored under a fixed IPNS name. The
ChainLink oracle system, also noticing the change in epoch, queries the latest rewards data using the known IPNS name.
Each oracle signer uses this rewards data to calculate newly earned rewards for each user.
Each oracle signer computes the new cumulative Merkle tree and Merkle root.
Each oracle signer writes the Merkle tree data to IPFS, receiving an IPFS CID. (They should have calculated the same tree and should therefore receive the same CID.)
If the oracle signers agree on the same values, then the RewardsOracle is updated with the new Merkle root, IPFS CID, and epoch number.
An oracle signer (or a third party) calls the public function MerkleDistributorV1.proposeRoot()
to set the proposed Merkle root to the new oracle value.
A waiting period takes place, during which governance can call MerkleDistributorV1.pauseRootUpdates()
to prevent the proposed Merkle root from taking effect.
After the waiting period, an oracle signer (or a third party) calls the public function MerkleDistributorV1.updateRoot()
causing the proposed Merkle root to become active.
Once the new Merkle root is active, users are able to claim rewards from the last epoch.
Trading Fees
dYdX Trading Inc. is currently offering DYDX holders trading fee discounts based on their current holdings of DYDX tokens.
You can see fee structure and fee discounts in the images down below. dYdX has made an announcement that every trader can freely trade (no fees charged for trades) if they have trading volume less than $100,000 per month.
Treasury
5.00% of the initial token supply (50,000,000 DYDX) will be distributed to a community treasury to be allocated on an ongoing basis through contributor grants, community initiatives, liquidity mining, and other programs.
Objectives:
Fund programs and initiatives that drive the growth of dYdX.
Develop grant programs to fund community NFTs, hackathons, analytics dashboards, memes, swag, third-party tools, translations, and other projects.
Develop a best-in-class governance system and incentivize robust governance.
The community treasury will retain DYDX to use as DYDX holders decide, whether it be for grants, new liquidity mining pools, or any other program. DYDX will vest to the community treasury on a continuous basis over the course of five years. A governance vote will be required to spend any DYDX from the community treasury.
If, after five years, governance decides to enact perpetual inflation (at a maximum annual inflation of 2%), any newly minted DYDX will be available to the community treasury.
Retroactive Mining Rewards
7.50% of the initial token supply (75,000,000 DYDX) will be distributed to past users of any dYdX protocol who complete certain trading milestones on the Protocol, except for users located in a jurisdiction where DYDX is not permitted, including the United States. To claim earned tokens, users will need to trade on dYdX’s Layer 2 Protocol and achieve their respective claim milestone.
Objectives:
Reward historical dYdX users with a retroactive reward based on past usage.
Incentivize historical dYdX users to trade on dYdX's Layer 2 Protocol.
Trading Rewards
25.00% of the initial token supply (250,000,000 DYDX) was allocated to be distributed to users who trade on the dYdX Layer 2 Protocol based on fees paid. In DIP 16, the dYdX community voted in support of reducing trading rewards by 25%. As a result, trading rewards distributed in a given epoch were reduced from 3,835,616 DYDX to 2,876,712 DYDX in Epoch 15.
Objectives:
Incentivize all traders to use the dYdX Layer 2 Protocol.
Accelerate market liquidity and overall product usage.
Liquidity Provider Rewards
7.5% of the initial token supply (75,000,000 DYDX) will be distributed to liquidity providers based on formulas that reward a combination of maker volume, uptime, two-sided depth, bid-ask spreads, stkDYDX, and the number of markets supported.
Objectives:
Liquidity Module
2.50% of the initial token supply (25,000,000 DYDX) was allocated to be distributed to users staking USDC to the Liquidity Staking Pool. The Liquidity Staking Pool is no longer active as of September 29, 2022. In DIP 14, the dYdX community voted to effectively wind down the Liquidity Staking Pool and the Borrowing Pool by setting the Liquidity Staking Pool rewards per second to 0.
Previously, DYDX was distributed to users who staked USDC to the Liquidity Staking Pool. Community-approved liquidity providers used the staked USDC to make markets on the dYdX Layer 2 Protocol, furthering the liquidity available across the markets. Liquidity providers were restricted from using borrowed funds outside of the dYdX Layer 2 Protocol.
Safety Module
2.50% of the initial token supply (25,000,000 DYDX) will be distributed to users staking DYDX to a Safety pool for backstopping the system.
Objectives:
Bootstrap a decentralized fund to be used in the case of insolvency or other issues with the protocol.
Incentivize DYDX holders to govern correctly: DYDX holders risk dilutive events as the ultimate backstop and act as the governors of risk in the system.
DYDX staked in the Safety Module retains its proposing and voting rights, as well as delegation abilities.
dYdX Protocol is a perpetual future trading platform that is decentralised. This means that unlike centralised exchanges, that you have to deposit your funds to their private accounts and they only give you some numbers (credits) on their platform and they are very vulnerable against hacks, you only need to deposit your fund to an on-chain smart contract that actually handles all the security for the platform. This assures you that your funds are safe while you can easily trade futures indices against your collateral.
DYDX is the governance token of this protocol. People can govern the protocol by proposing their tokens. They are rewarded due to the proportion of tokens they own. And they can even stake their tokens to get rewards and secure the protocol. The token is well allocated and will have a probable small inflation after 5 years from the start point.
Derivatives: Types, Considerations, and Pros and Cons, Investopedia
Crypto derivatives 101: A beginner’s guide on crypto futures, crypto options and perpetual contracts, CoinTelegraph
Layer 2, Ethereum
Sharding, Investopedia
zk-rollups, Ethereum