dydxprotocol / protocol_v1 Goto Github PK
View Code? Open in Web Editor NEW[DEPRECATED] Solidity Smart Contracts for the dYdX V1 Margin Trading Protocol
License: Apache License 2.0
[DEPRECATED] Solidity Smart Contracts for the dYdX V1 Margin Trading Protocol
License: Apache License 2.0
Consider our attack surface and mark all public/external functions everything as nonReentrant if at all possible
To make it cheaper to deploy each individual TokenizedShort contract
Need unit tests for Vault
Due to proposals like ethereum/EIPs#223
Sending tokens may soon have a fallback function much like sending ETH.
We should support this functionality and thus prevent sending of tokens outside of a personal withdraw function
We want to make shorts and loans standard non fungible tokens to allow them to be easily adopted by wallets and exchanges
The current standard can be found here: ethereum/EIPs#841
Token standards like ethereum/EIPs#223 force contracts receiving funds to implement a tokenFallback
function, or the transfer will fail. We need to implement this on all of our contracts that receive funds
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.
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);
});
Add tests for tokenized shorts (TokenizedShort.sol)
Implement a way for the loan offering and shortsell to instantly assign the loan or the short to a specified address without an additional transaction.
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.
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
Interest fee is currently paid out in base token. We want to change it to be paid in underlying token
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.
We need this for writing complete tests and helping us to self-audit our code
We've decided to not allow the Owner of Proxy to authorize additional addresses
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
We want to change the interest rate on loan offerings to be compounded continuously. Right now it linearly increases from the start timestamp
Maybe limit fractions to be 2^127 instead of 2^128 will allow us to add fractions without casting down
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.
Because we have decided to only support ERC20 tokens for V1, we no longer need SafetyDepositBox
Uses the new ShortSellOwner interface to be a short sell owner that allows an account or a contract to close a position.
Need unit tests for ShortSellAuctionRepo
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.
We want to make maxDuration
on loan offering represent an absolute timestamp. Right now it represents the number of seconds from the start of the loan that it can remain open
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.
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.
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
0x has been aggregating improvement proposals into github issues:
https://github.com/0xProject/ZEIPs/issues
Almost all of these are relevant to dYdX as well. We should take a look at them all and consider which we want to implement for dYdX V1
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
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.
We should finalize our design for calling external contracts such as ShortSell, Proxy, Vault, etc.
We would like these to be:
Slightly related, we should consider this in conjunction with our ability to pause the system in the case of security vulnerabilities.
Using new ShortSellOwner
To verify after each close rather than just after the first close. Also to verify for payoutInHeldToken
being true
or false
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
Because we multiply the short amount by a uint128
when we calculate the interest fee we need to ensure that the shortAmount is <= 128 bits as well.
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
As of now, we need unit tests for the following ShortSell functions:
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.
Make CloseShortVerifier a more general interface to own short positions.
Include inheriting classes like ShortCloser and LoanCaller
Prevent hard-coding the update time for interest rounding
We need to have the ability to set a maximum duration on shorts/loans, after which the short can be closed.
Need unit tests for Trader
We want to allow short sellers to use loan offerings to add value to an existing short position
Need unit tests for ShortSellRepo
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.