Giter Site home page Giter Site logo

dydxprotocol / protocol_v1 Goto Github PK

View Code? Open in Web Editor NEW
200.0 200.0 53.0 4.55 MB

[DEPRECATED] Solidity Smart Contracts for the dYdX V1 Margin Trading Protocol

License: Apache License 2.0

JavaScript 54.48% Python 1.38% Solidity 43.92% Shell 0.15% Dockerfile 0.07%
ethereum solidity

protocol_v1's People

Contributors

antoniojuliano avatar brendanchou avatar jeremyschlatter avatar maxwolff avatar prettymuchbryce avatar richmcateer avatar wjmelements avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

protocol_v1's Issues

Generalize Exchange Contracts

We want to allow ShortSell to work with any decentralized exchange. To do so we are changing our public interface to support a bytes order argument which will be passed to the exchange wrapper contract. We will also add an address exchangeWrapperAddress which will allow any decentralized exchange wrapper contract to be used.

Test ShortSell Events

We should test that events are properly sent. Example from Open-Zeppelin

it('emits a burn event', async function () {
  const { logs } = await token.burn(tokenId, { from: sender });
  logs.length.should.be.equal(1);
  logs[0].event.should.be.eq('Transfer');
  logs[0].args._from.should.be.equal(sender);
  logs[0].args._to.should.be.equal(ZERO_ADDRESS);
  logs[0].args._tokenId.should.be.bignumber.equal(tokenId);
});

Make it possible to extract collateral from a short position if someone owns both sides of it

TODO(richmcateer): update this title and description as you see fit.

If someone is the lender and the seller for the same short, they should be able to cancel out both sides and just extract the baseToken that was locked up in the position.

If someone owns equal amount of tokens in the lender and seller positions for the same short, they should be able to burn both tokens to extract some portion of the baseToken if the lender and seller token contracts agree that this is okay.

Generalize Short Sellbacks

Right now the auction logic for closing shorts without short seller interaction is coded directly into the base protocol. In order to simplify and generalize the base protocol as much as possible, we want to move the auction logic into a second layer, as well as provide a general interface where many different types of contracts can be used to provide offers to sell back the underlying token owed by a short position.

The interface will look something like:

contract SellbackOfferProvider {
    function getSellbackOffer(bytes32 shortId, uint256 underlyingTokenAmount)
         returns (bool _hasOffer, uint256 _offer);
}

The offer returned by getSellbackOffer is the amount of base token the contract is willing to accept from the position in return for providing the full underlying token amount.

This issue will allow us to support all kinds of ways of automatically closing short positions in the future

Implement Shared Loan Positions

TODO(maxwolff): update this title and description as you see fit.

Implement smart contracts that control loan positions and allow people to own shares in a short position or allow other contracts to margin-call positions for you.

Remove unnecessary external calls

For example there are several calls in ShortSellRepo.sol

/**
 * NOTE: Currently unused, added as a utility for later versions of ShortSell
 */

I guess wee can keep these if we are using ShortSellRepo for V2, but we should at least consider removing them as an attack vector or as corruption (attack by the owners aka us) vector

Implement Delegated Loan Calls

We want to have the ability for external addresses to perform loan calls if authorized by the lender. In practice this will usually be lenders authorizing a relayer to perform loan calls on their behalf so they don't have to always be watching the price.

We'll implement this as a second layer contract external to the base protocol. The second layer smart contract will own the loan and will keep track of which addresses are authorized to call it. It will pass on any proceeds from the loan to the lender.

Remove SafetyDepositBox

Because we have decided to only support ERC20 tokens for V1, we no longer need SafetyDepositBox

Allow Smart Contracts to Make Loans

We want to allow smart contracts to be lenders for a loan. Right now each lender must sign their own loan offering. Because smart contracts cannot make signatures, smart contracts can't be lenders right now.

We need to separate lender into two fields: lender and signer. If nonzero then the signer will be the one that has the signature checked. We also need to implement an interface for smart contracts to approve loans if they are the lender.

