Loopring: A Decentralized Token Exchange Protocol - GitHub

Transcription

Loopring:A Decentralized Token Exchange ProtocolDaniel Wangdaniel@loopring.orgJay Zhoujay@loopring.orgAlex Wangalex@loopring.orgMatthew orgSeptember 8, 2018AbstractLoopring is an open protocol for building decentralized exchanges. Loopring operates as a public set of smartcontracts responsible for trade and settlement, with an off-chain group of actors aggregating and communicating orders.The protocol is free, extensible, and serves as a standardized building block for decentralized applications (dApps) thatincorporate exchange functionality. Its interoperable standards facilitate trustless, anonymous trading. An importantimprovement over current decentralized exchange protocols is the ability for orders to be mix-and-matched with other,dissimilar orders, obviating the constraints of two-token trading pairs and drastically improving liquidity. Loopringalso employs a unique and robust solution to prevent front-running: the unfair attempt to submit transactions into ablock quicker than the original solution provider. Loopring is blockchain agnostic, and deployable on any blockchainwith smart contract functionality. At the time of writing, it’s operable on Ethereum [1] [2] and Qtum [3] with NEO [4]under construction.1Introductionit fails to uphold the virtues these decentralized projectsespouse. There are also numerous practical risks and limitations in using centralized exchanges which are describedbelow. Decentralized exchanges (DEXs) [7] [8] [9] havesought to address these issues, and in many cases havesucceeded in alleviating security risks by using blockchainsfor disintermediation. However, as DEX capability becomescrucial infrastructure for the new economy, there is substantial room for performance improvement. Loopring aims toprovide modular tools for said infrastructure with its dAppagnostic open protocol.With the proliferation of blockchain-based assets, the needto exchange these assets amongst counterparties has significantly increased. As thousands of new tokens are introduced- including the tokenization of traditional assets - this needis magnified. Whether exchanging tokens for speculativetrading motivations, or converting to access networks viatheir native utility tokens, the ability to exchange one cryptoasset for another is foundational for the larger ecosystem.Indeed, there is a potential energy in assets [5], and realizingthis energy - unlocking capital - requires not only assertingownership, which blockchains have immutably allowed for,but the ability to freely transfer and transform these assets.As such, the trustless exchange of tokens (value) is acompelling use case for blockchain technology. Until now,however, crypto enthusiasts have largely settled for tradingtokens on traditional centralized exchanges. The Loopringprotocol is needed because, just as Bitcoin [6] dutifullyemphasized that, in regards to peer-to-peer electronic cash,“the main benefits are lost if a trusted third party is stillrequired to prevent double-spending”, so too are the mainbenefits of decentralized assets lost if they must pass throughtrusted, gated, centralized exchanges.Trading decentralized tokens on centralized exchangesdoesn’t make sense from a philosophical perspective, as22.1Current Exchange LandscapeInadequacies of Centralized ExchangesThe three primary risks of centralized exchanges are; 1) Lackof security, 2) Lack of transparency, and 3) Lack of liquidity.Lack of Security arises from users typically surrendering control of their private-keys (funds) to one centralizedentity. This exposes users to the possibility that centralizedexchanges fall prey to malicious hackers. The security andhacking risks facing all centralized exchanges are well known[10] [11], yet are often accepted as “table stakes” for tokentrading. Centralized exchanges continue to be honeypots for1

