aboutsummaryrefslogtreecommitdiffstats
path: root/packages/contracts/src/contracts/current/protocol/Exchange/MixinExchangeCore.sol
blob: 58b5fa6b1834fa3b3a2d8bdf7bf0e9166cef850e (plain) (blame)
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
/*

  Copyright 2018 ZeroEx Intl.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

*/

pragma solidity ^0.4.23;
pragma experimental ABIEncoderV2;

import "./libs/LibFillResults.sol";
import "./libs/LibOrder.sol";
import "./libs/LibMath.sol";
import "./libs/LibStatus.sol";
import "./libs/LibExchangeErrors.sol";
import "./mixins/MExchangeCore.sol";
import "./mixins/MSettlement.sol";
import "./mixins/MSignatureValidator.sol";
import "./mixins/MTransactions.sol";

contract MixinExchangeCore is
    SafeMath,
    LibMath,
    LibStatus,
    LibOrder,
    LibFillResults,
    LibExchangeErrors,
    MExchangeCore,
    MSettlement,
    MSignatureValidator,
    MTransactions
{
    // Mapping of orderHash => amount of takerAsset already bought by maker
    mapping (bytes32 => uint256) public filled;

    // Mapping of orderHash => cancelled
    mapping (bytes32 => bool) public cancelled;

    // Mapping of makerAddress => lowest salt an order can have in order to be fillable
    // Orders with a salt less than their maker's epoch are considered cancelled
    mapping (address => uint256) public makerEpoch;

    ////// Core exchange functions //////

    /// @dev Gets information about an order.
    /// @param order Order to gather information on.
    /// @return status Status of order. Statuses are defined in the LibStatus.Status struct.
    /// @return orderHash Keccak-256 EIP712 hash of the order.
    /// @return takerAssetFilledAmount Amount of order that has been filled.
    function getOrderInfo(Order memory order)
        public
        view
        returns (
            uint8 orderStatus,
            bytes32 orderHash,
            uint256 takerAssetFilledAmount)
    {
        // Compute the order hash and fetch filled amount
        orderHash = getOrderHash(order);
        takerAssetFilledAmount = filled[orderHash];

        // If order.takerAssetAmount is zero, then the order will always
        // be considered filled because 0 == takerAssetAmount == takerAssetFilledAmount
        // Instead of distinguishing between unfilled and filled zero taker
        // amount orders, we choose not to support them.
        if (order.takerAssetAmount == 0) {
            orderStatus = uint8(Status.ORDER_INVALID_TAKER_ASSET_AMOUNT);
            return (orderStatus, orderHash, takerAssetFilledAmount);
        }

        // If order.makerAssetAmount is zero, we also reject the order.
        // While the Exchange contract handles them correctly, they create
        // edge cases in the supporting infrastructure because they have
        // an 'infinite' price when computed by a simple division.
        if (order.makerAssetAmount == 0) {
            orderStatus = uint8(Status.ORDER_INVALID_MAKER_ASSET_AMOUNT);
            return (orderStatus, orderHash, takerAssetFilledAmount);
        }

        // Validate order expiration
        if (block.timestamp >= order.expirationTimeSeconds) {
            orderStatus = uint8(Status.ORDER_EXPIRED);
            return (orderStatus, orderHash, takerAssetFilledAmount);
        }

        // Validate order availability
        if (takerAssetFilledAmount >= order.takerAssetAmount) {
            orderStatus = uint8(Status.ORDER_FULLY_FILLED);
            return (orderStatus, orderHash, takerAssetFilledAmount);
        }

        // Check if order has been cancelled
        if (cancelled[orderHash]) {
            orderStatus = uint8(Status.ORDER_CANCELLED);
            return (orderStatus, orderHash, takerAssetFilledAmount);
        }

        // Validate order is not cancelled
        if (makerEpoch[order.makerAddress] > order.salt) {
            orderStatus = uint8(Status.ORDER_CANCELLED);
            return (orderStatus, orderHash, takerAssetFilledAmount);
        }

        // Order is Fillable
        orderStatus = uint8(Status.ORDER_FILLABLE);
        return (orderStatus, orderHash, takerAssetFilledAmount);
    }

    /// @dev Validates context for fillOrder. Succeeds or throws.
    /// @param order to be filled.
    /// @param orderStatus Status of order to be filled.
    /// @param orderHash Hash of order to be filled.
    /// @param takerAssetFilledAmount Amount of order already filled.
    /// @param signature Proof that the orders was created by its maker.
    /// @param takerAddress Address of order taker.
    /// @param takerAssetFillAmount Desired amount of order to fill by taker.
    function validateFillOrderContextOrRevert(
        Order memory order,
        uint8 orderStatus,
        bytes32 orderHash,
        uint256 takerAssetFilledAmount,
        bytes memory signature,
        address takerAddress,
        uint256 takerAssetFillAmount)
        internal
    {
        // Ensure order is valid
        require(
            orderStatus != uint8(Status.ORDER_INVALID_MAKER_ASSET_AMOUNT),
            INVALID_ORDER_MAKER_ASSET_AMOUNT
        );
        require(
            orderStatus != uint8(Status.ORDER_INVALID_TAKER_ASSET_AMOUNT),
            INVALID_ORDER_TAKER_ASSET_AMOUNT
        );

        // Validate Maker signature (check only if first time seen)
        if (takerAssetFilledAmount == 0) {
            require(
                isValidSignature(orderHash, order.makerAddress, signature),
                SIGNATURE_VALIDATION_FAILED
            );
        }

        // Validate sender is allowed to fill this order
        if (order.senderAddress != address(0)) {
            require(
                order.senderAddress == msg.sender,
                INVALID_SENDER
            );
        }

        // Validate taker is allowed to fill this order
        if (order.takerAddress != address(0)) {
            require(
                order.takerAddress == takerAddress,
                INVALID_CONTEXT
            );
        }
        require(
            takerAssetFillAmount > 0,
            GT_ZERO_AMOUNT_REQUIRED
        );
    }

    /// @dev Calculates amounts filled and fees paid by maker and taker.
    /// @param order to be filled.
    /// @param orderStatus Status of order to be filled.
    /// @param takerAssetFilledAmount Amount of order already filled.
    /// @param takerAssetFillAmount Desired amount of order to fill by taker.
    /// @return status Return status of calculating fill amounts. Returns Status.SUCCESS on success.
    /// @return fillResults Amounts filled and fees paid by maker and taker.
    function calculateFillResults(
        Order memory order,
        uint8 orderStatus,
        uint256 takerAssetFilledAmount,
        uint256 takerAssetFillAmount)
        public
        pure
        returns (
            uint8 status,
            FillResults memory fillResults)
    {
        // Fill Amount must be greater than 0
        if (takerAssetFillAmount <= 0) {
            status = uint8(Status.TAKER_ASSET_FILL_AMOUNT_TOO_LOW);
            return;
        }

        // Ensure the order is fillable
        if (orderStatus != uint8(Status.ORDER_FILLABLE)) {
            status = uint8(orderStatus);
            return;
        }

        // Compute takerAssetFilledAmount
        uint256 remainingtakerAssetAmount = safeSub(order.takerAssetAmount, takerAssetFilledAmount);
        fillResults.takerAssetFilledAmount = min256(takerAssetFillAmount, remainingtakerAssetAmount);

        // Validate fill order rounding
        if (isRoundingError(
            fillResults.takerAssetFilledAmount,
            order.takerAssetAmount,
            order.makerAssetAmount))
        {
            status = uint8(Status.ROUNDING_ERROR_TOO_LARGE);
            fillResults.takerAssetFilledAmount = 0;
            return;
        }

        // Compute proportional transfer amounts
        // TODO: All three are multiplied by the same fraction. This can
        // potentially be optimized.
        fillResults.makerAssetFilledAmount = getPartialAmount(
            fillResults.takerAssetFilledAmount,
            order.takerAssetAmount,
            order.makerAssetAmount);
        fillResults.makerFeePaid = getPartialAmount(
            fillResults.takerAssetFilledAmount,
            order.takerAssetAmount,
            order.makerFee);
        fillResults.takerFeePaid = getPartialAmount(
            fillResults.takerAssetFilledAmount,
            order.takerAssetAmount,
            order.takerFee);

        status = uint8(Status.SUCCESS);
        return;
    }

    /// @dev Updates state with results of a fill order.
    /// @param order that was filled.
    /// @param takerAddress Address of taker who filled the order.
    /// @return fillResults Amounts filled and fees paid by maker and taker.
    function updateFilledState(
        Order memory order,
        address takerAddress,
        bytes32 orderHash,
        FillResults memory fillResults)
        internal
    {
        // Update state
        filled[orderHash] = safeAdd(filled[orderHash], fillResults.takerAssetFilledAmount);

        // Log order
        emitFillEvent(order, takerAddress, orderHash, fillResults);
    }

    /// @dev Fills the input order.
    /// @param order Order struct containing order specifications.
    /// @param takerAssetFillAmount Desired amount of takerToken to sell.
    /// @param signature Proof that order has been created by maker.
    /// @return Amounts filled and fees paid by maker and taker.
    function fillOrder(
        Order memory order,
        uint256 takerAssetFillAmount,
        bytes memory signature)
        public
        returns (FillResults memory fillResults)
    {
        // Fetch current order status
        bytes32 orderHash;
        uint8 orderStatus;
        uint256 takerAssetFilledAmount;
        (orderStatus, orderHash, takerAssetFilledAmount) = getOrderInfo(order);

        // Fetch taker address
        address takerAddress = getCurrentContextAddress();

        // Either our context is valid or we revert
        validateFillOrderContextOrRevert(order, orderStatus, orderHash, takerAssetFilledAmount, signature, takerAddress, takerAssetFillAmount);

        // Compute proportional fill amounts
        uint8 status;
        (status, fillResults) = calculateFillResults(order, orderStatus, takerAssetFilledAmount, takerAssetFillAmount);
        if (status != uint8(Status.SUCCESS)) {
            emit ExchangeStatus(uint8(status), orderHash);
            return fillResults;
        }

        // Settle order
        (fillResults.makerAssetFilledAmount, fillResults.makerFeePaid, fillResults.takerFeePaid) =
            settleOrder(order, takerAddress, fillResults.takerAssetFilledAmount);

        // Update exchange internal state
        updateFilledState(order, takerAddress, orderHash, fillResults);
        return fillResults;
    }

    /// @dev Validates context for cancelOrder. Succeeds or throws.
    /// @param order that was cancelled.
    /// @param orderStatus Status of order that was cancelled.
    /// @param orderHash Hash of order that was cancelled.
    function validateCancelOrderContextOrRevert(
        Order memory order,
        uint8 orderStatus,
        bytes32 orderHash)
        internal
    {
        // Ensure order is valid
        require(
            orderStatus != uint8(Status.ORDER_INVALID_MAKER_ASSET_AMOUNT),
            INVALID_ORDER_MAKER_ASSET_AMOUNT
        );
        require(
            orderStatus != uint8(Status.ORDER_INVALID_TAKER_ASSET_AMOUNT),
            INVALID_ORDER_TAKER_ASSET_AMOUNT
        );

        // Validate transaction signed by maker
        address makerAddress = getCurrentContextAddress();
        require(
            order.makerAddress == makerAddress,
            INVALID_CONTEXT
        );

        // Validate sender is allowed to cancel this order
        if (order.senderAddress != address(0)) {
            require(
                order.senderAddress == msg.sender,
                INVALID_SENDER
            );
        }
    }

    /// @dev Updates state with results of cancelling an order.
    ///      State is only updated if the order is currently fillable.
    ///      Otherwise, updating state would have no effect.
    /// @param order that was cancelled.
    /// @param orderStatus Status of order that was cancelled.
    /// @param orderHash Hash of order that was cancelled.
    /// @return stateUpdated Returns true only if state was updated.
    function updateCancelledState(
        Order memory order,
        uint8 orderStatus,
        bytes32 orderHash)
        internal
        returns (bool stateUpdated)
    {
        // Ensure order is fillable (otherwise cancelling does nothing)
        if (orderStatus != uint8(Status.ORDER_FILLABLE)) {
            emit ExchangeStatus(uint8(orderStatus), orderHash);
            stateUpdated = false;
            return stateUpdated;
        }

        // Perform cancel
        cancelled[orderHash] = true;
        stateUpdated = true;

        // Log cancel
        emit Cancel(
            order.makerAddress,
            order.feeRecipientAddress,
            orderHash,
            order.makerAssetData,
            order.takerAssetData
        );

        return stateUpdated;
    }

    /// @dev After calling, the order can not be filled anymore.
    /// @param order Order struct containing order specifications.
    /// @return True if the order state changed to cancelled.
    ///         False if the transaction was already cancelled or expired.
    function cancelOrder(Order memory order)
        public
        returns (bool)
    {
        // Fetch current order status
        bytes32 orderHash;
        uint8 orderStatus;
        uint256 takerAssetFilledAmount;
        (orderStatus, orderHash, takerAssetFilledAmount) = getOrderInfo(order);

        // Validate context
        validateCancelOrderContextOrRevert(order, orderStatus, orderHash);

        // Perform cancel
        return updateCancelledState(order, orderStatus, orderHash);
    }

    /// @dev Cancels all orders reated by sender with a salt less than or equal to the specified salt value.
    /// @param salt Orders created with a salt less or equal to this value will be cancelled.
    function cancelOrdersUpTo(uint256 salt)
        external
    {
        uint256 newMakerEpoch = salt + 1;  // makerEpoch is initialized to 0, so to cancelUpTo we need salt + 1
        require(
            newMakerEpoch > makerEpoch[msg.sender],  // epoch must be monotonically increasing
            INVALID_NEW_MAKER_EPOCH
        );
        makerEpoch[msg.sender] = newMakerEpoch;
        emit CancelUpTo(msg.sender, newMakerEpoch);
    }

    /// @dev Logs a Fill event with the given arguments.
    ///      The sole purpose of this function is to get around the stack variable limit.
    function emitFillEvent(
        Order memory order,
        address takerAddress,
        bytes32 orderHash,
        FillResults memory fillResults)
        internal
    {
        emit Fill(
            order.makerAddress,
            takerAddress,
            order.feeRecipientAddress,
            fillResults.makerAssetFilledAmount,
            fillResults.takerAssetFilledAmount,
            fillResults.makerFeePaid,
            fillResults.takerFeePaid,
            orderHash,
            order.makerAssetData,
            order.takerAssetData
        );
    }
}