This is a very similar problem to the one 0x is trying to solve with allowing smart contracts to be makers for an order. I've been talking to Will and Amir about the best ways to implement this.

Implement Delegated Loan Contract

One feature we want to have is the ability for external lenders to just deposit funds into a smart contract which we can then lend out on their behalf. This will allow us to offer a much simpler product.

We also must ensure that we aren't custodying the funds, but rather only have authorization to write loan offerings which pull from the funds locked in the smart contract. Some interest fee will be passed on to the external parties, and some will be taken by us.

We also need to decide if we want to include this in the V1 release.

Allow Delegated Short Closing

We want tokenized short to be a "pure 2nd-layer contract" that doesn't need any special permissions. This reduces the attack surface, the complexity of the protocol, the ways to close shorts, and the number of complex tests that need to be run.

Implementation:
If a user calls a close() function on ShortSell for a short for which they are not the seller, then assume the seller is a token contract and call an isVerified(user, amount) function on the token contract to verify that the user can close the short. If the user has enough tokens and the msg.sender to the isVerified function is the known ShortSell contract, then burn the tokens and allow the short to be closed by the user.

Handle Token Address Changes

There have been instances of tokens changing their address by migrating to a new contract. For example: https://medium.com/@AugurProject/serpent-compiler-vulnerability-rep-solidity-migration-5d91e4ae90dd

Normally, this requires exchanges and wallets to update their address for the token contract. This is easy for a centralized exchange, but it's not clear how it should operate for decentralized exchanges.

If something similar to this happened now, all REP stored in Vault for short positions would effectively be frozen forever. This is because Vault's internal accounting will still only account for the old token address, which will now be either worthless or unusable. The new version of REP would not be accounted for by Vault, so the REP would be locked (not associated with a position) forever

Get ShortSell deploy gas cost down

We're now right up against the block gas limit for deploying the ShortSell contract. This means we can't increase the bytecode size of ShortSell, or we won't be able to deploy (or even test) the contract

Update licenses

We should put a clear license at the top of our files and also ensure that we have not copied any code directly from files that contain licenses that would put our code in a legal bind.

To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Finalize Model for Changing External Contract Addresses

We should finalize our design for calling external contracts such as ShortSell, Proxy, Vault, etc.

We would like these to be:

  • Able to be changed by dYdX
    • So that we don't have to deploy all-new contracts on upgrade
    • So that we don't have to change client software to upgrade the protocol
  • Atomically changeable across all contracts
    • So that we don't have to submit multiple transactions to upgrade which could potentially create security vulnerabilities while the upgrade is halfway through
    • So that we don't forget to upgrade every single relevant contract
    • Because this is infeasible depending on the number of derivates contracts out on the blockchain
  • Have some delay for changing in a typical upgrade setting
    • To give users some trust that we won't instantly "pull the rug out from under them" and potentially inject some unwanted code upon them
  • Gas efficient to call
    • Having a master contract with these addresses would allow us to use one source of truth, but would require a ton of gas to make calls to

Slightly related, we should consider this in conjunction with our ability to pause the system in the case of security vulnerabilities.

Implement Tokenized Short Tokensales

We want to allow the ability to run simultaneous tokensale for a short token and loan for that short position. The tokensale for the short side will convert into a TokenizedShort, and the tokensale for the loan will convert into a TokenizedLoan

Implement General Loan Interest Rates

Right now the contracts only support linear interest rates. We want to be able to support any type of interest rate by allowing an external contract to be called to get the current interest fee

Test ShortSell functions

As of now, we need unit tests for the following ShortSell functions:

  • closeShort (The case where a short is partially closed)
  • callInLoan
  • cancelLoanCall
  • transferLoan
  • transferShort
  • placeSellbackBid
  • forceRecoverLoan
  • deposit
  • cancelLoanOffering

Figure out minimum-piece and rounding error issues

Right now we denominate options and shorts using ratios between the full amount of baseToken vs underLying token. This can introduce rounding errors when positions are opened or closed in a piecewise manner.

Should we have stricter limits on how orders can be defined and taken? These kinds of problems can cause unintended economic incentives for traders or security vulnerabilities.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.