hackers to attack as their servers have custody over millions 2.2 Inadequacies of Decentralized Exof dollars of user funds. Exchange developers can also makechangeshonest, accidental errors with user funds. Simply, usersare not in control of their own tokens when deposited at Decentralized exchanges differ from centralized exchangesin part because users maintain control of their private-keysa centralized exchange.(assets) by performing trades directly on the underlyingLack of Transparency exposes users to the risk of blockchain. By leveraging the trustless technology of crypdishonest exchanges acting unfairly. The distinction here is tocurrencies themselves, they successfully mitigate many ofby the exchange operator’s malicious intentions, as users are the abovementioned risks surrounding security. However,not truly trading their own assets on centralized exchanges, problems persist in regards to performance and structuralbut rather, an IOU. When tokens are sent to the exchange’s limitations.wallet, the exchange takes custody, and offers an IOU in itsLiquidity often remains an issue as users must searchplace. All trades are then effectively between users’ IOUs. for counterparties across disparate liquidity pools and stanTo withdraw, users redeem their IOU with the exchange, dards. Fragmented liquidity effects are present if DEXsand receive their tokens to their external wallet address. or dApps at large don’t employ consistent standards toThroughout this process there is a lack of transparency, interoperate, and if orders are not shared/propagated acrossand the exchange can shutdown, freeze your account, go a wide network. The liquidity of limit order books, and,bankrupt, etc. It is also possible that they use user assets specifically, their resiliency – how fast filled limit ordersfor other purposes while in custody, such as lending them are regenerated – can significantly affect optimal tradingout to third parties. Lack of transparency can cost users strategies [13]. The absence of such standards has resultedwithout a total loss of funds, such as in higher trading fees, not only in reduced liquidity, but also exposure to an arraydelays at peak demand, regulatory risk, and orders being of potentially insecure proprietary smart contracts.front ran.Furthermore, since trades are performed on chain, DEXsinherit the limitations of the underlying blockchain, namely:Lack of Liquidity. From the point of view of exchangescalability, delays in execution (mining), and costly modifioperators, fragmented liquidity inhibits entry by new excations to orders. Thus, blockchain order books do not scalechanges because of two winner-takes-all scenarios. First, theparticularly well, as executing code on the blockchain incursexchange with the greatest number of trading pairs wins,a cost (gas), making multiple order-cancellation cadencesbecause users find it desirable to conduct all their trades onprohibitively expensive.one exchange. Second, the exchange with the largest orderFinally, because blockchain order books are public, thebook wins, because of favorable bid-ask spreads for eachtransaction to place an order is visible by miners as it awaitstrading pair. This discourages competition from newcomersbeing mined into the next block and placed into an orderbecause it is difficult for them to build up initial liquidity.book. This delay exposes the user to the risk of being frontAs a result, many exchanges command a high market sharerun and having the price or execution move against him.despite user complaints and even major hacking incidents.It’s worth noting that as centralized exchanges win market2.3 Hybrid Solutionsshare, they become an ever-larger hacking target.For the above reasons, purely blockchain-based exchangeshave limitations that make them uncompetitive with centralized exchanges. There is a tradeoff between on-chaininherent trustlessness, and centralized exchange speed andorder flexibility. Protocols such as Loopring and 0x [14]extend a solution of on-chain settlement with off-chain ordermanagement. These solutions revolve around open smartcontracts, but navigate scalability limitations by performingseveral functions off-chain and giving nodes flexibility infulfilling critical roles for the network. However, drawbacksremain for the hybrid model as well [15]. The Loopringprotocol proposes meaningful differences in our approach toa hybrid solution throughout this paper.From the point of view of users, fragmented liquiditysignificantly reduces user experience. In a centralized exchange, users are only able to trade within the exchange’sown liquidity pools, against its own order book, and between its supported token pairs. To trade token A fortoken B, users must go to an exchange that supports bothtokens or register at different exchanges, disclosing personalinformation. Users often need to execute preliminary orintermediate trades, typically against BTC or ETH, payingbid-ask spreads in the process. Finally, the order books maynot be deep enough to complete the trade without materialslippage. Even if the exchange purports to process largevolumes, there is no guarantee that this volume and liquidityis not fake [12].The result is disconnected silos of liquidity and a frag- 3Loopring Protocolmented ecosystem that resembles the legacy financial system, with significant trading volume centralized on few Loopring is not a DEX, but a modular protocol for buildingexchanges. The global liquidity promises of blockchains hold DEXs on multiple blockchains. We disassemble the compono merit within centralized exchanges.nent parts of a traditional exchange and offer a set of public2

