Upgrading the Margin Trading Protocol

Our Approach to Extensibility, Security, and Trust

This article is the first in a set of more technical posts about the design of the dYdX Margin Trading Protocol. In this post, we discuss the design decisions behind the upgradability of the protocol, specifically how we expect the protocol to be enhanced over time. We designed the protocol to be as trustless and permissionless as possible, requiring minimal governance and allowing any party to extend the protocol’s functionality as new standards and exchanges emerge. We believe that the way we have chosen to approach these challenges is unique in the space today.

The Base Protocol

As described in the dYdX whitepaper, the basic primitive of the dYdX Margin Trading Protocol is a Margin Position. A Margin Position is an agreement between two parties: a lender and a trader. The trader borrows some asset from the lender with a specified interest rate, and locks up collateral to insure the loan. Margin Positions can be created, increased, and closed.

We use the term Base Protocol to refer to the collection of smart contracts written and deployed by the dYdX team that carry out and enforce the Margin Trading Protocol described above. The Base Protocol includes public functions to create, increase, and close positions, as well as other functions to help lenders and traders manage their Margin Positions. This includes functions to read state, transfer ownership, margin-call positions, and increase a margin deposit.

Upgrade Patterns

Existing Models

There are several ways to upgrade contracts. One of the most popular ways is to grant special privileges to the contract’s creators that allow them to make arbitrary changes to the contract’s logic or authorized accounts.

One way to upgrade contracts is to modify logic in-place, allowing a central party to effectively overwrite the contract’s code. As noted in the DAO whitepaper, “although code is theoretically immutable, one can easily get around this and have de-facto mutability by having chunks of the code in separate contracts, and having the address of which contracts to call stored in the modifiable storage.” RocketPool is a prime example of this model, stating that “all main contracts must be upgradable.” The justification given is that the contract logic must be mutable in case a serious bug is discovered.

Another way to upgrade contracts is by approving new authorized addresses to move users’ tokens. This is the model used by 0x’s TokenTransferProxy. Users set token approval on the proxy, but the proxy owner can add new authorized addresses that can use the proxy to move users’ tokens. The proxy owner is a multisig contract with a two week time-lock, which means that all function-calls out of the multisig require at-least a two week delay. However, users must monitor the contract to ensure that no malicious addresses are added.

Drawbacks

Upgrade mechanisms like these introduce a great deal of centralization and trust. The central party must be trusted to act in the best interests of the protocol users. The central party must also be trusted to secure their private keys since the mechanism can allow hackers to steal funds. We assert that such a high level of trust is unacceptable when dealing with financial products; no party should be able to influence open positions or modify settlement logic.

Our Approach

In the case of the Margin Trading Protocol, there is no on-chain mechanism for any party to modify the logic of the Base Protocol. Instead, most upgrades are designed to be implemented on top of the Base Protocol. That is, by deploying external smart contracts that interact-with and extend the functionality of the Base Protocol. We refer to these contracts as Second-Layer contracts.

Second-Layer contracts require no special permissions from the Base Protocol. They can be written and deployed by anyone, thereby decentralizing the process of extending the protocol and increasing the speed of development. Users can then opt-in to using Second-Layer contracts by explicitly specifying such contracts when making transactions.

Several features were originally intended to be part of the Base Protocol, but were later moved into Second-Layer contracts. Moving these features from the Base Protocol to the Second-Layer had two positive side effects. Firstly, removing features from the Base Protocol made for less complexity and a smaller attack surface. Secondly, the Base Protocol was able to adopt a more general and extensible design, allowing faster iteration on new features.

In the next section, we look at a few different kinds of Second-Layer contracts and how they can be used to extend the functionality of the Base Protocol.

Second-Layer Contracts

Exchange Wrappers

Traders are able to use any decentralized exchange to open or close a margin position. This is done by wrapping a decentralized exchange in a simple smart contract called an Exchange Wrapper. Exchange Wrappers are able to execute trades on the exchange and provide a standard interface to the Margin Trading Protocol. Wrappable exchanges include 0x, Kyber, Bancor, ForkDelta, and Oasis. As more exchanges are built on Ethereum, a simple Exchange Wrapper can be written for each, allowing any trader to access the exchange’s liquidity.

When a position is opened or closed, the trader specifies the Exchange Wrapper contract that they wish to use along with any relevant data. This data may be any arbitrary data that the exchange requires in order to execute a trade, including specific order details (such as a 0x order) or a maximum-acceptable-price. After the trade is complete, the Base Protocol ensures that the received token amounts are acceptable to all parties. Because of this assurance, lenders are indifferent to the trader’s choice of exchange.

Lenders

While loans can be offered by single users, they can also be offered by smart contracts. This can allow for more complex logic, increased liquidity, and an easier user experience for both lenders and traders. One such contract could take deposits from multiple lenders, offering aggregated loans on their behalf. By controlling a collection of positions for multiple users, the contract can effectively manage risk to the lenders by holding positions with different risk profiles and offering variable interest rates based on trader demand. Pooling funds together also allows lenders to participate in larger loans without requiring a minimum deposit.

Price Oracles

Using Second-Layer contracts can also be used to enhance the margin-calling mechanism. For example, margin-calling could be restricted unless an oracle (or collection of oracles) indicates that the price has crossed a certain threshold. This would provide extra protection for traders, making margin-calling more predictable, and therefore making it more likely for them to take loans from lenders who offer such a protection in their loan offerings.

Tokenization

Second-Layer contracts can grant fractional ownership in a position. This allows Margin Tokens to be created, which increases liquidity for traders and simplifies the process of using the Margin Trading Protocol. Because such a contract is not part of the base protocol, new versions can be created and deployed freely, changing as new token standards emerge and the ecosystem evolves. For example, a different contract can tokenize positions according to the new ERC721 standard.

Upgrading The Base Protocol

All software must be maintained. While we believe that most enhancements can be built on the Second-Layer, the Base Protocol itself is not perfect. In the event that a new version of the Base Protocol is released by the dYdX team, all users will be able to opt-in to the new version, but cannot be forced to use it. The new protocol will not have the power to move users’ tokens until given explicit permission.

In the case that a serious bug or security vulnerability is found in the Base Protocol after release, the dYdX team retains a single special power:the ability to put the protocol into a close-only mode. If activated, this close-only mode would prevent any new positions from being created and would prevent any existing positions from being further increased. However, users would still be able to close existing margin positions, preventing them from losing their value. After placing the protocol into close-only mode, the bug would be fixed, and the patched version of the protocol would be deployed.

Conclusion

By building the protocol with Second-Layer contracts in mind, the power to upgrade the protocol is not given to any single party or even a collection of token-holders. It is given directly to users of the protocol, allowing them to opt-in to any contracts that they want to use.

We’re excited about the possibilities of Second-Layer smart contracts built on top of dYdX, allowing the protocol to be used even as new exchanges and new standards emerge on the Ethereum blockchain. If you want to dive in further, check out our GitHub!

If you’re interested in building state-of-the-art smart contracts and decentralized applications check out our job postings or reach out to us at jobs@dydx.exchange. We’re rebuilding the core of the world’s biggest financial market and are always looking for talented individuals to join the team!