Coder Social home page Coder Social logo

loopringsecondary / protocol Goto Github PK

View Code? Open in Web Editor NEW
227.0 63.0 62.0 2.19 MB

Loopring Protocol Smart Contract on Ethereum

Home Page: https://loopring.github.io/protocol

License: Apache License 2.0

JavaScript 4.86% TypeScript 92.57% Shell 2.36% CSS 0.21%
decentralized ethereum erc20 token exchange protocol

protocol's Introduction

Loopring Protocol Smart Contracts

Compile

If you are using Windows:

npm install --global --production windows-build-tools

Then run the following commands from project's root directory:

npm install
npm run compile

Deployment on Ethereum Mainnet:

Run Unit Tests

  • run npm run testrpc from project's root directory in terminal.
  • run npm run test from project's root directory in another terminal window.
  • run single test: npm run test -- transpiled/test/xxx.js

Run Unit Tests inside Docker

If you prefer to use docker, you can install docker first, then run the following:

npm run docker

If you do not have node/npm installed but still wish to use docker, you can run the commands manually:

docker-compose up --build --abort-on-container-exit
docker-compose logs -f test

The logs command is optional but will give you an easy to read output of the tests without the output from testrpc mixed in (though the combination of both is good for debugging and is why they're not being silenced.)

protocol's People

Contributors

akash2504 avatar benjaminprice avatar brechtpd avatar dong77 avatar fredrikoseberg avatar fxfactorial avatar hephyrius avatar jonasshen avatar kongliangzhong avatar prakal avatar rainydio avatar xiaowheat 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  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

protocol's Issues

Token interface refine

Design a interface compatible with all tokens(ERC20, ERC223, and so on) with minimal amount of functions. And refine TokenRegistry contract.

Introduce WalletRegistry and RelayRegistry

Currently we need to put wallet's address and relay's address to collect fees, we can avoid this and make order byte-size smaller by use these registries so each wallet and relay can have a pre-defined addresses for signing and receiving fees.

Secondary Fee Model

Motivation

Almost all ICO projects have the desire of 1) adding more value to their issued tokens and 2) creating more demand for their tokens. I propose a Secondary Fee Model that can be added to Loopring Protocol 1.1 or 2.0 to give these projects better reasons to adopt Loopring to trade their tokens.

Overview

I propose a FeeReimbursePoliciesContract (or FRPC) that allows an ICO project (who issued token XYZ) to create one or more policies — the address that used to create a policy is called the policer owner. 

Here are some details about a policy:

  • it locks X LRC up to N blocks.
  • it can specify that if an address is to buy token XYZ of amount B, AND if the miner decided to take LRC as fee, then the corresponding policy owner will pay my% (m > 1) LRC for the trading address until the deposited LRC is exhausted. As a result, the trading address only has to pay 1-y% LRC as fee. FRPC will provide a way of specifying how y is calculated based on B. This policy encourages people to buy XYZ token with less LRC fee.
  • It can also specify that if an address is to do any token trading, as long as the address hold H amount of XYZ , AND if the miner decided to take LRC as fee, then the corresponding policy owner will pay mz% (m > 1) LRC for the trading address until the deposited LRC is exhausted, and the trading address only pays 1-z% LRC as fee. There will be a way of specifying how z is calculated based on H. This policy encourage people to hold XYZ token.
  • It should allow last two rules co-exist.

Note that a policy owner needs to pay my% or mz% LRC to the ring miner instead of y% or z%. This is because applying policies will consume more gas so the extra LRC will be required to compensate this additional cost. The multiplier m should also be configurable by policy owners.

Loopring ring-miners will decide if and what policies to apply for a ring, as for any single token, there may be multiple policies available. Miner only takes the best ones for the most profit.

From the user’s perspective, holding XYZ token or buying XYZ token eliminate part or even all the LRC trading fee.

Move order definition to impl file