of 3010 3.00A. In the case of fixing token B as reference,we say that Alice is selling 15 token A for the price of415 0.26666667B and Bob is buying 10 token A for theprice of 1030 0.33333334B. Hence, who’s the buyer or selleris arbitrary.In the first situation Alice is willing to pay a higherprice(3.75A) than the price Bob is selling his tokens for3.1 Order Ring(3.00A), while in the second situation Bob is willing to pay aLoopring orders are expressed in what we call a Unidirec- higher price (0.33333334B) than the price Alice is selling hertional Order Model (UDOM)[16]. UDOM expresses orders tokens for (0.26666667B). It is clear that a trade is possibleas token exchange requests, amountS/amountB, (amount to whenever the buyer is willing to pay an equal or higher pricesell/buy) instead of bids and asks. Since every order is just than the seller’s price.an exchange rate between two tokens, a powerful feature of101515 10the protocol is the mixing and matching of multiple orders in430 (1)304 4 · 30 1.25 1circular trade. By using up to 16 orders instead of a single1015trading pair, there is a dramatic increase in liquidity andThus, for a set of n orders to be able to be filled, fully orpotential for price improvement.partially, we need to know if the product of each one of thesmart contracts and decentralized actors in its place. Theroles in the network include wallets, relays, liquidity-sharingconsortium blockchains, order book browsers, Ring-Miners,and asset tokenization services. Before defining each, weshould first understand Loopring orders.ORDER#2owner: YamountS: 9BamountB: 12C8BORDER#1owner: XamountS: 10000AamountB: 2B7898Aexchange rates as buy orders results in a number greater orequal to 1. If so, all the n orders can be either partially, ortotally filled [17].If we introduce a third counterparty, Charlie, such thatAlice wants to give x1 token A and receive y1 token B,Bob wants to give x2 token B and receive y2 token C, andCharlie wants to give x3 token C and receive y3 token A. Thenecessary tokens are present, and the trade is possible if:98CORDER#3owner: ZamountS: 100CamountB: 160AFigure 1: An order-ring of 3 ordersx1 · x2 · x3The above figure shows an order-ring of 3 orders. Each 1(2)y1 · y2 · y3order’s token to sell (tokenS) is another order’s token toSee section 7.1 for more details about Loopring’s orders.buy (tokenB). It creates a loop that allows each order toexchange their desired tokens without requiring an opposingorder for its pair. Traditional order pair trades can, of 4Ecosystem Participantscourse, still be executed, in what is essentially a special caseof an order-ring.The following ecosystem participants jointly provide allfunctionalities a centralized exchange has to offer.Definition 3.1 (order-ring) Let C0 , C1 , · · · , Cn 1 be n Wallets: A common wallet service or interface thatdifferent tokens, O0 1 , · · · , Oi i 1 , · · · , On 1 0 be ngives users access to their tokens and a way to sendorders. Those orders can form a order-ring for trading:orders to the Loopring network. Wallets will beO0 1 · · · Oi i 1 · · · On 1 0 ,incentivized to produce orders by sharing fees withring-miners (see section 8). With the belief that thewhere n is the length of the order-ring, and i 1 i 1future of trading will take place within the safety ofmod n.individual user’s wallets, connecting these liquiditypools through our protocol is paramount.An order-ring is valid when all component transactionscan be executed at an exchange rate equal to or better than Consortium Liquidity Sharing Blockchain/Relaythe original rate specified implicitly by the user. To verifyMesh: A relay-mesh network for order & liquidityorder-ring validity, Loopring protocol smart contracts mustsharing. When nodes run Loopring relay software,receive order-rings from ring-miners where the product ofthey are able to join an existing network andthe original exchange rates of all orders is equal to or greatershare liquidity with other relays over a consortiumthan 1.blockchain.The consortium blockchain we areLet’s assume Alice and Bob want to trade their tokenbuilding as a first implementation has near real timeA and B. Alice has 15 token A and she wants 4 token B fororder sharing (1-2 second blocks), and trims oldthem; Bob has 10 token B and he wants 30 token A for them.history to allow for faster download by new nodes.Who is buying and who is selling? This depends onlyNotably, relays need not join this consortium; theyon the asset we fix to give price quotations. If token A iscan act alone and not share liquidity with others, or,the reference, then Alice is buying token B for the price ofthey can start and manage their own liquidity sharing15 43

