Overview
dYdX is a decentralized exchange for trading financial derivatives that specializes in trading perpetual contracts on digital assets. Initially powered by StarkEx, dYdX has migrated its matching engine and orderbook to become an appchain in Cosmos.
The platform is renowned for its user-friendly interface, low fees, and the ability to provide up to 20x leverage on positions. These features have positioned dYdX as a leading choice for traders seeking a decentralized alternative to centralized exchanges (CEXs).
Since its inception, dYdX has gone through 4 versions, the latest of them introducing the dYdX chain on Cosmos.
- Version 1: This was the original version of dYdX, which was launched in 2018.
- Version 2: This version of dYdX was launched in 2019 and relied on Ethereum’s mainnet for settlement, which made it slow and expensive.
- Version 3: This version was launched in 2021 and uses StarkWare’s Layer 2 solution, which makes it much faster and cheaper than previous versions.
- Version 4: With V4, dYdX deploys its own blockchain, called dYdX chain, in an effort to scale and further decentralize the platform.
dYdX V3
Unlike the previous 2 versions, the exchange runs on an Ethereum layer 2 instead of Ethereum mainnet. In this version, even though the protocol remains non-custodial and settles trades and liquidations in a trustless manner, dYdX v3 perpetuals use a centralized orderbook. This way, by settling trades on an Ethereum L2, the exchange is able to offer much higher trade throughput and lower minimum order sizes, compared with systems settling trades directly on Ethereum (i.e. L1). This is achieved while maintaining decentralization, and the exchange remaining fully non-custodial. This way, it also becomes much faster to add new markets.
StarkEx
The L2 system for v3 was developed in collaboration with Starkware. WIth this transition to an Ethereum layer 2 the goal was to enhance the performance and scalability of the protocol. StarkEx enables efficient processing and verification of transactions, reducing costs and providing instant finality.
- Transaction Sequencing: StarkEx receives a sequence of transactions from the sequencer, which in this case is dYdX. These transactions represent various actions and operations performed within the application.
- Internal Processing: StarkEx internally processes the transactions to ensure their correctness and validity. It verifies the integrity of the transactions and ensures that they comply with the predefined rules and requirements.
- Cairo Program: The processed transactions are then passed to the Cairo program, which acts as the underlying framework. The Cairo program has the remarkable capability of representing any statement and is Turing Complete, meaning it can execute complex computational tasks.
- Cairo Compilation: The Cairo compiler takes the Cairo program and compiles it into a trace. This trace is a concise representation of the program’s execution flow and data changes.
- STARK Proof Generation: The trace generated from the Cairo program is then transformed into a STARK proof by StarkWare’s prover. The STARK proof provides a cryptographic guarantee of the trace’s validity and integrity.
- On-Chain Verification: The generated STARK proof is sent to the Ethereum blockchain to be verified by a Verifier implemented in Solidity. The Verifier performs the crucial task of verifying the proof’s correctness and legitimacy.
- Scalability and Instant Finality: The key advantage of StarkEx is its ability to significantly reduce the cost and time required for transaction verification. Verifying the STARK proof on-chain is much more efficient and cost-effective compared to executing all the transactions directly on the Ethereum network. Additionally, once the Verifier accepts the proof, it guarantees the instant finality of the transactions, ensuring their legal validity.
StarkEx offers two different modes, namely Validium and ZK-Rollup, each with its own trade-offs in terms of cost, trust, and transparency. Initially, dYdX did not have strong preferences, but after they considered the implications of cost and transparency, the team opted to use a ZK-Rollup solution and keep the data on-chain.
The rationale behind this decision was that the cost of publishing the data on-chain, although higher in terms of gas fees, was manageable for dYdX at the time. They chose to absorb the gas costs and not pass them on to the users, ensuring a seamless trading experience without gas fees.
The transition to a Layer 2 meant that there would be less data available on the Layer 1 blockchain for users to see on a block explorer. On Layer 1, users can see the balances of all users, including synthetic assets and funding indices. This data provides information about the total amount of money in the system when the last batch was accepted. However, the transactions themselves are not published on-chain to save gas and keep trading strategies private.
To ensure the validity of off-chain data, the StarkEx protocol uses the Cairo program as its core. The Cairo program receives the sequence of transactions and adds the balances of the positions that were changed during the batch. This output is linked to a proof, and if the transaction data cannot be shown on-chain, the proof will not be accepted.
Unlike Layer 1 where validators typically select transactions based on the highest gas price, on Layer 2, such as dYdX, they have the responsibility of ordering transactions. This means they act as the “miner” for every block. However, there are protections in place to ensure that users can withdraw their funds and that transactions cannot be censored entirely.
Similar to Layer 1, Layer 2 solutions like dYdX are non-custodial, meaning they cannot steal users’ funds. However, due to the more centralized matching engine in use, in v3 dYdX has the ability to restrict certain traders from accessing the system.
Trading
In this version, accounts may only have up to 20 open orders for a given market/side pair at any one time. (For example up to 20 open BTC-USD bids).
Collateral is held as $USDC, which is also the quote asset for all perpetual markets. Additionally, cross-margin is used by default – an account can open multiple positions that share the same collateral. In order to access isolated margin, the user must create separate accounts (sub-accounts) under the same user.
Each market has 3 risk parameters which determine the maximum available leverage as well as how much value should be held in an account in order to open or increase positions (in the case of initial margin) or avoid liquidation (in the case of maintenance margin):
- Initial margin fraction: The margin fraction needed to open a position.
- Maintenance margin fraction: The margin fraction required to prevent liquidation.
- Incremental initial margin fraction: The increase of the initial margin fraction for each incremental position size above the baseline position size.
Besides, the following parameters are also monitored:
- Baseline position size: The maximum position size (in base token) before increasing the initial margin fraction.
- Incremental position size: The step size (in base token) for increasing the initial margin fraction by the incremental initial margin fraction.
Portfolio Margining
In dYdX v3, there is no distinction between realized and unrealized PnL for the purposes of margin calculations. Gains from one position will offset losses from another position within the same account, regardless of whether the profitable position is closed.
- Initial Margin Requirement = abs(S x P x I)
- Maintenance Margin Requirement = abs(S x P x M)
Where:
- S is the size of the position (positive if long, negative if short)
- P is the oracle price for the market
- I is the initial margin fraction for the market
- M is the maintenance margin fraction for the market
The margin requirement for the account as a whole is the sum of the margin requirement over each market i in which the account holds a position:
The total margin requirement is compared against the total value of the account, which incorporates the quote asset (USDC) balance of the account as well as the value of the positions held by the account:
The account value is also known as equity.
- Q is the account’s $USDC balance (note that Q may be negative). Every time a transfer, deposit or withdrawal occurs for an account, the balance changes. Similarly, the balance also changes when a position is modified for an account. The same occurs with liquidations and funding payments.
- S is the size of the position (positive if long, negative if short)
- P is the oracle price for the market
If the account’s total account value falls below the total initial margin requirement, the account is unable to open new positions or increase the size of existing positions without exceeding the available margin.
Free collateral, which indicates the amount of available funds, can be calculated using the formula:
Free collateral = Total account value – Total initial margin requirement
This way, changes in the account’s value can be monitored using the latest Oracle price obtained from the markets’ websocket.
Liquidations
The liquidation process is intended to protect the integrity of the system and ensure that accounts maintain sufficient margin. By automatically closing positions that fall below the maintenance margin requirement, the platform mitigates the risk of further losses and helps maintain stability in the trading ecosystem.
When the total account value falls below the total maintenance margin requirement, the account may be subject to liquidation. In such cases, the positions within the account are automatically closed by the liquidation engine. The profits or losses resulting from the liquidations are assumed by the insurance fund.
The close price for a position being liquidated is calculated differently depending on whether it is a short or long position:
- For a short position:
- P x (1+(M x V / W))
- For a long position:
- P x (1-(M x V / W))
Where:
- P represents the oracle price for the specific market.
- M represents the maintenance margin fraction for that market, which determines the minimum margin required to keep a position open.
- V represents the total account value, as calculated using the previous explanation (account value).
- W represents the total maintenance margin requirement, which is the sum of the maintenance margin requirements for all positions within the account.
These formulas are designed to ensure that the ratio V / W remains unchanged as individual positions are liquidated.
Funding
Funding payments play a vital role in encouraging the price of a perpetual contract to closely track the price of the underlying asset. These payments are exchanged between long and short traders.
- If the perpetual contract trades at a premium compared to the index price of the underlying asset, long traders typically make payments to short traders.
- If the perpetual contract trades at a discount relative to the index price, short traders generally make payments to long traders.
In v3, funding payments are credited or debited at the start of each hour and are included in the realized profit and loss (PnL) calculation for the position. To obtain information about funding payments, the GET /v3/funding API endpoint can be used, while the predicted funding rate can be retrieved with the GET /v3/markets API endpoint.
The funding rate is typically represented as a 1-hour rate since funding payments occur on an hourly basis. This rate signifies the return or payment an account may expect to receive or pay per hour for a position.
The funding payment at the start of each hour is calculated using the following formula:
F = (-1) x S x P x R
Where:
- S is the size of the position (positive if long, negative if short)
- P is the oracle price for the market
- R is the funding rate (as a 1-hour rate
The funding rate calculation includes a premium component, which considers market activity and is calculated every minute for each market. The premium component is determined based on the difference between the impact bid price (average execution price for a market sell) and the impact ask price (average execution price for a market buy), relative to the index price of the underlying asset.
Premium = (Max(0, Impact bid price – Index price) – Max(0, Index price – Impact ask price)) / Index price
Where the impact bid and impact ask prices are defined as:
Impact bid price = Avg Execution for a market sell of the impact notional value
Impact ask price = Avg Execution for a market buy of the impact notional value
The impact notional amount for a market is:
Impact notional amount = 500 USDC / Initial margin fraction
When calculating the funding rate, the premium component is adjusted to have a realization period of 8 hours. For example, if a perpetual market consistently trades at a 0.1% premium relative to the underlying asset, long traders can anticipate paying approximately 0.1% every 8 hours, while short traders may expect to earn a 0.1% return every 8 hours (excluding the interest rate component).
For example, for a market with a 10% initial margin fraction, the impact notional amount is 5,000 USDC.
At the end of each hour, the premium component is determined as the simple average (time-weighted average price – TWAP) of the 60 premiums calculated during the previous hour. Additionally, each market has a fixed interest rate component that accounts for the difference in interest rates between the base and quote currencies. The funding rate is then calculated as follows:
Funding rate = (Premium component / 8) + Interest rate component
Currently, the interest rate component for all dYdX v3 markets is 0.00125% (equivalent to 0.01% per 8 hours).
Contract Loss Mechanisms
To ensure the solvency and stability of the system, contract loss mechanisms are in place to address situations where the value of accounts holding perpetual contracts drops below zero due to high volatility in the underlying markets.
- Insurance Fund: The insurance fund serves as the first line of defense to maintain the system’s solvency when an account’s balance becomes negative. When an account with a negative balance is liquidated, the loss is absorbed by the insurance fund. The fund is designed to cover such losses and acts as a financial buffer to protect the overall integrity of the platform.
- Offsetting Positions: If the insurance fund becomes depleted or insufficient to cover all the losses, positions with the highest profitability and leverage may be utilized to offset the negative balances of accounts. By using these positions strategically, the aim is to mitigate the impact of negative balances and maintain the stability of the system.
Oracles
Oracles ensure collateralization and determine liquidation thresholds.
The oracle price for each trading pair is determined based on the median of the reported prices from 15 independent Chainlink nodes.
The 15 independent Chainlink nodes responsible for reporting the prices include providers such as Chainlayer, Inotel, LinkForest, SimplyVC, DexTrac, Fiews, dMakers, linkPool, SDL, Ztake, stakFacils, infStones, 01node, Syncnode, and Vulcan. These nodes contribute to the determination of the Oracle price by reporting their respective price data.
- Account Collateralization: Oracle prices are crucial in ensuring that each account remains adequately collateralized after each trade. By using the Oracle price, the platform can assess the value of assets held by an account and determine if it meets the required collateralization ratio. If the account’s collateral falls below the specified threshold based on the Oracle price, it may be subject to liquidation.
- Liquidation Threshold: Oracle prices are also used to determine when an account should be liquidated. If the value of an account’s position falls below a certain level relative to the oracle price, it triggers the liquidation process. This mechanism helps maintain the solvency and stability of the platform by preventing accounts from incurring excessive losses.
By relying on the median of prices reported by independent Chainlink nodes, the platform obtains a reliable and decentralized price feed that is used to assess collateralization levels and trigger necessary actions such as liquidation. The use of multiple independent nodes enhances the accuracy and integrity of the oracle prices, reducing the potential for manipulation or single-point failures in price reporting.
Index Prices
The index price for each asset is used to calculate the funding rate and trigger orders, such as stop-limit and take-profit orders.
Index prices are equal to the median of several exchanges’ spot prices, where each exchange’s spot price is calculated as the median of the best-ask, best-bid, and last-traded prices of its spot pair.
V3 API
dYdX V4
dYdXv4, also known as dYdX Chain, was fully released on October 24, 2023, and represents significant enhancements and a new architecture.
Unlike the v3, which relies on smart contracts deployed on existing chains with centralized cloud services, v4 is a standalone Layer 1 (L1) blockchain. This upgrade aims to scale and enhance decentralization using the CometBFT consensus and Cosmos SDK. Cosmos not only makes it easy to create a standalone blockchain but also offers strong cross-chain capabilities, high throughput, decentralization, and customizability. Additionally, each Cosmos chain has its own validators and layer 1 staking token.
The fundamental problem with most L1s and L2s is that they cannot handle the throughput needed to run a first-class orderbook and matching engine. To solve those problems, the core feature of v4 is the implementation of a fully decentralized, off-chain orderbook, and matching engine. This means that the orderbook and trade execution will be processed off-chain, offering improved scalability and efficiency.
While dYdX explored other trading models such as an AMM or RFQ system, the decision was made to go with an orderbook and matching engine. This is critical to offer the trading experience that pro users and institutions demand. In dYdX, each validator will run an in-memory orderbook that is never committed to consensus (i.e. off-chain). This way, orders placed and cancellations will be propagated through the network similar to normal blockchain transactions, ensuring that orders placed and cancellations will always make their way through the network. Furthermore, the orderbook that each validator stores is eventually consistent with one another. On a real-time basis, orders will be matched together by the network. The resulting trades are then committed on-chain each block. This is the key point that makes it possible for dYdX to offer high throughput for the orderbook while remaining decentralized.
Another notable feature is that there are no trading gas fees. The customizability of the Cosmos SDK makes it possible to develop these characteristics to suit the exact needs of the network. As a result, traders don’t pay gas fees to trade, but rather only pay fees based on the trades they execute, similar to dYdX v3 and centralized exchanges. These fees accrue value to validators and their stakers.
At the technical level, the dYdX Chain is built on the Cosmos SDK, which provides a framework for developing scalable and interoperable blockchains. The node software is written in Go and compiles into a single binary. To ensure consensus and network security, v4 utilizes the CometBFT Proof-of-Stake (PoS) consensus protocol. PoS consensus allows validators to participate in block production and secure the network based on the number of tokens they hold and “stake” as collateral.
Note that at the launch of dYdX v4, all previous versions were deprecated.
System Architecture
dYdX v4 is designed to be a completely decentralized end-to-end. The main components broadly include the protocol, the Indexer, and the front end. Each of these components will be made available as open-source software and none of the components will be run by dYdX Trading Inc.
Validators
The protocol operates as a network of nodes, and there are two types of nodes:
- Validators: Validators play a crucial role in the consensus and block production process. They are responsible for storing orders in an in-memory orderbook, gossiping transactions to other validators, and proposing new blocks for the dYdX chain.
- Full nodes: Full Nodes are nodes that run the v4 application but do not participate in the consensus process. They have a stake weight of 0 and do not propose or vote on blocks. However, full nodes are connected to the network of validators and participate in the gossiping of transactions. They also process each new committed block in the blockchain.
Validators take turns as proposers of new blocks in a weighted round-robin fashion, with the weight determined by the number of tokens staked to their node. When an order is matched, the proposer includes it in their proposed block and initiates a consensus round. If two-thirds or more of the validators (by stake weight) approve the block, it is considered committed and added to the blockchain. Users submit transactions directly to validators, who process and validate them.
Full nodes maintain a complete view of the dYdX Chain and its history. They are primarily intended to support the Indexer, a component that helps in querying and indexing blockchain data. For instance, some entities may choose to run their own full node and/or Indexer for performance or cost reasons.
Validator Requirements
The minimum recommended specs for running a node are:
- 8-core, x86_64 architecture processor
- 64 GiB RAM
- 500 GiB of locally attached SSD storage
An example of this would be an AWS instance like the r6id.2xlarge, or equivalent.
Validator Setup Guide
- Setting up Cosmovisor (a thin wrapper around Cosmos applications)
- Preparing for Genesis
- Starting the network
- Running a full node
- Types of upgrades
- Performing upgrades
- Network snapshots
- Voting for upgrade proposals
Indexer
The Indexer serves as a read-only collection of services. Its main purpose is to index and efficiently serve blockchain data to users in a more accessible and user-friendly manner.
To accomplish this, the Indexer consumes real-time data from a v4 full node, and then stores this data in a database, typically using Postgres, and makes it available for retrieval and querying.
By indexing the blockchain data in a separate database, the Indexer can optimize the storage and retrieval processes, enabling faster and more efficient access to the data. It also provides a range of services such as websockets and REST APIs to serve this indexed data to end-users.
One advantage of the Indexer is that it allows for a more web2-friendly experience, meaning it provides data in a format that is compatible and easily consumable by traditional web applications. It helps overcome the limitations of directly querying the v4 protocol endpoints, which can be slower and less efficient due to the primary focus of validators and full nodes on consensus and block production.
The Indexer utilizes various technologies to handle the data efficiently:
- Postgres databases for storing on-chain data.
- Redis for off-chain data storage.
- Kafka for consuming and streaming on/off-chain data to the different Indexer services.
These technologies work together to ensure the availability, scalability, and responsiveness of the Indexer’s data retrieval and serving capabilities.
On-chain and Off-chain Data
By distinguishing between on-chain and off-chain data and handling them separately, the protocol allows different services to scale according to the specific throughput requirements of each data type. On-chain data is crucial for maintaining the integrity and transparency of the blockchain, while off-chain data provides real-time and ephemeral information for efficient order book management and processing.
- On-chain data refers to the data that is stored and recorded on the dYdX Chain through committed transactions. This data is validated and agreed upon by the consensus process. It includes essential information such as account balances (USDC), account positions (open interest), order fills, trades, liquidations, deleveraging events, partially and completely filled orders, funding rate payments, trade fees, historical oracle prices (spot prices used for funding and liquidations), and long-term order placement and cancellation records.
- Off-chain data refers to the data that is kept in-memory on each v4 node but is not written to the blockchain or stored in the application state. This data does not persist and is considered ephemeral, meaning it is lost upon node restarts or the purging of in-memory data stores. Off-chain data includes short-term order placement and cancellations, the order book of each perpetual exchange pair, and indexed order updates before they are recorded on the chain. This data is not directly accessible through the gRPC API on v4 nodes, and it cannot be derived from the data stored in blocks.
Indexer Services
The Indexer comprises several services that work together to ingest and serve data from v4 Full Nodes. These services facilitate the efficient storage and retrieval of blockchain information.
- Ender (On-chain ingestion): Ender is responsible for ingesting on-chain data. It consumes data from the “to-ender” Kafka topic, which contains all on-chain events grouped by block. Ender processes the state changes from each block and stores them in a Postgres database, capturing all on-chain data. It also emits websocket events via the “to-websocket-?” Kafka topic for relevant events.
- Vulcan (Off-chain ingestion): Vulcan handles the ingestion of off-chain data. It consumes data from the “to-vulcan” Kafka topic, which contains payloads with updates related to the active order book, order placement, order cancellation, and optimistic fills. Vulcan stores this data in a Redis cache. It updates Redis with new open orders, sets canceled orders to a “cancel pending” status, and adjusts the order books based on the received payload. It also updates the Postgres database when a partially filled order is canceled. Vulcan emits websocket events through the “to-websocket-?” Kafka topic as needed.
- Comlink (API Server): Comlink serves as the API server for the Indexer. It exposes REST API endpoints that allow users to access both on-chain and off-chain data. Users can make requests for specific information, such as USDC balances or position sizes, and receive formatted JSON responses from Comlink. The API endpoints are designed to align closely with the v3 exchange APIs, ensuring familiarity for dYdX users.
- Roundtable: Roundtable is a job service that performs various exchange aggregation computations periodically. It calculates metrics such as 24-hour volume per market, open interest, profit and loss (PnL) by account, and candlestick data. These computations provide important aggregated information for analysis and reporting purposes.
- Socks (Websocket service): Socks facilitates real-time communication between clients and the Indexer through websockets. It consumes data from Ender, Vulcan, and Roundtable and sends websocket messages to connected clients. This allows clients to receive live updates and stay in sync with the latest information from the Indexer.
Infrastructure Requirements
Hosting and deploying the Indexer requires certain infrastructure and personnel to ensure its availability and maintenance.
- AWS: The Indexer is typically deployed on Amazon Web Services (AWS) cloud infrastructure.
- ECS – Fargate: AWS Elastic Container Service (ECS) with Fargate is used to deploy and manage containers for running the Indexer services.
- RDS – Postgres Database: Amazon RDS is utilized for hosting the Postgres database that stores the on-chain data.
- EC2: Elastic Compute Cloud (EC2) instances may be used for specific purposes within the infrastructure.
- Lambda: AWS Lambda functions can be leveraged for specific tasks within the Indexer.
- ElastiCache Redis: Amazon ElastiCache is employed for hosting the Redis cache used by the Indexer.
- EC2 ELB – Loadbalancer: Elastic Load Balancer (ELB) can be used to distribute traffic to the deployed Indexer services.
- Cloudwatch – Logs: AWS CloudWatch is utilized for log management and monitoring.
- Secret Manager: AWS Secrets Manager is employed for securely managing credentials and secrets used by the Indexer.
- Terraform Cloud: Terraform Cloud provides the infrastructure-as-code (IaC) capability for deploying the Indexer to the cloud.
- Bugsnag: Bugsnag is a tool used for bug awareness and real-time alerting of issues that require human intervention.
- Datadog: Datadog is used for metrics and monitoring of the Indexer services.
- Pagerduty: PagerDuty can be employed for alerting and incident management.
In addition to that, there are the following personnel requirements:
- At a minimum, a DevOps engineer is required to handle the deployment and ongoing maintenance of the Indexer. They will be responsible for setting up the AWS infrastructure, deploying the Indexer code, monitoring metrics and alerts, and addressing any issues that may arise.
This comes with the following deployment and maintenance responsibilities:
- Initial Deployment: The operator needs to set up the AWS infrastructure and deploy the Indexer code to ingest data from the full node and expose it through APIs and websockets. Tools like Terraform Cloud can be used for streamlined deployment.
- Ongoing Maintenance: The operator is responsible for managing the Indexer’s infrastructure, including migrating or upgrading the Indexer for new releases, monitoring Bugsnag and Datadog for any issues, and addressing them according to the run book provided by dYdX.
To meet these requirements, the operator should have accounts for the mentioned AWS services and hire appropriate personnel, such as a DevOps engineer, to handle the deployment and maintenance responsibilities. This ensures that the open-sourced Indexer can be hosted in a highly available manner, with consistent uptime for public access.
Front-Ends
The web front end provides an intuitive and performant UI/UX for traders who do not wish to interact with v4 programmatically. The web front-end application will interact with the Indexer via APIs/websockets to fetch and display both on-chain and off-chain information (e.g., orderbook, account balances, etc.). Orders will be placed directly to validators.
dYdX has developed three open-source front-ends to provide users with a decentralized experience: a web application, an iOS app, and an Android app.
- Web Application: The web app is built using Javascript and React, popular technologies for web development. It will interact with the Indexer, which serves as a centralized data source, through an API. The web app will retrieve off-chain orderbook information from the Indexer to display to users. When users execute trades, the web app will send the transaction directly to the dYdX chain. Anyone can access and deploy the web app to their own domain or hosting solution using IPFS (InterPlanetary File System) or a Cloudflare gateway.
- Mobile Applications: dYdX is also developing native mobile apps for iOS and Android platforms. The iOS app will be built using Swift, while the Android app will be developed in Kotlin. Similar to the web application, the mobile apps will interact with the Indexer to retrieve off-chain orderbook information and facilitate trade execution directly on the dYdX chain. Both the iOS and Android apps will be open-sourced, enabling anyone to deploy them to the App Store or Play Store. For iOS app deployment, the deployer will need a developer account and a Bitrise account to complete the app submission process.
By open-sourcing the front-end codebases and providing deployment scripts, dYdX aims to promote transparency, community involvement, and accessibility. Users and developers will have the ability to examine, modify, and deploy the front-end applications according to their own needs. This approach aligns with the decentralized nature of dYdX and empowers individuals to access and use the platform through a variety of interfaces.
Web Frontend Deployments
To deploy a web front end for dYdX, one should follow these steps:
- Codebase: Access the open-source GitHub repository for the web front-end codebase. The web app is written in Typescript using React.
- Deployment Script: Clone the codebase from the GitHub repository and utilize the provided deployment script. This script will handle the deployment process.
- IPFS: The deployment script will send and pin the files to IPFS (InterPlanetary File System) using a pinning service like web3.storage. IPFS is a peer-to-peer file-sharing protocol for distributed file storage.
- Retrieve IPFS Hash: Once the files are pinned to IPFS, retrieve the IPFS hash, which represents the unique identifier for the deployed content.
- Cloudflare: Update the DNS record of the web domain to point to the latest IPFS hash. This ensures that the domain resolves to the correct IPFS content. Cloudflare is used as an IPFS gateway and for DNS resolution.
- Accessibility: The content stored on IPFS can be accessed using the IPFS hash through any browser with native IPFS support or via public IPFS gateways like https://dweb.link or https://w3s.link.
The deployment script is designed to simplify the hosting and updating process for the front end. As a deployer, your responsibilities include:
- Acquiring and owning a web domain.
- Meeting deployment prerequisites, such as installing Node.js 16 and npm locally, setting up a web3.storage account, and setting up a Cloudflare account.
- Initial deployment of the front end by downloading the codebase and running the deployment script. This will pin the files to IPFS and update the IPFS hash.
- Updating the front end by monitoring the dYdX GitHub repository for codebase updates and running the deployment script to pin the updated files to IPFS and update the IPFS hash.
- Setup of ancillary accounts as required for the deployment process.
By following these steps, you can deploy and maintain a web front end for dYdX, allowing users to access the trading experience through your own domain.
Lifecycle of an Order
- User Places a Trade: The user initiates a trade by interacting with a decentralized front-end, such as the dYdX website or an API.
- Order Routing: The order is sent to a validator. This validator then propagates the transaction to other validators and full nodes to update their orderbooks with the new order. This ensures that all network participants have access to the latest order information.
- Consensus Process: The consensus process, which involves validators taking turns as proposers of new blocks, selects a validator to match the order and include it in their proposed block. The proposer adds the order to their proposed block and prepares it for the consensus round.
- Consensus Confirmation: The proposed block goes through the consensus process, where validators vote on whether to confirm or reject the block. If at least two-thirds (⅔) of the validators (by stake weight) approve the block, it is considered committed and saved to the on-chain databases of all validators and full nodes.
- Block Rejection: If the proposed block fails to receive the necessary approval threshold, it is rejected, and the order will not be included in the blockchain.
- Data Synchronization: After a block is committed, the updated on-chain and off-chain data are streamed from full nodes to Indexers. Indexers, which are read-only services, collect and store this data in databases.
- Data Availability: The Indexer makes the synchronized data available through APIs and Websockets. This allows the front-end application and other external services to query and retrieve the orderbook and other relevant information.
MEV
MEV (Miner or Maximal Extractable Value) refers to the profits that validators or miners can earn by reordering or censoring transactions to their advantage. In dYdX v4, the fully decentralized and performant in-memory orderbook used by the dYdX chain could potentially enable MEV extraction. To address this, dYdX is proactively working on researching and building MEV solutions that align the incentives of validators with the interests of users.
The Ethereum ecosystem generally takes a neutral approach toward MEV, with a Proposer-Builder Separation (PBS) approach used to auction off block space. PBS helps mitigate the centralization risks associated with MEV but still negatively impacts average users. In contrast, the Cosmos ecosystem, including Osmosis, takes a more opinionated stance towards MEV. It aims to mitigate harmful MEV and capture any benign MEV generated.
While dYdX v4’s design enhances performance, it introduces complexities like validator-driven MEV. Validators can manipulate transaction order and inclusion within a block, potentially benefiting themselves unfairly at the expense of others.
However, dYdX prioritizes user experience and has chosen the Cosmos infrastructure to create a fully decentralized exchange with high performance. This infrastructure enables the integration of unique MEV solutions into the dYdX v4 chain. By building MEV mitigations directly into the protocol code, dYdX aligns the incentives of validators and users on-chain. This way, unlike general-purpose smart contract environments, where validators are neutral towards the needs of application users, dYdX’s approach prevents validators from profiting at the expense of users. dYdX is working closely with MEV experts such as Skip Protocol and ChorusOne to develop MEV mitigation strategies for the dYdX v4 chain.
Exploring the Different Forms of MEV
The design of dYdX v4 introduces opportunities for MEV extraction through various methods beyond traditional forms like arbitrage, liquidation, and sandwich attacks.
To assess MEV on dYdX v4, research by Chorus One suggests using an estimator that quantifies the financial gain captured by the block proposer through privileged actions, such as manipulating the order book.
The MEV of a proposed block is calculated as the sum of absolute differences in profit and loss (PNL) at the subaccount level based on matched orders. This estimator measures how much the block proposer’s actions shift PNL values from other validators’ views.
Where PNLi^BP is the PNL based on the block proposer’s matched trades for subaccount i and PNLi^V is the PNL based on the block validator’s matched trades for subaccount i.
The MEV Estimator has two properties:
- It captures the profit captured by the block proposer through any action that leverages their privileged position.
- It measures any order book manipulation done by the block proposer, regardless of whether values are shifted between subaccounts.
Some examples of MEV extraction are:
- Capturing the Spread: The block proposer manipulates the order book to capture the spread by ignoring existing orders and transferring profit from other participants to themselves.
- Stale Order Snipe: The block proposer ignores a cancel order received during the intrablock time, leading to profit extraction from participants affected by the canceled order.
- Capturing the Slippage (Sandwiching Market Orders): The block proposer uses their privileged position to submit matched orders that capture slippage between different market orders, resulting in profit extraction.
- Stop Limit Order Cascade: The block proposer triggers a cascade of stop limit orders by exploiting knowledge of both the order book and pending stop limit orders, leading to price movement that benefits their interests.
Capturing The Spread
Suppose the order book on dYdX v4 looks like this:
- A: Sell 100 at $101
- B: Buy 100 at $99
During the intrablock period, the sub-account C submits the following order:
- C: Sell 100 at $101
The block proposer, who knows that the block will end with a mid-price of $100, chooses to insert a sell order for their own sub-account X during the block proposal stage, ignoring the existing sell order from A. The result is that the block proposer captures the spread profit from the existing orders. The validator’s view of matched orders after these actions could be:
The MEV extracted by the block proposer is calculated using the estimator formula:
MEV = 1/2 * (|0 – 100| + |0 – 0| + |-100 – -100| + |100 – 0|) = 100
Stale Order Snipe
Imagine the order book on dYdX v4 initially as follows:
- A: Sell 100 at $106
- B: Sell 100 at $102
- C: Buy 100 at $100
- D: Buy 100 at $96
During the intrablock period, the sub-account B submits a cancel order to cancel their sell order at $102, and the sub-account E submits a buy order at $104.
The block proposer, who anticipates a mid-price of $105 at the end of the block, ignores the cancel order from B and the buy order from E, executing only their own matched orders. This action transfers profit from the canceled order to their sub-account X. The PNL calculations for both the validator and block proposer could look like:
Using the MEV estimator, the block proposer captures MEV of:
MEV = 1/2 * (|0 – 0| + |-300 – 0| + |0 – 0| + |900 – 0| + |0 – 300|) = 400
Capturing The Slippage
Consider an order book on dYdX v4 with the following orders:
- A: Sell 100 at $106
- B: Sell 100 at $102
- C: Buy 100 at $100
During the intrablock period, the sub-account E submits a market sell order, aiming to fill at the market price.
The block proposer, aware that the block will end with a mid-price of $99, submits their own matched orders that capture the slippage between different market orders, resulting in profit extraction. The matched orders for both the validator and block proposer could be:
Using the MEV estimator, the block proposer captures MEV of:
MEV = 1/2 * (|0 – 300| + |100 – 0| + |0 – 0| + |-200 – 0| + |-300 – 0|) = 300
Stop Limit Order Cascade
Suppose the order book on dYdX v4 looks like this:
- A: Sell 100 at $120
- B: Buy 100 at $118
- C: Buy 100 at $110
- D: Buy 100 at $105
- E: Buy 100 at $101
Additionally, there are pending stop limit orders:
- F: if pmid ≤ $115 → Sell 100 at $110
- G: if pmid ≤ $112 → Sell 100 at $105
The block proposer, with the knowledge that the block will end with a mid-price of $110, submits matched orders to trigger a cascade of stop-limit orders by exploiting the price movement. This results in profit extraction by moving the price to their advantage. The matched orders for both the validator and block proposer could be:
Using the MEV estimator, the block proposer captures MEV of:
MEV = 1/2 * (|-800 – 0| + |500 – 0| + |800 – 0| + |-500 – 0|) = 1300
Challenges in MEV Estimation
There are challenges related to the MEV estimation suggested by research from Chorus One, which could introduce some bias in the implementation of the estimator. One situation could involve a misbehaving block proposer and differing mempool views on different validators. In this scenario, each validator has a unique view of the mempool due to receiving different transactions based on the network topology. Specifically, the case involves ignored orders coming from the intra-block period.
- Impact of Mismatched Views: If the cancel order is not seen by the block proposer in time, the estimator’s calculation could still point to a transfer of value between different sub-accounts. In this case, the transfer is due to a mismatch of views, not the block proposer’s manipulation.
- Addressing Bias with Statistical Analysis: To mitigate the risk of biased estimations due to mismatched views, the document by Chorus One suggests using statistical analysis. By analyzing consistent patterns of misbehavior and differentiating them from normal variations, it’s possible to obtain more accurate estimations.
- Deviation and Confidence Interval: The document proposes calculating the deviation of inserted orders in the block proposer’s view and comparing it to the expected network jitter. This helps compute a confidence interval that indicates the likelihood of a specific view of matched orders being observed.
- Distribution and Monte Carlo Simulations: To account for the impact of network topology and variability in transaction arrival times, the document suggests assuming a specific distribution for order placement and cancellation times (D(m, s)). Monte Carlo simulations can then be used to analyze the resulting profit and loss (PNL) distribution for sub-accounts.
- Unobserved Orders: It’s important to acknowledge that there’s a small likelihood that certain orders may never reach a validator due to network dynamics. This adds to the complexity of the system’s behavior.
- Quantifying Confidence and Probability: By leveraging the expected distribution and conducting simulations, it’s possible to associate a confidence interval with observed deviations in PNL for sub-accounts. This provides insights into the probability of MEV extraction occurring in the presence of a non-zero MEV condition.
dYdX Within The Cosmos MEV Ecosystem
The presence of dYdX could affect the overall MEV structure within the Cosmos ecosystem. To analyze that impact, one must account for different factors, such as:
- Profitability of Cross-Chain MEV: If there are enough opportunities for atomic cross-chain MEV within the Cosmos ecosystem to incentivize validators to adjust their operations for profit. This adjustment would involve inserting transactions ahead of others on a minimum of two chains.
- Hidden Incentives and Order Book Manipulation: The introduction of dYdX v4 could create hidden incentives for validators to manipulate the order book, leading to profit generation exceeding on-chain metrics. This manipulation might be triggered by cross-chain MEV opportunities.
- Insufficient Incentives: The current potential for cross-chain value extraction isn’t sufficient to incentivize validators to maintain custom validation clients on only two chains. This is based on research by Chorus One using Osmosis as a proxy for ecosystem MEV volume.
- Probability of MEV Extraction: The likelihood of a validator being selected as a block proposer on both chains simultaneously, along with overlapping blocks and a profitable MEV opportunity, is low. The probabilities are analyzed using a binomial distribution and are shown through cumulative probability distributions.
- Validator-Driven Arbitrage: Validators with the ability to modify their clients can leverage their position to execute profitable transactions in desired orders on both chains in an atomic manner. However, the chances of success are not high enough to entice validators to pursue this complex strategy.
- Block Proposal Selection: The selection of a validator as a block proposer on both chains is influenced by factors like voting power distribution, block times, and overlap conditions. The document uses these factors to calculate the probability of MEV extraction.
- MEV Revenue Distribution: Taking Osmosis as an example, the distribution of MEV revenue suggests that the rewards are lower than a few cents, with the median MEV revenue per block being zero.
- Probability of Profitable MEV Extraction: By considering the probability of three independent events happening simultaneously, research by Chorus One computes the probability distribution of revenue from cross-chain MEV extraction. It concludes that the revenue would likely be less than $1 per week with a high probability.
Impact of Cross-Venue MEV On User Welfare
During specific market conditions, validators proposing a block might be incentivized to create arbitrage opportunities between AMMs and dYdX v4, potentially impacting the users of the AMM.
We can look at two different scenarios: one where dYdX has liquidity supremacy and another where it doesn’t.
- When dYdX has liquidity supremacy (or pricing power), users may not experience direct impacts, but market makers might adjust their behavior to avoid losses on spread appreciation, leading to lower liquidity in certain ranges.
- When dYdX does not have liquidity supremacy, users may experience increased slippage due to order depletion from arbitrages, leading to a less favorable trading experience.
Additionally, pricing on dYdX v4 could be influenced by the presence of another Central Limit Order Book (CLOB) with higher liquidity for a given asset.
Impact of Validator-Driven MEV
There is the possibility that market makers and trading firms reach partnership agreements with validators to engage in MEV strategies. Due to the existing moats of both parties, a partnership is the most probable way validator-driven MEV would manifest.
There is a broad range of conditions that can be explored for each individual partnership, but fixed fee arrangements might be more likely due to their stability and compatibility with market-making operations.
One way to mitigate validator-driven MEV is to introduce a slashing penalty that reduces a validator’s staked capital. This is often a significant deterrent for validators engaging in potentially harmful MEV activities. Even if a partnership with a trading firm were to generate revenue, the risk-adjusted benefit would likely favor the validator, making it an unfavorable proposition for delegators. Additionally, publicizing the risk carried by delegators and offering a way to re-delegate to good actors could serve as an effective approach to mitigating validator-driven MEV.
Overall, it is increasingly important to detect misbehaving validators through order book execution comparisons and outlining penalties for non-accidental infractions. For instance, the development of a dashboard in collaboration with Skip Protocol could help to measure MEV events.
dYdX V5
The dYdX Chain v5.0 software update introduces several significant upgrades that enhance both functionality and user experience on the platform. These ongoing updates include:
Isolated Markets & Isolated Margin
- Isolated Markets: These are new market types that have their own segregated collateral pools and insurance funds, which means each market operates independently in terms of risk. This isolation allows dYdX to support a broader range of markets with different risk profiles, enhancing the protocol’s flexibility.
- Isolated Margin: With isolated margin, traders can manage their collateral separately for each position. This is different from cross-margining, where all positions share the same collateral pool. Isolated margin helps traders better control and predict their collateral requirements, making risk management more intuitive.
LP Vaults
- LP Vaults: These vaults allow users to deposit $USDC into automated liquidity strategies. The deposited $USDC is pooled and used to provide liquidity across different markets. This feature is especially beneficial for newer markets with limited liquidity. LP Vaults aim to maintain neutral market positions and offer competitive yields to depositors.
- Phased Rollout: The LP Vaults will be introduced in phases, starting with a basic version that supports deposits. Withdrawals and additional features like updated quoting strategies will be added in later updates.
Slinky Sidecar & Raydium Integrations
- Slinky Sidecar: This integration with Skip Protocol enhances the stability and speed of oracle price updates by removing them from the consensus process. It enables lower latency and more reliable price feeds.
- Raydium Integration: This integration allows dYdX to directly query prices from Raydium, a decentralized exchange on Solana. This will expand the range of available markets on the platform, allowing users to trade more assets.
Some other updates in v5.0 include:
- Batch Order cancellations which allows for users to cancel up to 100 short term orders at a time.
- General performance improvements, including parallelizing signature verification.
- Soft open interest cap which scales up the Initial Margin Fraction (IMF) after Open Interest (OI) exceeds a configurable cap.
- Full node streaming which allows the full node to stream data directly to subscribers via GRPC.
Why the Project was Created
dYdX was launched in 2017 by Antonio Juliano, a former engineer at Coinbase, and has since gained significant traction within the DeFi space. The protocol aims to address the limitations of traditional financial systems by providing a decentralized alternative that offers transparency, security, and accessibility.
In 2018, dYdX launched Expo, a simple trading app that allowed users to buy leveraged tokens. This app was built on the initial version of the margin protocol. The team continued to refine their protocols, and in 2019, they released a more advanced exchange product targeting experienced traders. This version, known as V2, introduced a powerful pool-based lending approach and implemented an order book system to enhance the trading experience.
A significant milestone for dYdX occurred in 2020 when it became the first decentralized exchange to offer perpetual contracts. In April 2020, the Bitcoin perpetual contract was launched, positioning dYdX as a pioneer in decentralized perpetual trading and solidifying its reputation as a product leader.
In 2021, when Ethereum gas fees soared, dYdX recognized the need for changes to their product. As a response, they transitioned to the layer 2 Starkware platform – StarkEx. This shift significantly improved throughput, introduced cross-margining, expanded trading markets, and increased liquidity. The most important reason for moving to a layer 2 was the order execution speed and associated costs. Another problem was the speed of getting oracle prices on-chain. When the price changes dramatically and gas costs increase, the oracle prices settle on-chain at a much slower pace, which also creates additional risk for users.
During the same year, dYdX took further steps towards decentralization by launching the $DYDX token. The token grants governance rights on the dYdX protocol, empowering the community to take ownership of protocol parameters and participate in community-led initiatives. The launch of the $DYDX token demonstrated dYdX’s commitment to decentralization and community involvement.
Moving forward, dYdX aims to achieve full decentralization by migrating the order book and matching engine to its standalone blockchain based on Cosmos in the V4 upgrade. By using the Cosmos SDK and Tendermint consensus, the goal is to ensure that the system remains as decentralized as possible.
The decentralization of a system is determined by its least decentralized component. Existing Layer 1 or Layer 2 blockchains cannot handle the required throughput for running a first-class orderbook and matching engine. dYdX v4 aims to process orders of magnitude more trades and order placements/cancellations per second.
In addition to that, Cosmos provides a high degree of customizability, allowing dYdX to design the blockchain to suit its specific needs. Validators in dYdX v4 will run in-memory orderbooks that are not committed to consensus. Orders and cancellations will be propagated through the network like blockchain transactions, ensuring their availability. Real-time matching of orders will take place off-chain, and the resulting trades will be committed on-chain. This approach allows for high throughput and decentralization.
Sector Outlook
While CEXs and DEXs serve similar purposes of facilitating the exchange of digital assets, they differ significantly in their underlying principles, control structures, security models, and user experience. DEXs, including dYdX, aim to provide users with self-custody, transparency, and greater control over their assets, aligning with the core principles of decentralization in the cryptocurrency ecosystem.
dYdX belongs to the decentralized finance (DeFi) sector, more specifically dedicated to financial derivatives. DEXs operate through smart contracts, eliminating the need for a centralized party. This offers advantages such as greater control over capital, streamlined onboarding, and direct peer-to-peer trading. However, they may be complicated for first-time users and typically have smaller trading volumes and less liquidity. DEXs also lack fiat on-and-off ramps, requiring users to obtain cryptocurrency elsewhere before trading. Smart contract risks exist, necessitating careful platform selection.
Why Decentralization Matters
- Transparency: Decentralization brings transparency to the financial system. With decentralized platforms like dYdX, users have visibility into the operations and code that govern the platform. This transparency fosters trust as users can verify and validate the platform’s integrity.
- Trustless Environment: Decentralized platforms like dYdX rely on smart contracts and blockchain technology, enabling users to trust the code and protocols instead of relying on centralized entities. This reduces the need to place trust in corporations or intermediaries, as the system’s rules and operations are governed by algorithms and consensus mechanisms.
- Control and Fairness: Decentralization empowers users with true control over their financial activities. In the case of dYdX, users have control over their assets, trades, and governance decisions. This leads to increased fairness, as decision-making is distributed among the community and aligns with the collective interests of the platform’s users. It also promotes equality of opportunity, ensuring that all participants have a level playing field.
- Community Alignment: Decentralization allows for community ownership and participation. With the launch of dYdX governance and the transition to full community control in dYdX V4, the platform’s future lies in the hands of its users. This ensures that decisions are made in the best interest of the community, fostering alignment, and a sense of ownership among users.
- Long-Term Vision: Decentralization is seen as the future of finance. As the financial landscape evolves, decentralized networks and protocols are expected to play a significant role. By embracing decentralization, platforms like dYdX position themselves as leaders in the transition to a decentralized financial ecosystem.
Competitive Landscape
When compared to other derivatives, dYdX has consistently ranked among the top protocols both in TVL and trading volume. The exchange is positioned to become a decentralized replacement for centralized exchanges. As a matter of fact, many firms hedge their exposure to centralized custodians by trading on-chain with dYdX. This saved many platforms during the collapse of FTX since they were able to keep custody of their own funds when trading on dYdX.
Market makers note that dYdX can often offer more liquidity for instantaneous trades compared to centralized exchanges, let alone other oracle-based on-chain perpetuals. This is greatly appreciated by professional firms, due to the ease of accessing liquidity on DeFi, which contributes to higher volumes and fees for the protocol. Examples of market makers using dYdX include Cumberland, Wintermute, and Genesis Global Trading among others.
Ultimately, the goal of dYdX is to eventually become one of the largest exchanges in all of crypto. Since v1, the protocol has kept on improving and showing its dissatisfaction with existing infrastructure solutions. While dYdX could have opted for more standard options like an AMM or RFQ system on an L2 rollup, none of these solutions would get the protocol close to seeing its mission achieved.
The volume on dYdX today is largely thanks to the two major developments that took place in 2021. First, shifting to a layer 2 rollup enabled faster and cheaper transactions. Second, the launch of the $DYDX token made it more attractive to trade on the exchange, since you could get paid token rewards for doing so.
The early-moved advantage of dYdX cannot be understated either. Even without adding many new tokens and doing so very frequently the exchange still retains a dominant position among derivative DEXs. Instead of focusing on that front, that has allowed the team to focus on features such as improving the API, which makes it more useful and attractive for market makers and institutions.
Developing a decentralized, off-chain orderbook and matching engine and moving from Ethereum to a dYdX-specific chain as a major DeFi protocol is very much untested. However, dYdX believes that this is the best shot at developing a network that could offer a long-term competitive product experience with centralized exchanges.
Potential Adoption
One of the differentiating factors of dYdX is that it is heavily used by professional market-making firms. These companies can interact with the protocol using a standard API, just like they do with centralized exchanges. This way they don’t have to worry about the complexity and non-standard ways to interact with blockchains. These hedge funds and proprietary trading firms make up the majority of the trading volume, with “prosumer” retail users being the minority.
Cross-margining is also extremely helpful to attract professional traders and market makers, especially those who trade in multiple dYdX markets. With cross-margining on dYdX, market makers benefit from reduced collateral requirements compared to non-cross-margined platforms. This allows them to optimize their capital utilization and avoid the need for excessive collateral posting during volatile market conditions. It also provides flexibility for traders to switch between different markets easily.
Market makers on dYdX typically build their technology stack in-house. This approach minimizes reliance on third-party aggregators or APIs, reducing the risk of disruptions and ensuring they have control over their infrastructure. The need for real-time, high-speed, and responsive systems makes it challenging to find existing solutions that meet their requirements.
In addition to that, Central Limit Order Books (CLOBs) tend to utilize liquidity more efficiently than Automated Market Makers (AMMs). CLOBs can adjust their quotes freely and concentrate liquidity around the market price, while AMMs spread their liquidity across a range of prices.
This also opens up opportunities for arbitrage, where traders would most frequently execute the opposite leg of the arbitrage on another CLOB, possibly on a centralized exchange (CEX). Professional market makers on CEXs could benefit from low fees and performant infrastructure as well. In fact, strong market-maker partnerships could attract an increasing number of firms to trade on exchange. There is a potential incentive for market makers to partner with validators on dYdX v4 to more competitively execute cross-venue arbitrage.
Additionally, there is another form of arbitrage that comes into play: regulatory arbitrage. While constrained in the U.S. and Canada, dYdX is accessible in many jurisdictions where competitors like Binance or other centralized exchanges are not. Not only that, but dYdX’s trading fees are generally lower than those of centralized competitors, particularly when considering token rewards.
The v4 update will further decentralize the orderbook and matching engine. It will also enable quick addition of new trading pairs through on-chain governance and token holders will receive a share of transaction-fee revenue, promoting stakeholder engagement. This becomes increasingly important considering that unlike most crypto projects dYdX has recently turned profitable. This is a rare feat in the crypto space and suggests sustainable growth.
Using the Protocol
Perpetual Contracts
Perpetual futures contracts, also known as perpetual swaps, are a type of derivative financial instrument that enables traders to speculate on the price movements of an underlying asset without needing to own the asset itself.
The concept of perpetual futures was introduced by economist Robert Shiller in 1992 as a way to provide derivatives markets for less liquid assets. However, it wasn’t until 2016, with the launch of the first live perpetual futures contracts on the cryptocurrency exchange BitMEX, that perpetuals gained significant traction. Since then, perpetual futures have become popular in the crypto market, offering high-leverage trading opportunities.
Perpetual futures cater to the demand for advanced trading products in the crypto market, allowing traders to take advantage of price volatility. The ability to hold positions indefinitely and the potential for high leverage make perpetual contracts appealing to active traders. They provide capital efficiency by enabling traders to take large positions with limited capital, maximizing potential returns. However, it’s important to note that higher leverage also increases the level of risk involved.
In traditional futures contracts, traders agree to buy or sell an asset at a fixed price on a specified future date. In contrast, perpetual contracts lack an expiration date, allowing traders to maintain their positions for an indefinite period. Instead of directly buying the underlying asset, traders use perpetual contracts to speculate on the asset’s future price movements.
To maintain a price close to the underlying asset price, perpetual contracts utilize a funding rate mechanism. This mechanism tracks the difference between the contract price and the index price (the underlying asset’s price) and adjusts periodically. If the contract price deviates from the index price, a funding rate is applied to incentivize traders on the profitable side to balance the market. This mechanism ensures price convergence and keeps the contract price in line with the index price.
Finally, trading in perpetual contracts involves leveraged collateral, enabling traders to access larger positions with less capital. However, this leverage increases the risk associated with trading. One significant risk is the potential for liquidation, which occurs when the value of a trader’s position falls below a certain threshold. In such cases, the position is forcefully closed at a loss, which can be substantial for highly leveraged positions. Proper risk management and understanding of market conditions are crucial for traders to navigate the potential risks and maximize profitability in perpetual futures trading.
Leverage Trading
Leverage trading, often known as margin trading, allows users to borrow funds, thereby trading with a larger capital base. This strategy offers the potential for amplified returns but also increases the risk of losses. Leverage trading enables traders to open larger positions using the capital in their trading accounts.
In traditional financial markets, leverage trading is typically executed through a margin account. This account permits traders to borrow funds from a broker, enabling them to take larger positions. To do this, traders must maintain a minimum balance in their margin account, which serves as collateral for the borrowed funds. If the value of their account falls below this minimum balance, the broker may issue a margin call. This requires the trader to deposit additional funds or sell some of their positions to reduce exposure and restore the account balance to the required level. Failing to meet the margin call can lead to the broker liquidating the trader’s positions to repay the outstanding debt.
it’s crucial to highlight that leverage trading comes with an elevated level of risk. This is because traders are utilizing borrowed funds that must be repaid, irrespective of whether the trade results in a profit or a loss. In the event that the market moves against the trader, losses can accumulate rapidly and may surpass the capital originally invested. This situation can trigger a margin call, which necessitates additional funds or the sale of positions to cover losses. If a trader is unable to meet the margin call, it can lead to a forced liquidation of their positions.
Given these inherent risks, it’s of paramount importance for traders to thoroughly assess their risk tolerance and adopt appropriate risk management strategies when engaging in leverage trading. These strategies can include setting stop-loss orders, diversifying their portfolio, and only using leverage they are comfortable with, among other risk mitigation techniques.
Leverage Trading Example
Suppose a trader has $100 in their account and wants to trade an ETH-USD position worth $1,000 with 10x leverage. They can use the $100 of their capital and borrow the remaining $900 from dYdX. If the position doubles in value to $2,000, the trader can close the position, returning the initial $900 to the exchange and earning the trader $1,100 in profit. If the position depreciates, the trader can close the position to limit their losses. In either case, the trader must repay the borrowed funds that were leveraged in the position.
Pros of Using Leverage
- Capital efficiency: By using borrowed funds, traders can deploy their capital to access larger positions than possible with their funds alone. The collateral deposited becomes efficient by supporting larger positions. If the trade is successful, the trader can earn a higher return on their capital.
- Increasing returns potential: Leverage allows traders to open larger positions than otherwise possible, thus increasing the potential returns if the trade is successful.
Cons of Using Leverage
- Potential for losses: Just as leverage enables higher returns, it also puts traders at risk of more significant losses on their positions. If the position turns negative, the losses are amplified due to the larger position and the use of borrowed funds.
- Liquidation: When a trade is executed with leverage, the exchange sets a liquidation price on the position, usually set at a small loss, but this varies based on the leverage amount. If the market hits this price, the position is automatically closed with a market order, realizing losses for the trader. These losses can be substantial, potentially wiping out the entire collateral in the account.
- Complexity and risk: Trading with leverage requires understanding markets, risk, and the exchange mechanics involving margin and liquidation. Traders face additional complexities and risks that are not present in regular trading.
Market Makers vs Market Takers
Market makers and market takers are two different types of participants that play distinct roles in the buying and selling of assets in an exchange.
Market Makers
Market makers are individuals or entities that provide liquidity to the market by continuously quoting both bid (buy) and ask (sell) prices for a specific asset. They essentially act as intermediaries between buyers and sellers. Market makers commit to facilitating trades by being willing to buy or sell at the prices they quote.
- Bid-Ask Spread: Market makers profit from the bid-ask spread, which is the difference between the prices at which they are willing to buy and sell an asset. They aim to buy at the lower bid price and sell at the higher ask price, capturing the spread as their profit.
- Continuous Quoting: Market makers provide constant quotes for buying and selling an asset, ensuring there is always a ready market for traders to execute their orders. By offering liquidity, they contribute to price stability and market efficiency.
- Reduced Execution Risk: Market makers help reduce execution risk for traders by providing liquidity and tight spreads. Traders can quickly buy or sell assets at prices quoted by market makers, without worrying about their orders significantly impacting the market price.
- Volume Incentives: Market makers may receive incentives, such as fee discounts or rebates, from exchanges or trading platforms to encourage higher trading volumes and liquidity provision.
Market Takers
Market takers are participants who accept the prices quoted by market makers and execute trades by accepting existing orders from the order book. They “take” liquidity from the market by accepting the available prices rather than providing liquidity themselves.
- Accepting Existing Prices: Market takers accept the current best available bid or ask prices in the order book for their trades. They are not involved in setting prices but rather execute orders at the prevailing market rates.
- Immediate Execution: Market takers prioritize immediate execution of their trades and are willing to accept the existing liquidity and prices in the market. They typically pay transaction fees to the exchange or trading platform for their executed trades.
- Market Impact: Market takers’ orders can have an impact on the market, particularly for larger orders. If a market taker’s order is large relative to the current liquidity available, it may cause the market price to move as the order is filled.
Market takers rely on the liquidity provided by market makers and other participants in the market. They are looking to quickly enter or exit positions and are willing to accept the prevailing market conditions.
Mobile Experience
dYdX was made available on iOS on May 10, 2022.
The app offers the same functionality and experience that is available on the website, but with the added convenience of trading on the phone.
Business Model
dYdX operates a decentralized exchange for trading financial derivatives and perpetual futures. Hence, the exchange’s business model is based on charging trading fees to users. There are two types of trading fees: maker fees and taker fees.
- Maker fees are charged to users who create orders that are not immediately filled.
- Taker fees are charged to users who take liquidity from the order book by filling existing orders.
With V4 and the dYdX chain, the protocol also earns revenue from staking fees. Staking is the process of locking up tokens in order to participate in the security and governance of the network. This way, dYdX users who stake $DYDX tokens are rewarded with a portion of the exchange’s trading fees.
In addition to trading fees and staking fees, dYdX also earns revenue from margin lending. Margin lending is a service that allows users to borrow funds to trade with leverage. dYdX charges interest on margin loans, which is another source of revenue for the exchange.
Fee Breakdown
v3
These are the current fee breakdowns for V3.
dYdX uses a maker-taker fee model for determining its trade fees. There are two types of orders on dYdX, being Maker and Taker orders.
- Maker orders are orders that do not immediately fill and rest on the order book — these orders add depth and liquidity to the order book.
- Taker orders, on the other hand, immediately cross existing Maker orders. They remove liquidity from the order book.
Level | From (30D Volume in USD) | To (30D Volume in USD) | Maker | Taker |
1 | $0 | $1M | 0.02% | 0.05% |
2 | $1M | $5M | 0.015% | 0.04% |
3 | $5M | $10M | 0.01% | 0.035% |
4 | $10M | $50M | 0.005% | 0.03% |
5 | $50M | $200M | 0% | 0.025% |
VIP | $200M+ | – | -0.0085% | 0.02% |
Trading Fee Discounts:
- Hedgie holders will be eligible to receive a 3% fee discount and holding multiple Hedgies will not increase the discount percent.
v4
These are the current fee breakdowns for v4.
All fees (trading fees denominated in $USDC and gas fees for DYDX-denominated transactions or USDC-denominated transactions) collected by the protocol are distributed to Validators and Stakers.
Tokenomics
$DYDX is the protocol token, and the dYdX protocol is governed by its token holders.
- On v3, $DYDX has been renamed to $ethDYDX.
- On v4, it is recognized as $DYDX.
The v4 protocol is designed with a need for a layer 1 protocol token, and this will be fulfilled with the $DYDX token. This way, $DYDX will be used for staking to validators as well as for the development of the ongoing governance of the chain.
The current token variants of $DYDX are as follows:
Token Distribution
A total of 1 billion $DYDX tokens have been minted, and will become accessible over five years, starting on August 3rd, 2021, at 15:00:00 UTC.
Due to several governance proposals passing, the current allocation of the total supply of $DYDX is as follows:
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 forward.
Governance
Scope
- Allocation of the community treasury
- New token listings on the Protocol
- Risk parameters for the Protocol
- Capital allocations to market makers in the liquidity staking pool
- Addition of new market makers to the liquidity staking pool
- Determining safety staking pool payouts in the event of a loss
- Changing any of the rewards and pools existing at launch
- The governance contracts themselves
Governance Architecture
dYdX grants holders the right to propose and vote on changes to the Protocol. dYdX governance is based on the AAVE governance contracts and supports voting based on DYDX token holdings.
Proposals must pass a given threshold and percent of yes votes based on the type of proposal.
These dYdX tokens can be used to make proposals or vote on governance proposals or be delegated to other Ethereum addresses.
There are 6 smart contracts at the core of dYdX Governance:
- The $DYDX Token Contract: has snapshots of each address’ voting power at different blocks in time.
- The Governance Strategy Contract: contains logic to measure users’ relative power to propose and vote.
- The Safety Module Contract: contains logic to stake DYDX tokens, tokenize the position, and get rewards. Tokens staked the safety module retain full governance rights.
- The Governor Contract: tracks proposals and can execute proposals via the Timelock smart contract.
- The Timelock Contracts: can queue, cancel, or execute transactions voted by Governance. The functions in a proposal are initiated by the Timelock contract. Queued transactions can be executed after a delay and before the expiration of the grace period.
- The Priority Timelock Contract: The same as the timelock contract, but allows a priority controller to execute transactions within the Priority Period (7 days) before the end of the timelock delay.
dYdX on-chain governance allows for:
- Voting on proposals to be executed by any authorized executor contract
- Snapshotting token holdings at the start of a proposal
- Separate delegation of voting and proposing powers
- Setting governance thresholds including proposals, quorums, and vote differential powers
- Changing how votes are counted (by changing the “Governance Strategy” smart contract address on the Governor contract)
There are four types of proposals with different parameters that affect the length and execution of a proposal, i.e. critical proposals that affect governance consensus require more voting time and a higher vote differential, whereas proposals affecting only protocol parameters require less voting time and can be quickly implemented. An executor must validate each type of proposal.
These include the following:
- Short timelock executor
- The short-timelock executor controls the following:
- Incentive contracts including the Liquidity Module, Safety Module, and Merkle Distributor Module
- funds in the Rewards and Community Treasuries
- minting new tokens
- all proxy contracts except the safety module
- guardian roles on Stark Proxy contracts
- Starkware priority timelock executor
- The Starkware priority timelock executor owns the StarkEx Perpetual Exchange contract. It can execute proposals that control the configuration of the dYdX Layer 2 Exchange.
- Depending on the action to be taken, the Starkware team may need to be involved in order to correctly implement the change on the exchange. For this reason, this executor is provided with a “priority controller” role, which provides Starkware with a period of 7 days (Priority Period) in which only they have the ability to trigger the execution of a proposal.
- Starkware does not have control over which protocol changes are made. Only DYDX tokenholders, via dYdX governance, have the ability to approve or deny changes to the exchange protocol.
- Long timelock executor
- The long timelock executor can execute proposals that generally change parts of the Protocol that affect governance consensus.
- Merkle-pauser executor
- The Merkle-pauser executor can execute proposals that freeze the Merkle root, which is updated periodically with each user’s cumulative reward balance, allowing new rewards to be distributed to users over time, in case the proposed root is incorrect or malicious. It can also veto forced trade requests by any of the stark proxy contracts.
The initial timelock parameters are as follows:
Proposal Lifecycle
The dYdX Governance Process is fueled by governance forums at https://dydx.forum/ and ratified through the dYdX Improvement Proposal (“DIPs”).
The process consists of multiple stages.
Stage 0: Forum Discussion
Anyone can sign up and set up a thread on any topic on dYdX’s Governance forums hosted at https://dydx.forum/. Community members are required to register using an email address or an Ethereum wallet.
Stage 1: (Off-chain) DRC Creation
Off-chain dYdX Request for Comments (DRCs) creation is the first step in the governance improvement process. Anyone can participate in the Governance Forum, create off-chain DRCs, and discuss improvements.
To create a DRC, use this template. The DRC should cover all the information of the potential final DIP.
At a minimum, DRCs must include:
- Short and concise titles of the DRC
- A short and concise description of the proposal
- The rationale for the DRC, e.g. why?
- The title of the forum post must include DRC: with the short title of the DRC. E.g. DRC: New Market Request
- A community poll that community members can use to vote on improvements off-chain
Stage 2: DRC Discussion & Feedback
Once posted on the governance forum, all questions and comments should be addressed & taken into consideration, to further improve the DRC.
Stage 3: DRC Snapshot Polling
Snapshot polls serve two purposes: sentiment signaling for future on-chain DIPs and binding votes for variables controlled off-chain.
Once an off-chain DRC has a very rough consensus, a community member with more than 10,000 $DYDX proposing power can create an off-chain vote for the DRC on Snapshot. It is encouraged for the dYdX Community to create Snapshot polls on Mondays to increase visibility during the regular workweek.
Snapshot is a simple voting interface that allows users to signal sentiment off-chain. Votes on Snapshot are weighted by the voting power of the address used to vote.
For Snapshot polls related to sentiment signaling, the proposer will need to provide:
- details of the DRC,
- a voting system,
- a voting period – vote start date and vote end date set to a 4-day voting period, and
- a voting delay – a Snapshot block number that is 6570 blocks (approximately 1 day based on 13.2 second block time) in the future. The Snapshot block number locks the state of community members who can vote. Token holders who hold tokens before the Snapshot block number are eligible to vote. Before the snapshot of each address’ respective voting power, the voting delay gives $DYDX/stkDYDY holders time to acquire tokens, delegate voting power, and move tokens between wallets (moving tokens between wallets only applies to $DYDX holders).
For decisions that don’t require an on-chain smart contract call, notably changes to the Trading and Liquidity Provider rewards formulas, Snapshot votes are considered the binding and final vote. The proposer will need to include the requirements above and provide:
- binary voting options – for clarity, an address is either voting for or against a proposal.
The proposed change(s) will be implemented by dYdX Trading Inc. if the results of the Snapshot poll satisfy:
- the minimum quorum – at least 1M $DYDX/stkDYDX. The minimum quorum contributes to the decentralization of decision-making and protects against unilateral decision-making, and
- the minimum vote differential – at least 67% of votes must be in favor of the proposal. The minimum vote differential assists with filtering out proposals that are highly contentious and require further discussion.
dYdX Trading Inc. will have up to 1 Epoch (28 days), an execution grace period, to implement changes from a successful Snapshot poll.
Note that proposals and votes are just signed messages, stored on IPFS, and available via the Commonwealth portal.
Stage 4. (On-chain) DIP Creation
When a rough consensus is reached, an on-chain DIP may be submitted by a community member who holds enough proposition power for the type of proposal. An on-chain DIP is initiated via a smart contract call. The proposal should be based on the winning outcome of the off-chain DIP voting on Snapshot and can consist of one or multiple actions, up to a maximum of 10 actions per proposal.
A DIP creation is subject to a minimum number of tokens held/delegated required for an account. A Timelock executor must be specified when a proposal is created. The initial parameters are as follows (and can be modified by governance):
Parameter | Description | Short Timelock Executor | Merkle-Pauser Executor | Long Timelock Executor | Starkware Executor |
Proposal Threshold | Minimum tokens held/delegated to create proposal | 0.5% of total supply | 0.5% of total supply | 2% of total supply | 0.5% of total supply |
Stage 5: (On-chain) DIP Voting
After an On-Chain DIP is created, the proposal enters a pending state for a period defined by the Voting Delay, which is currently configured to 6570 blocks or approximately 1 day (assuming 13.2 seconds per block). In other words, user snapshots are recorded 1 day after the DIP is created, at which point the proposal transitions to an active state.
After the Voting Delay, the Voting Period is activated. The voting period length depends on the proposal type.
The following chart shows a DIP state flowchart:
After a DIP is created on-chain it is subject to a Voting Delay, Voting Period, Minimum Quorum, and a minimum Vote Differential. The initial parameters are as follows:
Parameter | Description | Short Timelock Executor | Merkle-Pauser Executor | Long Timelock Executor | Starkware Executor |
Voting Delay | Number of Ethereum blocks to wait before voting on a proposal may begin after a proposal is submitted | 6,570 blocks | 6,570 blocks | 6,570 blocks | 6,570 blocks |
Voting Period* | Length of time for which proposals are available to be voted upon | 4 days | 2 days | 10 days | 4 days |
Minimum Quorum | Minimum yes votes for a DIP proposal to pass | 2% of total supply | 1% of total supply | 10% of total supply | 2% of total supply |
Vote Differential | Required yes-no gap for a DIP proposal to pass | 0.5% of total supply | 0.5% of total supply | 10% of total supply | 0.5% of total supply |
Only the voting delay can be modified by governance, and it can only be changed to values in between (inclusive) the minimum and maximum delay. The voting period, minimum quorum, and vote differential can’t be changed.
Stage 6: Proposal Queuing & Execution
After a DIP has passed, any address can call the queue method to move the proposal into the timelock queue. A DIP can only be queued if it has passed.
Parameter | Description | Short Timelock Executor | Merkle-Pauser Executor | Long Timelock Executor | Starkware Executor |
Timelock Delay* | After a proposal passes and is queued, delay before the proposal is executed | 2 days | 0 days | 7 days | 2-9 days |
Execution Grace Period* | The time after which a proposal becomes executable, during which it must be executed. | 7 days | 7 days | 7 days | 7 days |
Minimum Timelock Delay* | Minimum delay before a proposal is executed (after queuing) | 1 day | 0 days | 5 days | 4 days |
Maximum Timelock Delay* | Maximum delay before a proposal is executed (after queuing) | 7 days | 1 day | 21 days | 21 days |
As soon as the voting period ends and a proposal has succeeded, anyone can call a queue to begin the timelock delay.
For the Starkware priority timelock executor, it has a priority period of 7 days out of the 9-day timelock delay. This means that after 9 days anyone can execute a proposal, but within days 2-9 (the priority period) Starkware has the option to execute the proposal.
In practical terms, it’s:
- Days 0–2: No one can execute
- Days 2–9: Only Starkware can execute
- Days 9: Anyone can execute
Stage 7: (Optional) Proposal Cancellation
At any point in a DIP lifecycle, the proposer can cancel the DIP. A proposal can be canceled by anyone before it is executed if the proposer does not have sufficient proposition power at the current block.
Voting Process
The Protocol is governed and upgraded by $DYDX holders and delegates.
There are two powers associated with each $DYDX token:
- The proposing power gives access to creating and sustaining a proposal.
- The voting power is used to vote for or against existing proposals.
$DYDX holders receive governance powers proportionally to their sum of owned and delegated tokens at a given block.
V4
The governance module for dYdX Chain (v4) was introduced on June 23, 2023.
dYdX Chain will utilize the standard x/gov module within the Cosmos SDK. The module enables Cosmos SDK-based blockchain to support an on-chain governance system, where holders of the native staking token can vote on proposals on a 1 token 1 vote basis.
Holders, via the governance process, will be able to alter the standard parameters across a variety of modules within the Cosmos SDK.
In addition, a non-exhaustive list of parameters that are adjustable includes:
- Add new markets
- Adjust parameters of a live market
- Remove any market
- Edit the list of 3rd party price sources that the exchange uses
- Fee schedule
- Trading rewards mechanics
- x/distribution module parameters affecting trading and gas fees
- x/staking module parameters
- Funding rate formula
- Control of the insurance fund
Proposing a New Market
To propose a new market on the dYdX Chain, dYdX v4 software users can follow a streamlined process designed to ensure optimal compatibility and performance.
Step-by-Step Process:
- Navigating to the Markets Tab:
- Start by accessing the dYdX Chain’s interface. Locate and click on the “Markets” tab where you can view existing markets and manage market-related activities.
- Adding a New Market:
- Click on the “Add New Markets” button. This will initiate the process for proposing a new market listing.
- Selecting a Market:
- You will be prompted to either search for or select a market from a list. dYdX Trading provides an open-sourced list of market parameters that have been evaluated for compatibility with the dYdX v4 software. This ensures that any proposed market will operate optimally within the existing infrastructure.
- Confirming Market Details:
- After selecting a market, key details such as the Reference Price, Oracles, and Liquidity Tier will automatically populate based on the chosen market. These parameters are crucial for ensuring that the market functions correctly and efficiently.
- Submitting the Market Proposal:
- Once all details are confirmed, you can proceed to sign a transaction. This transaction will create a formal proposal to add the selected asset as a new market on the dYdX Chain. It’s important to note that you must have a sufficient balance of the applicable governance tokens to initiate this proposal.
Click here for more information and methodologies.
Security
Audits
Smart Contract Audit Report – 2021 – PeckShield
- Medium – 1 (1 Fixed)
- Low – 3 (3 Fixed)
- Informational 3 (3 Fixed)
V4 Chain Audit, Security Audit Report – September 15, 2023 – Informal Systems
- Medium – 1
- Low – 12
- Informational – 15
V4 Chain Audit, Security Audit Report – September 28, 2023 – Informal Systems
- Critical – 1
- Medium – 3
- Low – 5
- Informational – 4
Bug Bounty
dYdX has a bug bounty program for its dYdX Chain.
The rewards are as listed:
- Low: $50 – $5,000
- E.g. Display or event-parsing issues
- Medium: $5,000 – $50,000
- E.g. Issues leading to non-core-product failures of the exchange such as staking or governance
- High: $50,000 – $150,000
- E.g. Issues leading to network downtime or liveness failures
- Critical: $150,000 – $1,000,000, depending on the potential impact of the critical vulnerability. Extraordinary finds in this category could extend up to $5,000,000.
- E.g. Issues leading to bugs or attacks resulting in significant loss of funds.
Vulnerability Disclosure Policy
The vulnerability disclosure policy helps to ensure the security of dYdX by allowing users to report vulnerabilities found, via email, and including the following:
- A description of the location and potential impact of the vulnerability.
- A detailed description of the steps required to reproduce the vulnerability.
Scope
Any vulnerability not previously disclosed by dYdX or their independent auditors in their reports.
Guidelines
Reporters are required to adhere to the following:
- Make every effort to avoid privacy violations, degradation of user experience, disruption to production systems, and destruction of data during security testing.
- Use the identified communication channels to report vulnerability information to dYdX.
- Keep information about any vulnerabilities discovered confidential between yourself and dYdX until dYdX has had 30 days to resolve the issue.
- If you follow these guidelines when reporting an issue to dYdX, dYdX commits to:
- Not pursue or support any legal action related to your findings.
- Work with you to understand and resolve the issue quickly (including an initial confirmation of your report within 72 hours of submission).
- Grant a monetary reward based on the OWASP risk assessment methodology.
Past Vulnerabilities
Deposit Proxy Contract Post-Mortem
On November 27th, 2021, a critical vulnerability was discovered in the proxy smart contract responsible for handling deposits to the dYdX exchange. This vulnerability allowed an attacker to steal ERC-20 balances up to the approved amount by manipulating contract calls. The dYdX team took immediate action to address the issue and protect user funds.
Upon confirming the bug, the dYdX team collaborated with external experts to execute a white-hat hack, rescuing approximately $2 million worth of vulnerable user funds. These funds were securely transferred to a non-custodial escrow contract, ensuring only the original owners can access them. Affected users were promptly notified and advised to revoke all approvals on the contract and avoid receiving ERC-20 tokens until completing this step.
A total of 730 addresses with allowances were identified as affected, with 180 of them holding funds directly at risk during the exploit. As of December 8th, all but 91 of the original affected addresses, which currently hold no exploitable funds, have revoked their allowances. The dYdX team continues to monitor these wallets to safeguard user funds. Users who have not yet revoked their allowances are strongly advised to take immediate action.
The smart contract containing the vulnerability was a “currency converter” proxy contract designed to allow deposits to dYdX from a broad range of currencies. The contract works by converting a user’s funds to $USDC and depositing them to the dYdX exchange in a single transaction. The implementation was based on a previous smart contract that was used with an earlier version of the dYdX exchange. The old contract uses a standardized “exchange wrapper” interface to support calls to various decentralized spot exchanges.
The new contract intended to perform swaps using 0x API. Quotes returned from the 0x /swap/v1/quote endpoint included calldata that can be submitted to the 0x contract to execute a trade.
Note that both the exchange and data parameters are untrusted: they are provided off-chain by 0x API and are supplied to the smart contract by the client/user. For dYdX’s use case, this is safe when the call to the 0x contract is made via the exchange wrapper interface.
The problem with the new design is that a single smart contract has both an ERC-20 approval set by the user, as well as the ability to make an arbitrary smart contract, calls to an untrusted address with untrusted calldata. This allows an attacker to steal an ERC-20 balance, up to the approved amount, by passing in parameters with exchange equal to the ERC-20 token address, and data encoding a call to transferFrom() transferring funds to the attacker.
DNS Nameserver Hijacking Postmortem
In 2023, dYdX’s domain, dydx.exchange, was migrated from Google Domains to Squarespace following Google’s domain service shutdown. On July 9, 2024, attackers exploited an OAuth vulnerability at Squarespace to gain control of the domain’s DNS settings, redirecting traffic to a malicious site. This attack was initially mitigated by DNSSEC settings, but a subsequent security incident on July 23 allowed the attackers to fully compromise the domain through a social engineering attack targeting Squarespace’s account-recovery process.
In this second incident, the attackers managed to reset the domain’s admin email to their own, bypassing the 2FA protections. They then hosted a phishing site that led to two users losing approximately $31,000 in $ETH and ERC20 tokens. dYdX worked with security teams to block the malicious site and recover the domain, eventually transferring it to Cloudflare to prevent further breaches.
The issues were attributed to both the OAuth vulnerability and weak account-recovery protocols at Squarespace. dYdX has taken steps to secure its domain and is assisting affected users in recovering their lost funds. No security breaches were reported in dYdX’s smart contracts, backend systems, or the dYdX Chain as a result of these incidents.
$YFI and $SUSHI Market Manipulation Incidents
In late 2023, dYdX v3 experienced significant market manipulation involving $SUSHI and $YFI. An attacker exploited the platform’s leverage and margin mechanisms to inflate the prices of these tokens, profiting substantially before the markets crashed. While no user funds were directly compromised, the events highlighted vulnerabilities in the platform’s risk management and margin systems.
$SUSHI Market Incident
Oct 29th 2023 – Nov 3rd 2023 |
$YFI Market Action
Nov 1st 2023 – Nov 17th 2023 |
$YFI Market Crash
Nov 18th 2023 |
|
dYdX increased the margin requirements and adjusted position sizes to limit the attacker’s ability to withdraw further profits. |
|
As a result, dYdX implemented updates and enhancements to risk control systems on:
dYdX v3:
- Revised Margining: Automatic adjustments to the initial margin fraction during abnormal activities to prevent profit withdrawals against inflated gains.
- Improved Monitoring: Enhanced open-interest tracking and alert systems to detect and respond to unusual market behavior.
dYdX Chain (v4):
- Redesigned Liquidation Engine: A new liquidation system designed to detect and efficiently liquidate risky positions, with a fallback to automatic deleveraging (ADL) to protect the system.
- Data-Driven Market Availability: Deployers of the dYdX Chain are advised to use market depth and trading activity data to determine which instruments to list and the appropriate leverage to extend.
Variable Margin Fraction: A new feature that adjusts the margin requirements in response to large price movements, preventing the kind of cyclical profit withdrawals seen in the YFI incident.
Team
The LinkedIn page lists 77 employees. Some of the notable employees include:
- Antonio Juliano – Founder
- George Xian Zeng – COO
- Rashan A. Colbert – Head of Policy
- Daniel Lan – Head of Finance
- Gian Raciti – Head of Talent and People
- Vivek Saini – Chief of Staff
- Roselynn Chang – Chief of Staff
dYdX Foundation
The dYdX Foundation is an independent not-for-profit foundation headquartered in Zug, Switzerland. The Council consists of Arthur Cheong, Rebecca Rettig, and Markus Spillman.
It was introduced on August 3, 2023, with the purpose of supporting and growing every aspect, technical or otherwise, of the current and future implementations of the dYdX Protocol, including but not limited to the related ecosystem.
The mandate empowers the Foundation to do the following:
- Support and finance appropriate research and development activities and projects.
- Promote and educate the public on the ecosystem and/or dYdX.
- Issue, receive, spend, and hold digital assets (no speculative trading activities)
- Deploy governance smart contracts and issue governance tokens.
- Engage with various businesses, partners, banks, regulators, authorities, and other third parties to the benefit of the ecosystem.
- Distribute received contributions and participate in companies.
- Acquire, hold, or grant trademarks, copyrights, and other intellectual property rights or licenses.
- Organize conferences and other events that support and promote the ecosystem and/or dYdX.
- Conduct and promote all businesses and/or enter into all transactions, and generally perform all acts as may be necessary, appropriate, incidental to, or desirable to assist in achieving or promoting the objects described herein.
As the dYdX Foundation assists with the development and growth of the dYdX ecosystem and governance-related matters, dYdX Trading’s core development team will spend its future time focused on, amongst other things, decentralizing the order book and matching engine components. Although a decentralized orderbook and matching engine will result in modifications, there is no expectation that it will enhance functionality. Instead, it will have the benefit of creating censorship resistance in all aspects of the protocol.
The dYdX Foundation does not have a profit-making purpose and does not seek any profits in general. Meanwhile, dYdX Trading will continue to charge maker-taker fees tied to trade volume, which will cover transaction fees for trades, earn revenue, and incentivize more liquidity.
By fostering decentralized governance and empowering traders with powerful, transparent, and open advanced financial products, the dYdX Foundation will help push dYdX towards community-led growth, development, and self-sustainability.
Project Investors
There have been 4 rounds of raises for dYdX, including a seed round. The total amount raised is $87M.
- Seed Round
- $2M raised in December 2017.
- Led by Chris Dixon at Andreessen Horowitz and Olaf Carlson-Wee at Polychain Capital.
- Other investors include Fred Ehrsam, Brian Armstrong, Elad Gil, Scott Belsky, Avichal Garg, Kindred Ventures, Abstract Ventures, 1confirmation, and many more.
- Series A Round
- $10M raised in October 2018.
- Led by Chris Dixon at a16z crypto and Olaf Carlson-Wee at Polychain Capital.
- Other investors include Abstract Ventures, Kindred Ventures, 1confirmation, Elad Gil, Fred Ehrsam, Craft Ventures, Bain Capital Ventures, Naval Ravikant, Kevin Hartz, Dragonfly Capital and VY Capital.
- Series B Round
- $10M raised in January 2020.
- Led by Three Arrows Capital and DeFiance Capital.
- Also includes Wintermute, Hashed, GSR, SCP, Scalar Capital, Spartan Group, and Rocktree Capital.
- Series C Round
- $65M raised in June 2021.
- Led by Paradigm.
- Also includes QCP Capital, CMS Holdings, CMT Digital, Finlink Capital, Sixtant, and many more.
Additional Information
Glossary
- $DYDX: The native asset of the DYDX ecosystem, which constitutes the foundation of governance and safety for the dYdX Protocol. $DYDX is an ERC-20 token that designates the weight of a user’s voting or proposing power.
- dYdX Protocol: dYdX’s Layer 2 perpetual protocol.
- dYdX Foundation: an independent foundation, headquartered in Zug, Switzerland, was created to participate in propelling the dYdX Protocol into the future.
- $DYDX Token contract: has snapshots of each address’ voting power at different blocks in time.
- DIP: dYdX Improvements Proposals are on-chain governance proposals.
- DRC: dYdX Request for Comments are off-chain proposals and the first required step in the governance improvement process.
- Quorum: In order for a vote to pass, it must achieve a minimum quorum of $DYDX tokens in the affirmative. The purpose of the quorum is to ensure that the only measures that pass have adequate voter participation.
- Epoch: All other contracts operate on 28-day cycles, referred to as epochs.
- Execution Grace Period: The period after vote when a DIP proposal becomes executable, during which it must be executed.
- Governance Strategy contract: contains logic to measure users’ relative power to propose and vote.
- Governor contract: tracks proposals and can execute proposals via the Timelock smart contract.
- Long timelock executor: The long timelock executor can execute proposals that generally change parts of the Protocol that affect governance consensus.
- Merkle-pauser executor: The Merkle-pauser executor can execute proposals that freeze the Merkle root, which is updated periodically with each user’s cumulative reward balance, allowing new rewards to be distributed to users over time, in case the proposed root is incorrect or malicious.
- Safety Pool: Component in charge of shielding the protocol from insolvency.
- Staked dYdX contract: contains logic to stake $DYDX tokens, tokenize the position, and get rewards.
- Short timelock executor: The short timelock executor can execute proposals that generally change Rewards and Incentive contracts or the Community Treasury that require quick intervention.
- Starkware executor: The Starkware executor can execute proposals that generally change parts of the Protocol that currently require intervention from Starkware.
- Timelock contract: can queue, cancel, or execute transactions voted by Governance. The functions in a proposal are initiated by the Timelock contract. Queued transactions can be executed after a delay and until the Grace period is not over.
- Timelock Delay: The delay before a DIP proposal is executed after a proposal passes and is queued.
- Proposal Threshold: To prevent a system where countless spam proposals are created, a proposal threshold requires an address to have a certain number of votes before they can make a proposal.
- Proposing Power: Token stake giving access to creating and sustaining a proposal.
- Voting Power: Voting power which is used to vote for or against existing proposals.
- Voting Delay: This is the length of time between which a proposal can be created and it is available to be voted upon. By requiring at least one block to pass, the governance is protected from Flash Loan attacks that might borrow a large number of tokens, propose a vote, and vote on it all in one block.
- Voting Period: Once a DIP proposal has been put forward, dYdX community members will have to cast their votes before the end of the Voting Period. This is the length of time for which proposals are available to be voted upon, with time in Ethereum Blocks.
- Proposal Threshold: Minimum tokens held/delegated required to create a DIP proposal.
- Vote Differential: Required yes–no gap for DIP proposal to pass.
License
dYdX provides a license specific to dYdX Trading Inc. that grants certain rights and imposes restrictions on the access, copying, and use of the code in their repository.
- Grant of Rights: The license grants the right to access, copy, and use the code in the repository (referred to as the “Licensed Code”) for the purpose of evaluating the code and assessing its interoperability with your own products and services.
- Restrictions: You are not allowed to use the Licensed Code for any purpose other than the specified evaluation and interoperability assessment. Additionally, you are prohibited from providing, disclosing, or distributing the Licensed Code to any third party, and from modifying or creating derivative works based on the code.
- Termination: Violation of the license terms automatically terminates your rights under the license.
- Conspicuous Display: If you make copies of the Licensed Code, you must display the license terms prominently on each copy.
- Future Open Source License: The license states that dYdX intends to release the Licensed Code under an open source license in the future. Until that happens, the terms of this proprietary license remain in effect.
- Trademark Disclaimer: The license does not grant any rights to use dYdX’s trademarks, service marks, or logos.
- Disclaimer of Warranties: dYdX disclaims all warranties and conditions, both express and implied, including but not limited to warranties of merchantability, fitness for a particular purpose, non-infringement, and title. The Licensed Code is provided “as is.”
FAQ
General
- What is the balance of the Community Treasury and Rewards Treasury that the dYdX community can access?
- dYdX community members can view the vested balance of the community treasury here.
- Further, the dYdX Foundation publishes the accrued balance of the Community Treasury in the Epoch Review at the end of each epoch.
- Who can submit proposals to spend $DYDX from the Rewards Treasury?
- Any user with sufficient proposing power can submit proposals. A governance vote will be required to spend any $DYDX from the community treasury and/or the rewards treasury. To submit a proposal, please submit a dYdX Improvement Proposal (DIP) as laid out in the DIP Proposal Lifecycle.
Chain
- Isn’t bridging assets across chains a challenge? Will this limit the number of markets available to trade on dYdX?
- Yes, bridging assets across blockchains is indeed challenging. Existing bridges often face issues related to user experience and security. However, dYdX’s focus on synthetic trading offers a solution. Only one collateral asset, such as a stablecoin, is required to enable synthetic trading of any asset. This means that the number of markets available to trade on dYdX is not limited by the challenges of asset bridging.
- Yes, bridging assets across blockchains is indeed challenging. Existing bridges often face issues related to user experience and security. However, dYdX’s focus on synthetic trading offers a solution. Only one collateral asset, such as a stablecoin, is required to enable synthetic trading of any asset. This means that the number of markets available to trade on dYdX is not limited by the challenges of asset bridging.
- I thought Ethereum & Ethereum-based L2s were more decentralized than Cosmos. Do you not care about decentralization?
- Decentralization is the fundamental objective of dYdX v4. With the dYdX Chain, the goal of v4 is to achieve maximum decentralization and performance throughout the entire product. While Ethereum L1 may currently be more decentralized than Cosmos, it lacks the necessary performance to power dYdX. Ethereum-based L2s also face limitations in terms of performance and rely on central sequencers, which can potentially censor transactions. The dYdX Chain on Cosmos allows to strike the ideal balance between decentralization and performance.
- What is the impact of Layer 2 on liquidity & composability?
- If adoption becomes fragmented across a number of different Rollups in addition to liquidity on Layer 1 vs Layer 2, Ethereum’s base layer is likely to lose some of the composability. However, it is likely that in the medium term, new solutions will emerge to enhance composability.
Exchange
- Which collateral will you accept?
- All perpetual contrast will be settled and margined in $USDC.
- How does trade settlement work?
- Trades are matched off-chain and held in batches until the proof of the validity of the batch is submitted on-chain, where it lives permanently. This prevents the front-running of trade settlements and allows for instantaneous balance updates without waiting for a transaction to be mined. Trading on dYdX will feel every bit as fast as trading on a centralized exchange
- How will liquidations work, and what are the penalties?
- Given the performance improvements of the oracles, we will be able to offer lower margin requirements, which means both higher maximum leverage as well as lower penalties when liquidated. Accounts whose total value falls below the maintenance margin requirement may have their positions automatically closed by the dYdX liquidation engine. Profits or losses from liquidations are taken on by the insurance fund.
Community Links