The struct Order is not part of the implementation, we may need to move it to the implementation file. We can also move most of the constant values into the implementation file or even delete them and use local instances inside methods to save gas. We only need to document those constants clearly.

Different scaling logic in LRC fee calculation between calculateOrderFillAmount and scaleRingBasedOnHistoricalRecords

in calculateOrderFillAmount, LRC fee is calculated with reference to amountS:

    if (state.order.buyNoMoreThanAmountB) {
            if (fillAmountB > state.order.amountB) {
                fillAmountB = state.order.amountB;

                state.fillAmountS = fillAmountB.mul(
                    state.rate.amountS
                ) / state.rate.amountB;

                newSmallestIdx = i;
            }
        }

        state.lrcFee = state.order.lrcFee.mul(
            state.fillAmountS
        ) / state.order.amountS;

while in scaleRingBasedOnHistoricalRecords, it is calculated with reference to amountS or amountB based on the value of buyNoMoreThanAmountB:

            if (order.buyNoMoreThanAmountB) {
                amount = order.amountB.tolerantSub(
                    cancelledOrFilled[state.orderHash]
                );

                order.amountS = amount.mul(order.amountS) / order.amountB;
                order.lrcFee = amount.mul(order.lrcFee) / order.amountB;

                order.amountB = amount;
            } else {
                amount = order.amountS.tolerantSub(
                    cancelledOrFilled[state.orderHash]
                );

                order.amountB = amount.mul(order.amountB) / order.amountS;
                order.lrcFee = amount.mul(order.lrcFee) / order.amountS;

                order.amountS = amount;
            }

Enable safe two-party trading

Enable safe two-party trading

If two parties want to make a trade based on a price/rate that had been negotiated and agreed upon directly, they can create two orders, then one party A can give his/her order to party B, using text message or email, for example. Party B can create a ring of these orders then submit it to Loopring smart contracts for settlement.

The problem is that this ring can be intercepted before this Ethereum transaction is mined by miners. Once stolen, the ring can be broken into two orders which can be re-matched with other orders in the ring.

The problem is obvious if both parties' orders are the same size in value. (10 X -> 2Y), (2Y -> 10X) for example. If stolen, both of them might only get partially filled, this is not expected by either party.

Optimization: remove salt from orders

The salt was introduced to make sure if all other parameters are the same, orders can still have different hashes. Now that we have ‘timpestamp’ field, we can use it to make sure orders with the same parameters can have different hashes. If the unit of ‘timestamp’ is second, we can append change it to milliseconds so the ‘mill’ part can act as the salt.

Enable batch register ringhashes

If a relay is performing well, it may find several rings quickly. We should enable ring-miners to submit the hash of multiple rings in one tx to save gas. If any ringhash fails to submit, the rest shouldn't be affected.

fee calculation adjustment

If an address doesn't have any LRC but will receive LRC as a result of trading, paying LRC fee should also succeed in most cases.

New fee payment model

Do not transfer fee to miner or wallet in loopring protocol, instead, keep the fee for each miner/wallet in another contract, and miner/wallet can initiate a withdrawal any time.

Enable submitting multiple rings in one trasaction.

Enable submitting multiple rings in one transaction

The idea is to enable more trades in one Ethereum transaction. In order to achieve this, the protocol contracts need to be tolerant with invalid rings — if one or more rings are invalid the rings that follow will still be verified and settled.

This will make smart contract more error-prone, I would suggest this goes into future release.

Wallet get a percentage of mining income.

The current design of Loopring has a nice incentive mechanism for ring-miners. But it doesn't really offer any reward for wallets and website that help user to manage their orders.

We can provide such an incentive mechanism, by allowing wallet to supply an address in the order to split the fee or margin-split with miners. The percentage of LRC or margin-split should be configurable upon deployment.

Allow orders to be only completely matched

Allow orders to be only completely matched