Relays/Ring-Miners: Relays are nodes that receive orders from wallets or the relay-mesh, maintainpublic order books and trade history, and optionallybroadcast orders to other relays (via any arbitraryoff-chain medium) and/or relay-mesh nodes. Ringmining is a feature – not a requirement – of relays.It is computationally heavy and is done completelyoff-chain. We call relays with the ring-mining featureturned on “Ring-Miners”, who produce order-rings bystitching together disparate orders. Relays are free in(1) how they choose to communicate with one another,(2) how they build their order books, and (3) how theymine order-rings (mining algorithms).order books to be built in a certain way, such as firstcome-first-serve. Instead, relays have the power tomake their own design decisions in building their orderbooks.4. Liquidity Sharing: Relays broadcast the order toother relays through any arbitrary communicationmedium. Once again, there is flexibility how/whethernodes interact. To facilitate a certain level of networkconnectivity, there is a built-in liquidity sharing relaymesh using a consortium blockchain. As mentionedin the prior section, this relay-mesh is optimized forspeed and inclusivity. Loopring Protocol Smart Contracts (LPSC):A set of public and free smart contracts that checksorder-rings received from ring-miners, trustlessly settles and transfers tokens on behalf of users, incentivizesring-miners and wallets with fees, and emits events.Relays/order browsers listen to these events to keeptheir order books and trade history up to date. Seeappendix ? for details.ORDER 1owner: XamountS: 10000 AamountB: 2 BaccountX8BORDER 2owner: YamountS: 9 BamountB: 12 C2user Y1accountY7898 Auser ZaccountZ6relay MaccountM98 CORDER 3owner: ZamountS: 100 CamountB: 160 A Asset Tokenization Services (ATS): A bridgebetween assets that cannot be directly traded onLoopring. They are centralized services run by trustworthy companies or organizations. Users depositassets (real, fiat or tokens from other chains) and gettokens issued, which can be redeemed for the depositin the future. Loopring is not a cross-chain exchangeprotocol (until a suitable solution exists), but ATSenable trading of ERC20 tokens [18] with physicalassets as well as assets on other blockchains.5user XFeeshare liquidity3settlement4relay NaccountNring-miningORDER 1owner: XamountS: 10000 AamountB: 2 BORDER 2owner: YamountS: 9 BamountB: 12 CORDER 3owner: ZamountS: 100 CamountB: 160 AExchange Process1. Protocol Authorization: In figure 2, user Y whowants to exchange tokens authorizes the LPSC tohandle amountS of token B the user wants to sell. Thisdoes not lock the user’s tokens, who remains free tomove them while the order is processed.5submitRingLPSCblockchainFigure 2: Loopring Exchange Process2. Order Creation: The current rate and order bookfor token B vs token C, are provided by relays orother agents hooked up to the network, such as orderbook browsers. User Y places an order (limit order)specifying amountS and amountB and other parametersthrough any integrated wallet interface. An amount ofLRx can be added to the order as a fee for ring-miners;higher LRx fee means a better chance to be processedearlier by ring-miners. The order’s hash is signed withuser Y’s private-key.5. Ring-Mining (Order Matching): Ring-miners tryto fill the order fully or partially at the given exchangerate or better by matching it with multiple other orders. Ring-mining is the main reason why the protocolis able to provide high liquidity over any pair. If theexecuted rate is better than what user Y specified,margin is shared amongst all orders in the order-ring.As a reward, the ring-miner chooses between claimingpart of the margin (Margin-Split, and giving back theLRx to the user), or simply keeping the LRx fee.3. Order Broadcast: The wallet sends the order andits signature to one or more relays. Relays updatetheir public order book. The protocol doesn’t require6. Verification & Settlement: The order-ring is received by LPSC. It makes multiple checks to verifythe ring-miner supplied data and determines if the4

