This repository has been archived by the owner on Sep 27, 2024. It is now read-only.
forked from forkdelta/classic-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmartContract.ejs
417 lines (338 loc) · 26.2 KB
/
smartContract.ejs
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
<h3>Smart contract overview</h3>
<h4>Changelog</h4>
<h5>February 9, 2017</h5>
<ul>
<li>In response to breaking changes in the eth_sign function, signatures now require a special prefix. See <a href="https://github.com/ethereum/go-ethereum/pull/2940">this GitHub issue</a> for technical details.</li>
</ul>
<h5>October 25, 2016</h5>
<ul>
<li>The smart contract has been upgraded to <code>pragma solidity ^0.4.2</code>.</li>
<li>The only <code>payable</code> function is <code>deposit</code>.</li>
<li>The smart contract has improved on-chain order functionality. Previously, the on-chain order function would have required an off-chain signature as input. This is no longer necessary. Order hashes that have been submitted on-chain are now stored in a separate mapping, and the order details are stored in the event log. This is meant to be a fallback in the event that the off-chain order system is no longer feasible.</li>
<li>Because the smart contract is now an order parameter, orders are only valid on one smart contract. Previously, they were valid on multiple EtherDelta smart contracts at a time.</li>
<li>An admin account has the ability to change the fee account, the admin account, or the fees.</li>
<li>The fees are currently the same as before (0.3% for takers, 0.0% for makers), and the admin account is only allowed to decrease the fees.</li>
<li>The smart contract allows for a market maker rebate and tiered account levels with different fee structures. These are currently not enabled.</li>
<li>Previously, take fees were paid in the token being received by the taker. Now they (along with make fees and rebates) are paid in the token being given by the taker. This simplifies the fee calculus.</li>
<li>The fee calculation can no longer cause rounding error. Previously, this could have introduced problems for tokens with a low number of decimals and a high value per token.</li>
</ul>
<h4>High level overview</h4>
<p>At a high level, EtherDelta functions just like a normal exchange. Unlike a traditional exchange, which has all of its business logic defined and executed on a private server owned by a company, EtherDelta's business logic is defined and executed in a smart contract on the public, decentralized <a href="https://ethereum.org">Ethereum</a> blockchain. The EtherDelta GUI (Graphical User Interface) is designed to let you interact with the EtherDelta smart contract without having to deal with the low-level details of blockchain transactions.</p>
<p>The EtherDelta smart contract allows you to deposit or withdraw Ether or any <a href="https://github.com/ethereum/EIPs/issues/20">ERC-20</a> Ethereum token.</p>
<p>Like any other exchange, EtherDelta has an order book of resting orders. A resting order consists of a price, volume, expiration time (measured in blocks), and signature. In effect, it represents a signed intent to trade. When you create a new resting order, it gets broadcast to an off-chain order book server. The primary benefit of storing resting orders off-chain is that you don't have to create an Ethereum transaction and pay gas to submit a resting order. EtherDelta does have a backup mechanism that allows orders to be submitted with on-chain transactions.</p>
<p>When a counterparty decides to trade your resting order, he submits a transaction to the smart contract with your signed intent to trade and the volume he wishes to trade. The smart contract checks the signature, makes sure you and the counterparty both have enough funds to cover the trade, and then executes the trade by moving funds between accounts.</p>
<h4>Internal security review</h4>
<p>The smart contract source code can be found <a href="https://github.com/etherdelta/etherdelta.github.io/blob/master/smart_contract/etherdelta.sol">on GitHub</a>. It is also verified on Etherscan.</p>
<pre><code>pragma solidity ^0.4.2;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
</code></pre>
<p>The first contract, <code>SafeMath</code>, defines functions that can be used to do addition, subtraction, or multiplication and throw an error in the event of an unsigned integer overflow or underflow. The <code>safeMul</code> and <code>safeAdd</code> functions are used throughout the smart contract to prevent situations where arguments are so large that numbers overflow, causing unexpected and undesired behavior. The <code>safeSub</code> function is also used throughout the smart contract to prevent situations where a transaction would cause a user's balance to be negative.</p>
<pre><code>contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send <code>_value</code> token to <code>_to</code> from <code>msg.sender</code>
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send <code>_value</code> token to <code>_to</code> from <code>_from</code> on the condition it is approved by <code>_from</code>
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice <code>msg.sender</code> approves <code>_addr</code> to spend <code>_value</code> tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
uint public decimals;
string public name;
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ReserveToken is StandardToken, SafeMath {
address public minter;
function ReserveToken() {
minter = msg.sender;
}
function create(address account, uint amount) {
if (msg.sender != minter) throw;
balances[account] = safeAdd(balances[account], amount);
totalSupply = safeAdd(totalSupply, amount);
}
function destroy(address account, uint amount) {
if (msg.sender != minter) throw;
if (balances[account] < amount) throw;
balances[account] = safeSub(balances[account], amount);
totalSupply = safeSub(totalSupply, amount);
}
}
</code></pre>
<p>The <code>Token</code> interface defines the ERC-20 token standard. EtherDelta relies on the <code>Token</code> fuction signatures to be able to do token transfers. EtherDelta's <a href="https://github.com/etherdelta/etherdelta.github.io/blob/master/test.js">test framework</a> uses the <code>StandardToken</code> implementation along with the <code>ReserveToken</code> contract to implement and trade a basic token.</p>
<pre><code>contract AccountLevels {
//given a user, returns an account level
//0 = regular user (pays take fee and make fee)
//1 = market maker silver (pays take fee, no make fee, gets rebate)
//2 = market maker gold (pays take fee, no make fee, gets entire counterparty's take fee as rebate)
function accountLevel(address user) constant returns(uint) {}
}
contract AccountLevelsTest is AccountLevels {
mapping (address => uint) public accountLevels;
function setAccountLevel(address user, uint level) {
accountLevels[user] = level;
}
function accountLevel(address user) constant returns(uint) {
return accountLevels[user];
}
}
</code></pre>
<p>The <code>AccountLevels</code> interface defines a contract that can keep track of account levels for EtherDelta users. The regular level involves paying make and take fees. The market maker silver level involves paying a take fee, but no make fee, and getting a make rebate. The gold level involves paying a take fee, but no make fee, and getting a make rebate equal to the take fee paid by the counterparty. The test framework uses the <code>AccountLevelsTest</code> contract to test the different account levels.</p>
<pre><code>contract EtherDelta is SafeMath {
address public admin; //the admin address
address public feeAccount; //the account that will receive fees
address public accountLevelsAddr; //the address of the AccountLevels contract
uint public feeMake; //percentage times (1 ether)
uint public feeTake; //percentage times (1 ether)
uint public feeRebate; //percentage times (1 ether)
mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether)
mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
</code></pre>
<p>The first section of the main <code>EtherDelta</code> contract defines the storage variables.</p>
<ul>
<li>The <code>admin</code> variable holds the account with special administrative privileges. The admin account can change the admin account, change the <code>accountLevelsAddr</code>, or lower the fees. The admin account cannot raise the fees.</li>
<li>The <code>feeAccount</code> variable holds the account to which EtherDelta trading fees are paid.</li>
<li>The <code>accountLevelsAddr</code> variable holds the address of the contract that specifies account levels. If the <code>accountLevelsAddr</code> is set to the zero account, then no account levels will be in effect.</li>
<li>The <code>feeMake</code>, <code>feeTake</code>, and <code>feeRebate</code> variables hold the fee percentages, times 1 ether. For example, since 1 ether = 10^18, 10^17 would represents 10%.</li>
<li>The <code>tokens</code> variable is where user balances are stored. For example, if your address is <code>0x123</code> and the DAO token address is <code>0xbb9</code>, then your DAO balance will be in <code>tokens[0xbb9][0x123].</code> By special case, your Ether balance will be in <code>tokens[0][0x123]</code>. Note that all Ether amounts are in Wei, and all token amounts are in the base unit of the token (which is usually Wei, but depends on the token).</li>
<li>The <code>orders</code> variable is used to keep track of orders that have been initiated on-chain. For example, if your address is <code>0x123</code>, and you create an order with order hash <code>0x234</code>, then <code>orders[0x123][0x234]</code> will be true.</li>
<li>The <code>orderFills</code> variable is used to keep track of orders that have been partially or completely filled. For example, if you create a resting order (using the account <code>0x123</code>) to buy 10 tokens with a hash of <code>0x234</code>, and someone submits a transaction to sell you 5 tokens (taking out half of your order), then <code>orderFills[0x123][0x234]</code> will be changed to 5.</li>
</ul>
<pre><code>event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
</code></pre>
<p>The events are emitted by similarly named transactions and stored in the blockchain. The GUI uses them to display a list of trades, deposits, and withdrawals.</p>
<pre><code>function EtherDelta(address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) {
admin = admin_;
feeAccount = feeAccount_;
accountLevelsAddr = accountLevelsAddr_;
feeMake = feeMake_;
feeTake = feeTake_;
feeRebate = feeRebate_;
}
function() {
throw;
}
</code></pre>
<p>The <code>EtherDelta</code> constructor simply initializes the admin account, fee account, account levels address, and fee percentages. The default function simply throws an error. Any Ether sent to EtherDelta without a function call will be returned to sender.</p>
<pre><code>function changeAdmin(address admin_) {
if (msg.sender != admin) throw;
admin = admin_;
}
function changeAccountLevelsAddr(address accountLevelsAddr_) {
if (msg.sender != admin) throw;
accountLevelsAddr = accountLevelsAddr_;
}
function changeFeeAccount(address feeAccount_) {
if (msg.sender != admin) throw;
feeAccount = feeAccount_;
}
function changeFeeMake(uint feeMake_) {
if (msg.sender != admin) throw;
if (feeMake_ > feeMake) throw;
feeMake = feeMake_;
}
function changeFeeTake(uint feeTake_) {
if (msg.sender != admin) throw;
if (feeTake_ > feeTake || feeTake_ < feeRebate) throw;
feeTake = feeTake_;
}
function changeFeeRebate(uint feeRebate_) {
if (msg.sender != admin) throw;
if (feeRebate_ < feeRebate || feeRebate_ > feeTake) throw;
feeRebate = feeRebate_;
}
</code></pre>
<p>The admin account has the ability to change the admin account, the account levels address, the fee account, and the fees. The fees can only be improved, meaning the make and take fees can only be lowered and the rebate can only be increased.</p>
<pre><code>function deposit() payable {
tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value);
Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
}
function withdraw(uint amount) {
if (msg.value>0) throw;
if (tokens[0][msg.sender] < amount) throw;
tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount);
if (!msg.sender.call.value(amount)()) throw;
Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
}
</code></pre>
<p>The vanilla <code>deposit</code> and <code>withdraw</code> functions are to be used for depositing and withdrawing Ether only. Note that the <code>withdraw</code> function does all state changes before sending Ether to the account owner, to avoid potential recursive or reentrant call vulnerabilities. The <code>deposit</code> function is the only <code>payable</code> function in the entire smart contract.</p>
<pre><code>function depositToken(address token, uint amount) {
//remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
if (msg.value>0 || token==0) throw;
if (!Token(token).transferFrom(msg.sender, this, amount)) throw;
tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount);
Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
function withdrawToken(address token, uint amount) {
if (msg.value>0 || token==0) throw;
if (tokens[token][msg.sender] < amount) throw;
tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
if (!Token(token).transfer(msg.sender, amount)) throw;
Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
</code></pre>
<p>The <code>depositToken</code> and <code>withdrawToken</code> functions are similar to their vanilla equivalents, but they are meant to handle deposits and withdrawals of ERC-20 tokens.</p>
<pre><code>function balanceOf(address token, address user) constant returns (uint) {
return tokens[token][user];
}
</code></pre>
<p>The <code>balanceOf</code> function is a helper function to get a user's balance for a particular token.</p>
<pre><code>function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) {
if (msg.value>0) throw;
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
orders[msg.sender][hash] = true;
Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
</code></pre>
<p>Resting orders are meant to be stored off-chain. In the event that the off-chain broadcasting mechanism fails, users can always store resting orders on-chain by calling the <code>order</code> function. This function will record the hash as signed by the sender in the <code>orders</code> variable and emit an event with the order parameters.</p>
<p>These are the parameters that define an order:</p>
<ul>
<li><code>tokenGet</code> is the token you want to get and <code>tokenGive</code> is the token you want to give. For example, if you want to buy DAO with ETH, then <code>tokenGet</code> is the DAO address, and <code>tokenGive</code> is the ETH token address (0, since ETH is a special case token address).</li>
<li><code>amountGet</code> and <code>amountGive</code> represent the size and price you want to trade. For example, if you want to buy 100 DAO with 1 ETH, then <code>amountGet</code> would be 100 DAO, and <code>amountGive</code> would be 1 ETH, which implies a price of 0.01 DAO/ETH or 100 ETH/DAO. In this case, both values would be stored in Wei.</li>
<li><code>expires</code> is the block number the order expires in. After this block number, the order can no longer trade.</li>
<li><code>nonce</code> is a number you can include with your order to make it relatively unique. This way, if you want to place two otherwise identical orders, they won't have the same hash.</li>
</ul>
<pre><code>function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) {
//amount is in amountGet terms
if (msg.value>0) throw;
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(hash,v,r,s) == user) &&
block.number <= expires &&
safeAdd(orderFills[user][hash], amount) <= amountGet
)) throw;
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = safeAdd(orderFills[user][hash], amount);
Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether);
uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether);
uint feeRebateXfer = 0;
if (accountLevelsAddr != 0x0) {
uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether);
if (accountLevel==2) feeRebateXfer = feeTakeXfer;
}
tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer));
tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer));
tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer));
tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet);
tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet);
}
</code></pre>
<p>The <code>trade</code> function, along with its helper <code>tradeBalances</code>, represent the biggest chunk of logic. <code>trade</code> is the function you call when you see a resting order you like and you want to trade it. The parameters are the same as the order parameters, plus an <code>amount</code>, which is the amount of the order you want to trade (in <code>amountGet</code> terms). For example, if you see the order to buy 100 DAO with 1 ETH, and you want to sell 50 DAO for 0.5 ETH, you would use an <code>amount</code> of 50 DAO. The additional arguments <code>v</code>, <code>r</code>, and <code>s</code> hold the signature for the order hash as signed by <code>user</code>. These parameters can be filled with zero values if the order was submitted on-chain (since it will be marked as true in the <code>orders</code> variable).</li>
<p>The first thing the <code>trade</code> function does is construct an order hash. Then it checks to make sure the signature provided matches the order hash (or the order was submitted by the <code>user</code> on-chain), the order hasn't expired, and the trade won't overfill the remaining volume associated with the order. If all these things are true, the <code>tradeBalances</code> function moves funds from one account to the other, and moves funds to the fee account. Note that all fees are paid in the <code>tokenGet</code> token. Then the <code>trade</code> function updates the <code>orderFills</code> variable with the amount that has been filled, and emits an event.</p>
<p>Note that the balances of the two counterparties are never explicitly checked, because the <code>safeSub</code> function is used to ensure the balances don't go below zero. If the trade would result in a balance going below zero, the <code>safeSub</code> function would throw an error and the trade would fail. Also note that the <code>tradeBalances</code> function is marked as private, which means it can only be called from within the EtherDelta smart contract (specifically, from within the <code>trade</code> function).</p>
<pre><code>function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) {
if (!(
tokens[tokenGet][sender] >= amount &&
availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(hash,v,r,s) == user) &&
block.number <= expires
)) return 0;
uint available1 = safeSub(amountGet, orderFills[user][hash]);
uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive;
if (available1<available2) return available1;
return available2;
}
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
return orderFills[user][hash];
}
</code></pre>
<p>The <code>testTrade</code>, <code>availableVolume</code>, and <code>amountFilled</code> functions are helper functions. The <code>testTrade</code> function tests whether a trade is still available, using the <code>availableVolume</code> function to check how much volume is available on an order, taking into account the amount that has been filled so far and the funds available in the user's account. The <code>amountFilled</code> function is a helper for accessing the <code>orderFills</code> variable to see how much of an order has been filled already.</p>
<pre><code>function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) {
if (msg.value>0) throw;
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(orders[msg.sender][hash] || ecrecover(hash,v,r,s) == msg.sender)) throw;
orderFills[msg.sender][hash] = amountGet;
Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
</code></pre>
<p>The last function, <code>cancelOrder,</code> lets the owner of an order cancel it before it expires by maxing out the <code>orderFills</code> variable.</p>