function createMarketOrder(bytes32 ticker, Side side, uint amount) public{
uint orderBookSide;
if(side == Side.BUY){
orderBookSide = 1;
}
else{
require(balances[msg.sender][ticker] >= amount, "Insufficient balance");
orderBookSide = 0;
}
Order[] storage orders = orderBook[ticker][orderBookSide];
uint totalFilled;
for (uint256 i = 0; i < orders.length && totalFilled < amount; i++){
if(orderBookSide == 1 && orders[i].amount < amount){
totalFilled = orders[i].amount + totalFilled;
orders[i].filled = orders[i].amount;
amount = amount - orders[i].amount;
_transfer(ticker, msg.sender, orders[i].trader, orders[i].amount, orders[i].price);
}
else if(orderBookSide == 1 && orders[i].amount >= amount){
totalFilled = amount;
orders[i].filled = amount;
_transfer(ticker, msg.sender, orders[i].trader, orders[i].filled, orders[i].price);
}
if(orderBookSide == 0 && orders[i].amount < amount){
totalFilled = orders[i].amount + totalFilled;
orders[i].filled = orders[i].amount;
amount = amount - orders[i].amount;
_transfer(ticker, orders[i].trader, msg.sender, orders[i].amount, orders[i].price);
}
else if(orderBookSide == 0 && orders[i].amount >= amount){
totalFilled = amount;
orders[i].filled = amount;
_transfer(ticker, orders[i].trader, msg.sender, orders[i].filled, orders[i].price);
}
if(totalFilled == amount){
break;
}
}
if(totalFilled != 0){
_clearOrders(ticker, orderBookSide);
}
}
function _transfer(bytes32 ticker, address buyer, address seller, uint amount, uint price) internal{
require(balances[buyer]["ETH"] > amount.mul(price));
balances[buyer][ticker] = amount + balances[buyer][ticker];
balances[seller][ticker] = balances[seller][ticker] - amount;
balances[buyer]["ETH"] = balances[buyer]["ETH"] - amount.mul(price);
balances[seller]["ETH"] = balances[seller]["ETH"] + amount.mul(price);
}
function _clearOrders(bytes32 ticker, uint orderBookSide) internal{
while(orderBook[ticker][orderBookSide][0].filled == orderBook[ticker][orderBookSide][0].amount){
if(orderBook[ticker][orderBookSide].length > 1){
for(uint256 i = 0; i < orderBook[ticker][orderBookSide].length - 1; ++i){
orderBook[ticker][orderBookSide][i] = orderBook[ticker][orderBookSide][i + 1];
}
}
orderBook[ticker][orderBookSide].pop();
}
}
I keep failing my test due to my clear order function not working properly as my failed test says they sell book isn’t cleared correctly. So I was wondering if in this instance am I using the while loop correctly because it seems to me that it should work. Any bits of help or ideas would be appreciated! Thanks!