order-ring can be settled fully or partially (depending 7Protocol Specificationon the fill rate of orders in-ring and tokens in users’wallets). If all checks are successful, the contract 7.1 Anatomy of an Orderatomically transfers the tokens to users and pays thering-miner and wallet fees at the same time. If user An order is a pack of data that describes the intent of theY’s balance as determined by the LPSC is insufficient, user’s trade. A Loopring order is defined using the Uniit will be considered scaled-down: a scaled-down Directional Order Model, or UDOM, as follows:order will automatically scale up to its original sizemessage Order {if sufficient funds are deposited to its address, unlikeaddress protocol;a cancellation, which is a one way manual operationaddress owner;and cannot be reversed.address tokenS;address tokenB;uint256 amountS;6 Operational Flexibilityuint256 amountB;unit256 lrcFeeIt’s important to note that Loopring’s open standard allowsunit256 validSince; // Seconds since epochparticipants significant flexibility in how they operate. Acunit256 validUntil; // Seconds since epochtors are free to implement novel business models and provideuint8marginSplitPercentage; // [1-100]value for users, earning LRx fees on volume or other metricsboolbuyNoMoreThanAmountB;in the process (if they so choose). The ecosystem is modularuint256walletId;and meant to support participation from a multitude of//Dual-Authoringaddressapplications.address authAddr;// v, r, s are parts of the signature6.1 Order Bookuint8v;bytes32 r;Relays can design their order books in any number of waysbytes32 s;to display and match users’ orders. A first implementation// Dual-Authoring private-key,of our own order book follows an OTC model, where limit// not used for calculating order’s hash,orders are positioned based on price alone. Timestamps of// thus it is NOT signed.orders, in other words, have no bearing on the order book.string authKey;However, a relay is free to design their order book in such auint256 nonce;way as to emulate a typical centralized exchange’s matching}engine, where orders are ranked by price, while respectingtimestamps as well. If a relay was inclined to offer this typeTo ensure the origin of the order, it is signed againstof order book, they can own/integrate with a wallet, and the hash of its parameters, excluding authAddr, with thehave those wallet orders sent solely to the single relay, who user’s private-key. The authAddr parameter is used forwould then be able to match orders based on time. Any signing order-rings that this order is part of, which preventssuch configuration is possible.front-running. Please reference section 9.1 for more details.Whereas other DEX protocols at times require Relays The signature is represented by the v, r, and s fields, andto have resources - initial token balances to place taker is sent alongside the order parameters over the network.orders - Loopring Relays need only find matchable orders to This guarantees the order stays immutable during its wholeconsummate a trade, and can do so without initial tokens. lifetime. Even though the order never changes, the protocol6.2can still compute its current state based on the balance ofits address along with other variables.UDOM doesn’t include a price (which must be a floatingpoint number by nature), but, instead uses the term rate orr, which is expressed as amountS/amountB. The rate is nota floating-point number but an expression that will only beevaluated with other unsigned integers on demand, to keepall intermediate results as unsigned integers and increasecalculation accuracy.Liquidity SharingRelays are free to design how they share liquidity (orders)with each other. Our consortium blockchain is but one solution to accomplish this, and the ecosystem is free to networkand communicate as they wish. Besides joining a consortiumblockchain, they can build and manage their own, creatingrules/incentives as they see fit. Relays can also work alone,as seen in the time-sensitive wallet implementation. Ofcourse, there are clear advantages in communicating with 7.1.1 Buy Amountsother Relays in pursuit of network effects, however, differentbusiness models could merit peculiar sharing designs and When a ring-miner ring-matches orders, it’s possible thatsplit fees in any number of ways.a better rate will be executable, allowing users to get5

more tokenB than the amountB they specified. However, if buyNoMoreThanAmountB is set to True, the protocol ensures users receive no more than amountB oftokenB. Thus, UDOM’s buyNoMoreThantokenB parameterdetermines when an order is considered completely filled.buyNoMoreThantokenB applies a cap on either amountS oramountB, and allows users to express more granular tradeintentions than traditional buy/sell orders.For example: with amountS 10 and amountB 2, therate r 10/2 5. Thus the user is willing to sell 5 tokenSfor each tokenB. The ring-miner matches and finds the usera rate of 4, allowing the user to receive 2.5 tokenB insteadof 2. However, if the user only wants 2 tokenB and set thebuyNoMoreThanAmountB flag to True, the LPSC performsthe transaction at a rate of 4 and the user sells 4 tokenS foreach tokenB, effectively saving 2 tokenS. Keep in mind thisdoes not take into account mining fees (See section 8.1).Indeed, if we use7.2.1Sub-Ring CheckingThis step prevents arbitrageurs from unfairly realizing allthe margin in an order-ring by implementing new orderswithin it. Essentially, once a valid order-ring is found by aring-miner, it could be tempting to add other orders to theorder-ring to fully absorb the users’ margin (rate discounts).As illustrated by figure 3 below, carefully calculated x1, y1,x2 and y2 will make the product of all orders’ rate be exactly1 so there will be no rate discount.ORDER 2owner: YamountS: 9BamountB: antokenB)ORDER 1owner: XamountS: 10000 AamountB: 2 BORDER 3owner: ZamountS: 100 CamountB: 160 AORDER 5owner: addressMamountS: x2 CamountB: y2 AORDER 4owner: MamountS: x1 AamountB: y1 BFigure 3: An order-ring with sub-ringThis is zero-risk, zero-value add to the network, and isconsidered unfair conduct by the ring-miner. To preventto represent an order in a simplified form, then for this, Loopring requires that a valid loop cannot contain anyETH/USD markets on a traditional exchange, traditional sub-rings. To check this, the LPSC ensures a token cannotbuy-sell modeling can express the 1st and the 3rd order be in a buy or sell position twice. In the above diagram, wecan see that token A is a sell token twice and a buy tokenbelow, but not the other two:twice, which would be disallowed.1. Sell 10 ETH at price of 300 USD/ETH. This order canexpressed as: Order(10, ETH, 3000, USD, False). 7.2.2Fill Rate CheckingThe exchange rate calculations in the order-ring are madeby ring-miners for reasons stated above. It is the LPSCthat must verify they’re correct. First, it verifies that thebuy rate the ring-miner can execute for each order is equalto or less than the original buy rate set by the user. This3. Buy 10 ETH at price of 300 USD/ETH, This order can ensures the user gets at least the exchange rate they askedexpressed as: Order(3000, USD, 10, ETH, True).for or better on the transaction. Once the exchange ratesare confirmed, the LPSC ensures that each order in the4. Spend 3000 USD to buy as many ETH as possible at order-ring shares the same rate discount. For instance, ifprice of 300 USD/ETH, This order can expressed as: the discounted rate is γ, then the price for each order willbe:Order(3000, USD, 10, ETH, False).r0 1 · (1 γ), r1 2 · (1 γ), r2 0 · (1 γ), and satisfy:2. Sell ETH at price of 300 USD/ETH toget 3000 USD. This order can expressed as:Order(10, ETH, 3000, USD, True).7.2r0 1 · (1 γ) · r1 2 · (1 γ) · r2 0 · (1 γ) 1Ring Verification(3)The Loopring Smart Contracts do not perform exchange hence:1.(4)γ 1 rate or amount calculations, but must receive and verify3r0 1 · r1 2 · r2 0what the ring-miners supply for these values. These calculations are done by ring-miners for two main reasons: If the transaction crosses n orders, the discount is:(1) the programming language for smart contracts, such as1solidity[19] on Ethereum, does not have support for floatingγ 1 qQ,(5)n 1 inpoint math, especially pow(x, 1/n) (calculating the n-thri 0root of a floating point number), and (2) it is desirable forwhere ri is the order turnover rate of i-th order. Obvithe computation to be made off-chain to reduce blockchainously, only when the discount rate is γ 0, can these orderscomputation and cost.6

