(Part 9) Decentralized Exchange - Removing Orders/Items From The Queue(PT 8)

in #utopian-io5 years ago

Repository

https://github.com/igormuba/DEX/blob/master/Class8/exchange.sol

What Will I Learn?

  • Removing a buy or sell order
  • Iterating through the price queue

Requirements

  • Internet connection.
  • Code editor.
  • Browser.

Difficulty

  • Advanced.

Tutorial Contents

Introduction

On the previous tutorial we have finished all the functions to fetch the orders that have already been placed on the exchange. We have also learned how to work with it, connecting the Exchange to the ERC20 token (you can use any ERC20 compatible token on this exchange!) and placing orders on both sides of the book (buy and sell).

On this tutorial, you will learn how can you remove the orders from the user at a price point. The user will request us to remove his orders to buy or sell at a certain price, and the exchange will remove all of his orders at the given price point. Notice that we must be careful to remove only his orders, so the other orders from other people will still be on the queue of that price point. To achieve that effect, we will check for each node on the queue data structure is the maker of that order is the caller of the functions. If it is, we remove the node.

It is recommended to follow this course to understand what we will be doing here, but it is not mandatory. A previous knowledge of data structures, in whatever language, is recommended, because we are using linked lists and queues in this exercise. This class connects with the previous, as we will use the "fetch book" functions to see the changes in the book, at the end of the post.

The function and loading the token

The function will take 3 arguments, the address of the ERC20 compatible token that has a struct of a Token stored in our exchange, a boolean telling if the order is a sell order or not, and the price of the orders that the user wants to delete. Using just those 3 pieces of data, the function will, later, remove all of the orders of the user at that price point

function removeOrder(address _token, bool isSellOrder, uint _price) public{
Token storage loadedToken = tokenList[_token];
// code to remove the buy or sell order omitted
}

Notice we are also loading the token from the mapping of Token structures saved on the Ethereum storage. This will make it easier to work with the variables and data from the token on the exchange, though, it will consume more of the ethereum stack, it is recommended to avoid creating too many variables to not reach the end of the stack, but I think it is safe to create this one here, even though it is a big one.

Is it a sell or a buy order

Now, we will use the boolean value received on the function arguments to know if the user wants to remove a buy or remove a sell order, the data will be used to take the decision on the branch below:

if (isSellOrder){
// code to remove sell order omitted
}else{
// code to remove buy order omitted
}

The above is the simplest implementation I have found for that, however, many other equally or better designs can be implemented, you could actually use strings, uints, and other data types to take that decision. You can even not take any data to specify the order type! In that case, another logic would be used to see if that price is on the buying or selling side of the book.

There is an implementation that the user does not even need to tell you if it is a buy or sell order! I am not using this on my code, but if you want to try it, the user can just give the token and the price. If the price is higher than the highest price in the buy book, then it obviously is a sell order. On the other hand, if the price of the order the user wants to delete is lower. In this case, you don't even need the boolean as an argument for the function. And the implementation would be like this:

if (_price>loadedToken.maxBuyPrice){
// code to remove sell order omitted
} else if (_price<minSellPrice) {
// code to remove buy order omitted
}

Removing the sell order

Whatever the decision branch you have designed on the section above, the procedure to remove the buy and sell orders are different. Starting on the selling branch.

First, we prepare a loop to check all the orders at that price. We will need a counter for that:

uint counter = loadedToken.sellBook[_price].offerPointer;
while (counter <= loadedToken.sellBook[_price].offerLength){
    // if the maker of the order is the caller
    if (loadedToken.sellBook[_price].offers[counter].maker==msg.sender){
        // remove the order and reimburse the caller
    }
counter++;
}

The above will loop through all the elements on that price point. Now, inside it we need to do 2 things:

  1. remove the volume of the order of the user
  2. reimburse the user on the volume of that order

If the maker of the order is the caller of the function, first, we store the volume of the order into a variable:

uint orderVolume = loadedToken.sellBook[_price].offers[counter].amount;

So that we can reimburse him later. Then we do a simple check for overflow:

require(tokenBalance[msg.sender][_token]+orderVolume>=tokenBalance[msg.sender][_token]);

Before we reimburse, we clean the volume of the order, to avoid the race condition that would allow for exploits:

loadedToken.sellBook[_price].offers[counter].amount=0;

And then we can reimburse the tokens to the person that tried to sell them:

tokenBalance[msg.sender][_token]+=orderVolume;

Removing a buy order

The remove buy order decision branch is very similar to the above, in regards to logic, so I will paste the code here and explain what changes later.

uint counter = loadedToken.buyBook[_price].offerPointer;
            while (counter <= loadedToken.buyBook[_price].offerLength){
                if (loadedToken.buyBook[_price].offers[counter].maker==msg.sender){
                    uint orderVolume = loadedToken.buyBook[_price].offers[counter].amount*_price;
                    require(ethBalance[msg.sender]+orderVolume>=ethBalance[msg.sender]);
                    loadedToken.buyBook[_price].offers[counter].amount=0;
                    ethBalance[msg.sender]+=orderVolume;
                }
                counter++;
            }

The first thing that changes is that instead of working with the sellBook we are working with the buyBook

Also, we are working with the users ETH balance, not the token balance. In the previous section, as the user wanted to sell tokens, he needs to have tokens. Now, as he wants to buy, he needs ETH. So, instead of working with the tokenBalance[msg.sender][_token] we are working with the ethBalance[msg.sender].

Another change is that the orderVolume is the product of the price times the amount of tokens he wants to buy, not just the tokens.

How it works

I have deployed both contracts and allowed the exchange to spend from my balance on the token contract, just like on the previous tutorial.
image.png

I have placed a few orders on both sides
image.png

Now, removing the all volume from the orders I have placed on the buy at 11 and sell at 11:
image.png

So those orders will be ignored when parsing through them.

Curriculum

Latest tutorial of the series:

First tutorial of the series:

Beneficiaries

This post has as beneficiaries

using the SteemPeak beneficiary tool

Captura de Tela 20190122 às 16.07.11.png

Sort:  

Thank you for your contribution @igormuba.
After analyzing your tutorial we suggest the following:

  • Just a suggestion, be careful with the indentation of your code.
    1.png

Thank you for your good work in developing these tutorials.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

This story was recommended by Steeve to its users and upvoted by one or more of them.

Check @steeveapp to learn more about Steeve, an AI-powered Steem interface.

Hi, @igormuba!

You just got a 0.24% upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in here to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.

Congratulations! Your post has been selected as a daily Steemit truffle! It is listed on rank 2 of all contributions awarded today. You can find the TOP DAILY TRUFFLE PICKS HERE.

I upvoted your contribution because to my mind your post is at least 5 SBD worth and should receive 212 votes. It's now up to the lovely Steemit community to make this come true.

I am TrufflePig, an Artificial Intelligence Bot that helps minnows and content curators using Machine Learning. If you are curious how I select content, you can find an explanation here!

Have a nice day and sincerely yours,
trufflepig
TrufflePig

Hi @igormuba!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @igormuba!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 61926.98
ETH 3060.91
USDT 1.00
SBD 3.79