It is reasonably for users to request his/her orders to be only fully matched or not to be matched at all. Mathematically most orders cannot be matched fully - centralized exchanges usually have rounding-up calculation for very small units. But smart contracts is very accurate in calculation. Therefore the practical solution might be allowing user to specify that his order must be matched x% of the total/original size where x == 99. Or we can even allow user to specify this x value.

Implement logc to prevent ring from being stolen

We should allow ring-miners to submit a ring-fingerprint before submitting a ring. THe finger-print should be order-indenpendent, i.e, A ring X->Y->Z should have the same fingerprint as ring Y->Z->X.

add `cancelAllOrdersForTradingPair` functionality

Currently we have a setCutoff method, this is essentially to cancel all orders whose timestamp is less than the current timestamp. We need to enable user to cancel all orders for specific trading pairs.

We will need to rename setCutoff to cancelAllOrders

A possible feature that loopring should consider to have

Dear loopring development team,

This might not be very appropriate to be raised as an issue, you may ignore and delete this if you think it is.

So far the project is under development quite well, but the work so far is about ERC20 token exchange, have you ever considered about Ether to be one of the coins that can be included in loopring exchange protocol? Please kindly suggest as the market demands for exchange between Ether and other ERC20 tokens are really out there and take the majority part in daily token trading volume. Hope all go well with loopring development.

Best Regards,
John

Write batch register token script

This script should pass an input string in form of:

0x2956356cD2a2bf3202F771F50D3D14A367b48070  ERC20 18  WETH    Ether Token
0xEF68e7C694F40c8202821eDF525dE3782458639f  ERC20 18  LRC     Loopring
0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0  ERC223 18  EOS     EOS

and generate geth console command lines. Please create a script directory.

Define events in the interface?

Is it better to define the standard events in the interface?

Events:

  • RingMined
  • OrderFilled
  • OrderCancelled
  • CutoffTimestampChanged

Support a fee discount parameter for each order.

The idea is to enable ring miners to decide if they would like to give an order a fee discount based on certain criteria, for example, the balance of token XYZ in their address. Protocol wont' care why the discount is given, the decision is for the miners off-chain.

Remove `_time` and `_blocknumber` from events

Possible to remove it from the event logs as they're accessible from the transaction recipients.

Pros:

  • Conciseness
  • Less gas consumption

Cons:

  • Indirect data access from the UI perspective

TokenRegistry's unregisterToken need refractory

This unregisterToken now takes O(n) time. We really need to change it to O(1) otherwise when the list is too long, we'll eventually run out of gas before a token near the end of the list can be unregistered.

We will probably support thousands of tokens in the future.

Allow user to authorize and de-authorize each version of the protocol

Currently the only authorization a user has to do is setting up allowance that TokenTransferDelegate can leverage. When we added new versions, all of them will inherit the capability of spending money that was previous authorized. If one version is hacked, the all people's money is at risk.

We should consider allowing each address to authorize and de-authorize new versions of the protocol.

Use a uint256 to encapsulate various Order/Ring parameters

buyNoMoreThanAmountB, marginSplitPercentage, feeSelectionList can be put into a uint256:

  • 1-7 bits: marginSplitPercentage
  • 8th bit: buyNoMoreThanAmountB
  • 9-15 bits: minimalFillPercentage
  • 16th bit: feeSelection

There are more bits available for new features such as those in #130

TokenRegistry need to support a ERC223 token

Currently this contract only ERC20 token registration. We need to add a 'standard' property for each token and return that property upon query.

The looping protocol will need to instantiate either an ERC20 or an ERC223 contract to interact with the token contract.

TokenTransferDelegate can be refactored

I would recommend to use an array to save all the protocol versions in TokenTransferDelegate. The order in which versions are saved in the array doesn't matter, as long as we have a version label in the struct.

getLatestAuthorizedAddresses should be unnecessary - we are unlikely to register more than 100 versions. If we do in the long term, it is possible that we have to improve this TokenTransferDelegate contract as well and deploy a new incompatible version, then we start from clean.

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.