be filled; and the i-th order (Oi )’s actual exchange rate isrˆi ri · (1 γ), rˆi ri .During implementation we can safely assume any orderin the order-ring to have the lowest value, then iteratethrough the order-ring at most twice to calculate eachorder’s fill volume.Example: If the smallest amount to be filled compared tothe original order is 5%, all the transactions in the order-ringare scaled down to 5%. Once the transactions are completed,the order that was considered to have the smallest amountremaining to be filled should be completely filled.Recall our prior example where Alice has 15 token A andwants 4 token B for them, Bob has 10 token B and wants 30token A for them. If token A is the reference, then Alice isbuying token B for 154 3.75A, while Bob is selling token B150for 30 3.00A.Tocalculatethe discount: 120 1.25 thus1012 0.8 (1 γ).Thustheexchangeratethatrenders1.25 the trade equitable for both parties is 0.8 · 3.75 3.3541token A per token B.Bob gives 4 token B and receives 13.4164 token A, morethan the 12 he was expecting for those 4 tokens. Alicereceives 4 token B as intended but gives only 13.4164 token Ain exchange, less than the 15 she was willing to give for those4 tokens. Note, a portion of this margin will go towardspaying fees to incentivize miners (and wallets). (See section8.1).7.3Ring SettlementIf the order-ring fulfills all the previous checks, the order-ringcan be closed, and transactions can be made. This meansthat all n orders form a closed order-ring, connected as infigure 4:O37.2.3Fill Tracking & CancellationA user can partially or fully cancel an order by sendinga special transaction to the LPSC, containing the detailsabout the order and the amounts to cancel. The LPSC takesthat into account, stores the amounts to cancel, and emitsan OrderCancelled event to the network. The LPSC keepstrack of filled and cancelled amounts by storing their valuesusing the order’s hash as an identifier. This data is publiclyaccessible and OrderCancelled / OrderFilled events areemitted when it changes. Tracking these values is criticalfor the LPSC during the order-ring settlement step.LPSC also supports cancelling all orders for any tradingpair with the OrdersCancelled event and cancelling allorders for an address with the AllOrdersCancelled event.7.2.4O2O4O1O5OnFigure 4: Ring SettlementTo make the transactions, the LPSC uses theTokenTransferDelegate smart contract. The introductionof such a delegate makes upgrading the protocol smartcontract easier as all orders only need to authorize thisdelegate instead of different versions of the protocol.For each order in the order-ring, a payment of tokenSis made to the next or the previous order depending on theimplementation. Then the ring-miner’s fee is paid dependingon the fee model chosen by the ring-miner. Finally, once allthe transactions are made, a RingMined

on the asset we x to give price quotations. If token A is the reference, then Alice is buying token B for the price of 15 4 3:75A, while Bob is selling 10 token B for the price of 30 10 3:00A. In the case of xing token B as reference, we say that Alice is selling 15 token A for the price of 4 15 0:26666667B and Bob is buying 10 token A .