-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathITT.sol
487 lines (412 loc) · 15 KB
/
ITT.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
file: ITT.sol
ver: 0.3.9
updated:20-Apr-2018
author: Darryl Morris
contributors: terraflops
email: o0ragman0o AT gmail.com
An ERC20 compliant token with currency
exchange functionality here called an 'Intrinsically Tradable
Token' (ITT).
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
*/
pragma solidity ^0.4.18;
import "./Base.sol";
import "./Math.sol";
import "./ERC20.sol";
import "./LibCLL.sol";
contract ITTInterface
{
using LibCLLu for LibCLLu.CLL;
/* Constants */
string constant public VERSION = "ITT 0.3.9";
uint constant HEAD = 0;
uint constant MINNUM = uint(1);
// use only 128 bits of uint to prevent mul overflows.
uint constant MAXNUM = 2**128;
uint constant MINPRICE = uint(1);
uint constant NEG = uint(-1); //2**256 - 1
bool constant PREV = false;
bool constant NEXT = true;
bool constant BID = false;
bool constant ASK = true;
// minimum gas required to prevent out of gas on 'take' loop
uint constant MINGAS = 100000;
// For staging and commiting trade details. This saves unneccessary state
// change gas usage during multi order takes but does increase logic
// complexity when encountering 'trade with self' orders
struct TradeMessage {
bool make;
bool side;
uint price;
uint tradeAmount;
uint balance;
uint etherBalance;
}
/* State Valiables */
// To allow for trade halting by owner.
bool public trading;
// Mapping for ether ownership of accumulated deposits, sales and refunds.
mapping (address => uint) etherBalance;
// Orders are stored in circular linked list FIFO's which are mappings with
// price as key and value as trader address. A trader can have only one
// order open at each price. Reordering at that price will cancel the first
// order and push the new one onto the back of the queue.
mapping (uint => LibCLLu.CLL) orderFIFOs;
// Order amounts are stored in a seperate lookup. The keys of this mapping
// are `keccak256` hashes of the price and trader address.
// This mapping prevents more than one order at a particular price.
mapping (bytes32 => uint) amounts;
// The pricebook is a linked list holding keys to lookup the price FIFO's
LibCLLu.CLL priceBook = orderFIFOs[0];
/* Events */
// Triggered on a make sell order
event Ask (uint indexed price, uint amount, address indexed trader);
// Triggered on a make buy order
event Bid (uint indexed price, uint amount, address indexed trader);
// Triggered on a filled order
event Sale (uint indexed price, uint amount, address indexed buyer, address indexed seller, bool side);
// Triggered when trading is started or halted
event Trading(bool trading);
/* Functions Public constant */
/// @notice Returns best bid or ask price.
function spread(bool _side) public view returns(uint);
/// @notice Returns the order amount for trader `_trader` at '_price'
/// @param _trader Address of trader
/// @param _price Price of order
function getAmount(uint _price, address _trader)
public constant returns(uint);
/// @notice Returns the collective order volume at a `_price`.
/// @param _price FIFO for price.
function getPriceVolume(uint _price) public view returns (uint);
/// @notice Returns an array of all prices and their volumes.
/// @dev [even] indecies are the price. [odd] are the volume. [0] is the
/// index of the spread.
function getBook() public view returns (uint[]);
/* Functions Public non-constant*/
/// @notice Will buy `_amount` tokens at or below `_price` each.
/// @param _bidPrice Highest price to bid.
/// @param _amount The requested amount of tokens to buy.
/// @param _make Value of true will make order if not filled.
function buy (uint _bidPrice, uint _amount, bool _make)
external payable returns (bool);
/// @notice Will sell `_amount` tokens at or above `_price` each.
/// @param _askPrice Lowest price to ask.
/// @param _amount The requested amount of tokens to buy.
/// @param _make A value of true will make an order if not market filled.
function sell (uint _askPrice, uint _amount, bool _make)
external returns (bool);
/// @notice Will withdraw `_ether` to your account.
/// @param _ether The amount to withdraw
function withdraw(uint _ether)
external returns (bool success_);
/// @notice Cancel order at `_price`
/// @param _price The price at which the order was placed.
function cancel(uint _price)
external returns (bool);
/// @notice Will set trading state to `_trading`
/// @param _trading State to set trading to.
function setTrading(bool _trading)
external returns (bool);
}
/* Intrinsically Tradable Token code */
contract ITT is ERC20Token, ITTInterface
{
/* Structs */
/* Modifiers */
/// @dev Passes if token is currently trading
modifier isTrading() {
require(trading);
_;
}
/// @dev Validate buy parameters
modifier isValidBuy(uint _bidPrice, uint _amount) {
require(!((etherBalance[msg.sender] + msg.value) < (_amount * _bidPrice) ||
_amount == 0 || _amount > totalSupply ||
_bidPrice <= MINPRICE || _bidPrice >= MAXNUM)); // has insufficient ether.
_;
}
/// @dev Validates sell parameters. Price must be larger than 1.
modifier isValidSell(uint _askPrice, uint _amount) {
require(!(_amount > balance[msg.sender] || _amount == 0 ||
_askPrice < MINPRICE || _askPrice > MAXNUM));
_;
}
/// @dev Validates ether balance
modifier hasEther(address _member, uint _ether) {
require(etherBalance[_member] >= _ether);
_;
}
/// @dev Validates token balance
modifier hasBalance(address _member, uint _amount) {
require(balance[_member] >= _amount);
_;
}
/* Functions */
function ITT(
uint _totalSupply,
uint8 _decimalPlaces,
string _symbol,
string _name
)
ERC20Token(
_totalSupply,
_decimalPlaces,
_symbol,
_name
) public
{
// setup pricebook and maximum spread.
priceBook.cll[HEAD][PREV] = MINPRICE;
priceBook.cll[MINPRICE][PREV] = MAXNUM;
priceBook.cll[HEAD][NEXT] = MAXNUM;
priceBook.cll[MAXNUM][NEXT] = MINPRICE;
trading = true;
balance[owner] = totalSupply;
}
/* Functions Getters */
function etherBalanceOf(address _addr) public view returns (uint) {
return etherBalance[_addr];
}
function spread(bool _side) public view returns(uint) {
return priceBook.step(HEAD, _side);
}
function getAmount(uint _price, address _trader)
public view returns(uint) {
return amounts[keccak256(_price, _trader)];
}
function sizeOf(uint l) public view returns (uint s) {
if(l == 0) return priceBook.sizeOf();
return orderFIFOs[l].sizeOf();
}
function getPriceVolume(uint _price) public view returns (uint v_)
{
uint n = orderFIFOs[_price].step(HEAD,NEXT);
while (n != HEAD) {
v_ += amounts[keccak256(_price, address(n))];
n = orderFIFOs[_price].step(n, NEXT);
}
return;
}
function getBook() public view returns (uint[])
{
uint i;
uint p = priceBook.step(MINNUM, NEXT);
uint[] memory volumes = new uint[](priceBook.sizeOf() * 2 - 2);
while (p < MAXNUM) {
volumes[i++] = p;
volumes[i++] = getPriceVolume(p);
p = priceBook.step(p, NEXT);
}
return volumes;
}
function numOrdersOf(address _addr) public view returns (uint)
{
uint c;
uint p = MINNUM;
while (p < MAXNUM) {
if (amounts[keccak256(p, _addr)] > 0) c++;
p = priceBook.step(p, NEXT);
}
return c;
}
function getOpenOrdersOf(address _addr) public view returns (uint[])
{
uint i;
uint p = MINNUM;
uint[] memory open = new uint[](numOrdersOf(_addr)*2);
p = MINNUM;
while (p < MAXNUM) {
if (amounts[keccak256(p, _addr)] > 0) {
open[i++] = p;
open[i++] = amounts[keccak256(p, _addr)];
}
p = priceBook.step(p, NEXT);
}
return open;
}
function getNode(uint _list, uint _node) public view returns(uint[2])
{
return [orderFIFOs[_list].cll[_node][PREV],
orderFIFOs[_list].cll[_node][NEXT]];
}
/* Functions Public */
// Here non-constant public functions act as a security layer. They are re-entry
// protected so cannot call each other. For this reason, they
// are being used for parameter and enterance validation, while internal
// functions manage the logic. This also allows for deriving contracts to
// overload the public function with customised validations and not have to
// worry about rewritting the logic.
function buy (uint _bidPrice, uint _amount, bool _make)
external
payable
canEnter
isTrading
isValidBuy(_bidPrice, _amount)
returns (bool)
{
trade(_bidPrice, _amount, BID, _make);
return true;
}
function sell (uint _askPrice, uint _amount, bool _make)
external
canEnter
isTrading
isValidSell(_askPrice, _amount)
returns (bool)
{
trade(_askPrice, _amount, ASK, _make);
return true;
}
function withdraw(uint _ether)
external
canEnter
hasEther(msg.sender, _ether)
returns (bool success_)
{
etherBalance[msg.sender] -= _ether;
safeSend(msg.sender, _ether);
success_ = true;
}
function cancel(uint _price)
external
canEnter
returns (bool)
{
TradeMessage memory tmsg;
tmsg.price = _price;
tmsg.balance = balance[msg.sender];
tmsg.etherBalance = etherBalance[msg.sender];
cancelIntl(tmsg);
balance[msg.sender] = tmsg.balance;
etherBalance[msg.sender] = tmsg.etherBalance;
return true;
}
function setTrading(bool _trading)
external
onlyOwner
canEnter
returns (bool)
{
trading = _trading;
Trading(true);
return true;
}
/* Functions Internal */
// Internal functions handle this contract's logic.
function trade (uint _price, uint _amount, bool _side, bool _make) internal {
TradeMessage memory tmsg;
tmsg.price = _price;
tmsg.tradeAmount = _amount;
tmsg.side = _side;
tmsg.make = _make;
// Cache state balances to memory and commit to storage only once after trade.
tmsg.balance = balance[msg.sender];
tmsg.etherBalance = etherBalance[msg.sender] + msg.value;
take(tmsg);
make(tmsg);
balance[msg.sender] = tmsg.balance;
etherBalance[msg.sender] = tmsg.etherBalance;
}
function take (TradeMessage tmsg)
internal
{
address maker;
bytes32 orderHash;
uint takeAmount;
uint takeEther;
// use of signed math on unsigned ints is intentional
uint sign = tmsg.side ? uint(1) : uint(-1);
uint bestPrice = spread(!tmsg.side);
// Loop with available gas to take orders
while (
tmsg.tradeAmount > 0 &&
cmpEq(tmsg.price, bestPrice, !tmsg.side) &&
msg.gas > MINGAS
)
{
maker = address(orderFIFOs[bestPrice].step(HEAD, NEXT));
orderHash = keccak256(bestPrice, maker);
if (tmsg.tradeAmount < amounts[orderHash]) {
// Prepare to take partial order
amounts[orderHash] = safeSub(amounts[orderHash], tmsg.tradeAmount);
takeAmount = tmsg.tradeAmount;
tmsg.tradeAmount = 0;
} else {
// Prepare to take full order
takeAmount = amounts[orderHash];
tmsg.tradeAmount = safeSub(tmsg.tradeAmount, takeAmount);
closeOrder(bestPrice, maker);
}
takeEther = safeMul(bestPrice, takeAmount);
// signed multiply on uints is intentional and so safeMaths will
// break here. Valid range for exit balances are 0..2**128
tmsg.etherBalance += takeEther * sign;
tmsg.balance -= takeAmount * sign;
if (tmsg.side) {
// Sell to bidder
if (msg.sender == maker) {
// bidder is self
tmsg.balance += takeAmount;
} else {
balance[maker] += takeAmount;
}
} else {
// Buy from asker;
if (msg.sender == maker) {
// asker is self
tmsg.etherBalance += takeEther;
} else {
etherBalance[maker] += takeEther;
}
}
Sale (bestPrice, takeAmount, msg.sender, maker, tmsg.side);
// prep for next order
bestPrice = spread(!tmsg.side);
}
}
function make(TradeMessage tmsg)
internal
{
bytes32 orderHash;
if (tmsg.tradeAmount == 0 || !tmsg.make || msg.gas < MINGAS) return;
orderHash = keccak256(tmsg.price, msg.sender);
if (amounts[orderHash] != 0) {
// Cancel any pre-existing owned order at this price
cancelIntl(tmsg);
}
if (!orderFIFOs[tmsg.price].exists()) {
// Register price in pricebook
priceBook.insert(
priceBook.seek(HEAD, tmsg.price, tmsg.side),
tmsg.price, !tmsg.side);
}
amounts[orderHash] = tmsg.tradeAmount;
orderFIFOs[tmsg.price].push(uint(msg.sender), PREV);
if (tmsg.side) {
tmsg.balance -= tmsg.tradeAmount;
Ask (tmsg.price, tmsg.tradeAmount, msg.sender);
} else {
tmsg.etherBalance -= tmsg.tradeAmount * tmsg.price;
Bid (tmsg.price, tmsg.tradeAmount, msg.sender);
}
}
function cancelIntl(TradeMessage tmsg) internal {
uint amount = amounts[keccak256(tmsg.price, msg.sender)];
if (amount == 0) return;
if (tmsg.price > spread(BID)) tmsg.balance += amount; // was ask
else tmsg.etherBalance += tmsg.price * amount; // was bid
closeOrder(tmsg.price, msg.sender);
}
function closeOrder(uint _price, address _trader) internal {
orderFIFOs[_price].remove(uint(_trader));
if (!orderFIFOs[_price].exists()) {
priceBook.remove(_price);
}
delete amounts[keccak256(_price, _trader)];
}
}