aboutsummaryrefslogtreecommitdiffstats
path: root/packages/contract-wrappers/test/order_validation_test.ts
blob: 2afea2d5f198c54d394554059b7929d3e5353566 (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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import { BlockchainLifecycle } from '@0xproject/dev-utils';
import { FillScenarios } from '@0xproject/fill-scenarios';
import { OrderError } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai';
import * as Sinon from 'sinon';

import { ContractWrappers, ExchangeContractErrs, SignedOrder, Token } from '../src';
import { BalanceAndProxyAllowanceLazyStore } from '../src/stores/balance_proxy_allowance_lazy_store';
import { TradeSide, TransferType } from '../src/types';
import { ExchangeTransferSimulator } from '../src/utils/exchange_transfer_simulator';
import { OrderValidationUtils } from '../src/utils/order_validation_utils';

import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
import { TokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper';

chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);

describe('OrderValidation', () => {
    let contractWrappers: ContractWrappers;
    let userAddresses: string[];
    let tokens: Token[];
    let tokenUtils: TokenUtils;
    let exchangeContractAddress: string;
    let zrxTokenAddress: string;
    let fillScenarios: FillScenarios;
    let makerTokenAddress: string;
    let takerTokenAddress: string;
    let coinbase: string;
    let makerAddress: string;
    let takerAddress: string;
    let feeRecipient: string;
    const fillableAmount = new BigNumber(5);
    const fillTakerAmount = new BigNumber(5);
    const config = {
        networkId: constants.TESTRPC_NETWORK_ID,
    };
    before(async () => {
        contractWrappers = new ContractWrappers(provider, config);
        exchangeContractAddress = contractWrappers.exchange.getContractAddress();
        userAddresses = await web3Wrapper.getAvailableAddressesAsync();
        [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
        tokens = await contractWrappers.tokenRegistry.getTokensAsync();
        tokenUtils = new TokenUtils(tokens);
        zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
        fillScenarios = new FillScenarios(provider, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
        const [makerToken, takerToken] = tokenUtils.getDummyTokens();
        makerTokenAddress = makerToken.address;
        takerTokenAddress = takerToken.address;
    });
    beforeEach(async () => {
        await blockchainLifecycle.startAsync();
    });
    afterEach(async () => {
        await blockchainLifecycle.revertAsync();
    });
    describe('validateOrderFillableOrThrowAsync', () => {
        it('should succeed if the order is fillable', async () => {
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
        });
        it('should succeed if the maker is buying ZRX and has no ZRX balance', async () => {
            const makerFee = new BigNumber(2);
            const takerFee = new BigNumber(2);
            const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                makerTokenAddress,
                zrxTokenAddress,
                makerFee,
                takerFee,
                makerAddress,
                takerAddress,
                fillableAmount,
                feeRecipient,
            );
            const zrxMakerBalance = await contractWrappers.token.getBalanceAsync(zrxTokenAddress, makerAddress);
            await contractWrappers.token.transferAsync(zrxTokenAddress, makerAddress, takerAddress, zrxMakerBalance);
            await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
        });
        it('should succeed if the maker is buying ZRX and has no ZRX balance and there is no specified taker', async () => {
            const makerFee = new BigNumber(2);
            const takerFee = new BigNumber(2);
            const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                makerTokenAddress,
                zrxTokenAddress,
                makerFee,
                takerFee,
                makerAddress,
                constants.NULL_ADDRESS,
                fillableAmount,
                feeRecipient,
            );
            const zrxMakerBalance = await contractWrappers.token.getBalanceAsync(zrxTokenAddress, makerAddress);
            await contractWrappers.token.transferAsync(zrxTokenAddress, makerAddress, takerAddress, zrxMakerBalance);
            await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
        });
        it('should succeed if the order is asymmetric and fillable', async () => {
            const makerFillableAmount = fillableAmount;
            // tslint:disable-next-line:custom-no-magic-numbers
            const takerFillableAmount = fillableAmount.minus(4);
            const signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                makerFillableAmount,
                takerFillableAmount,
            );
            await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder);
        });
        it('should throw when the order is fully filled or cancelled', async () => {
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            await contractWrappers.exchange.cancelOrderAsync(signedOrder, fillableAmount);
            return expect(contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder)).to.be.rejectedWith(
                ExchangeContractErrs.OrderRemainingFillAmountZero,
            );
        });
        it('should throw when order is expired', async () => {
            const expirationInPast = new BigNumber(1496826058); // 7th Jun 2017
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
                expirationInPast,
            );
            return expect(contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder)).to.be.rejectedWith(
                ExchangeContractErrs.OrderFillExpired,
            );
        });
    });
    describe('validateFillOrderAndThrowIfInvalidAsync', () => {
        it('should throw when the fill amount is zero', async () => {
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            const zeroFillAmount = new BigNumber(0);
            return expect(
                contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
                    signedOrder,
                    zeroFillAmount,
                    takerAddress,
                ),
            ).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
        });
        it('should throw when the signature is invalid', async () => {
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            // 27 <--> 28
            // tslint:disable-next-line:custom-no-magic-numbers
            signedOrder.ecSignature.v = 28 - signedOrder.ecSignature.v + 27;
            return expect(
                contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
                    signedOrder,
                    fillableAmount,
                    takerAddress,
                ),
            ).to.be.rejectedWith(OrderError.InvalidSignature);
        });
        it('should throw when the order is fully filled or cancelled', async () => {
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            await contractWrappers.exchange.cancelOrderAsync(signedOrder, fillableAmount);
            return expect(
                contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
                    signedOrder,
                    fillableAmount,
                    takerAddress,
                ),
            ).to.be.rejectedWith(ExchangeContractErrs.OrderRemainingFillAmountZero);
        });
        it('should throw when sender is not a taker', async () => {
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            // tslint:disable-next-line:custom-no-magic-numbers
            const nonTakerAddress = userAddresses[6];
            return expect(
                contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
                    signedOrder,
                    fillTakerAmount,
                    nonTakerAddress,
                ),
            ).to.be.rejectedWith(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker);
        });
        it('should throw when order is expired', async () => {
            const expirationInPast = new BigNumber(1496826058); // 7th Jun 2017
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
                expirationInPast,
            );
            return expect(
                contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
                    signedOrder,
                    fillTakerAmount,
                    takerAddress,
                ),
            ).to.be.rejectedWith(ExchangeContractErrs.OrderFillExpired);
        });
        it('should throw when there a rounding error would have occurred', async () => {
            const makerAmount = new BigNumber(3);
            const takerAmount = new BigNumber(5);
            const signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                makerAmount,
                takerAmount,
            );
            const fillTakerAmountThatCausesRoundingError = new BigNumber(3);
            return expect(
                contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
                    signedOrder,
                    fillTakerAmountThatCausesRoundingError,
                    takerAddress,
                ),
            ).to.be.rejectedWith(ExchangeContractErrs.OrderFillRoundingError);
        });
    });
    describe('#validateFillOrKillOrderAndThrowIfInvalidAsync', () => {
        it('should throw if remaining fillAmount is less then the desired fillAmount', async () => {
            const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            const tooLargeFillAmount = new BigNumber(7);
            const fillAmountDifference = tooLargeFillAmount.minus(fillableAmount);
            await contractWrappers.token.transferAsync(takerTokenAddress, coinbase, takerAddress, fillAmountDifference);
            await contractWrappers.token.setProxyAllowanceAsync(takerTokenAddress, takerAddress, tooLargeFillAmount);
            await contractWrappers.token.transferAsync(makerTokenAddress, coinbase, makerAddress, fillAmountDifference);
            await contractWrappers.token.setProxyAllowanceAsync(makerTokenAddress, makerAddress, tooLargeFillAmount);

            return expect(
                contractWrappers.exchange.validateFillOrKillOrderThrowIfInvalidAsync(
                    signedOrder,
                    tooLargeFillAmount,
                    takerAddress,
                ),
            ).to.be.rejectedWith(ExchangeContractErrs.InsufficientRemainingFillAmount);
        });
    });
    describe('validateCancelOrderAndThrowIfInvalidAsync', () => {
        let signedOrder: SignedOrder;
        const cancelAmount = new BigNumber(3);
        beforeEach(async () => {
            [coinbase, makerAddress, takerAddress] = userAddresses;
            const [makerToken, takerToken] = tokenUtils.getDummyTokens();
            makerTokenAddress = makerToken.address;
            takerTokenAddress = takerToken.address;
            signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
        });
        it('should throw when cancel amount is zero', async () => {
            const zeroCancelAmount = new BigNumber(0);
            return expect(
                contractWrappers.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, zeroCancelAmount),
            ).to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
        });
        it('should throw when order is expired', async () => {
            const expirationInPast = new BigNumber(1496826058); // 7th Jun 2017
            const expiredSignedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                fillableAmount,
                expirationInPast,
            );
            return expect(
                contractWrappers.exchange.validateCancelOrderThrowIfInvalidAsync(expiredSignedOrder, cancelAmount),
            ).to.be.rejectedWith(ExchangeContractErrs.OrderCancelExpired);
        });
        it('should throw when order is already cancelled or filled', async () => {
            await contractWrappers.exchange.cancelOrderAsync(signedOrder, fillableAmount);
            return expect(
                contractWrappers.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, fillableAmount),
            ).to.be.rejectedWith(ExchangeContractErrs.OrderAlreadyCancelledOrFilled);
        });
    });
    describe('#validateFillOrderBalancesAllowancesThrowIfInvalidAsync', () => {
        let exchangeTransferSimulator: ExchangeTransferSimulator;
        let transferFromAsync: Sinon.SinonSpy;
        const bigNumberMatch = (expected: BigNumber) => {
            return Sinon.match((value: BigNumber) => value.eq(expected));
        };
        beforeEach('create exchangeTransferSimulator', async () => {
            const balanceAndProxyAllowanceLazyStore = new BalanceAndProxyAllowanceLazyStore(
                contractWrappers.token,
                BlockParamLiteral.Latest,
            );
            exchangeTransferSimulator = new ExchangeTransferSimulator(balanceAndProxyAllowanceLazyStore);
            transferFromAsync = Sinon.spy();
            exchangeTransferSimulator.transferFromAsync = transferFromAsync as any;
        });
        it('should call exchangeTransferSimulator.transferFrom in a correct order', async () => {
            const makerFee = new BigNumber(2);
            const takerFee = new BigNumber(2);
            const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerFee,
                takerFee,
                makerAddress,
                takerAddress,
                fillableAmount,
                feeRecipient,
            );
            await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
                exchangeTransferSimulator,
                signedOrder,
                fillableAmount,
                takerAddress,
                zrxTokenAddress,
            );
            // tslint:disable-next-line:custom-no-magic-numbers
            expect(transferFromAsync.callCount).to.be.equal(4);
            expect(
                transferFromAsync
                    .getCall(0)
                    .calledWith(
                        makerTokenAddress,
                        makerAddress,
                        takerAddress,
                        bigNumberMatch(fillableAmount),
                        TradeSide.Maker,
                        TransferType.Trade,
                    ),
            ).to.be.true();
            expect(
                transferFromAsync
                    .getCall(1)
                    .calledWith(
                        takerTokenAddress,
                        takerAddress,
                        makerAddress,
                        bigNumberMatch(fillableAmount),
                        TradeSide.Taker,
                        TransferType.Trade,
                    ),
            ).to.be.true();
            expect(
                transferFromAsync
                    .getCall(2)
                    .calledWith(
                        zrxTokenAddress,
                        makerAddress,
                        feeRecipient,
                        bigNumberMatch(makerFee),
                        TradeSide.Maker,
                        TransferType.Fee,
                    ),
            ).to.be.true();
            expect(
                transferFromAsync
                    .getCall(3)
                    .calledWith(
                        zrxTokenAddress,
                        takerAddress,
                        feeRecipient,
                        bigNumberMatch(takerFee),
                        TradeSide.Taker,
                        TransferType.Fee,
                    ),
            ).to.be.true();
        });
        it('should call exchangeTransferSimulator.transferFrom with correct values for an open order', async () => {
            const makerFee = new BigNumber(2);
            const takerFee = new BigNumber(2);
            const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerFee,
                takerFee,
                makerAddress,
                constants.NULL_ADDRESS,
                fillableAmount,
                feeRecipient,
            );
            await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
                exchangeTransferSimulator,
                signedOrder,
                fillableAmount,
                takerAddress,
                zrxTokenAddress,
            );
            // tslint:disable-next-line:custom-no-magic-numbers
            expect(transferFromAsync.callCount).to.be.equal(4);
            expect(
                transferFromAsync
                    .getCall(0)
                    .calledWith(
                        makerTokenAddress,
                        makerAddress,
                        takerAddress,
                        bigNumberMatch(fillableAmount),
                        TradeSide.Maker,
                        TransferType.Trade,
                    ),
            ).to.be.true();
            expect(
                transferFromAsync
                    .getCall(1)
                    .calledWith(
                        takerTokenAddress,
                        takerAddress,
                        makerAddress,
                        bigNumberMatch(fillableAmount),
                        TradeSide.Taker,
                        TransferType.Trade,
                    ),
            ).to.be.true();
            expect(
                transferFromAsync
                    .getCall(2)
                    .calledWith(
                        zrxTokenAddress,
                        makerAddress,
                        feeRecipient,
                        bigNumberMatch(makerFee),
                        TradeSide.Maker,
                        TransferType.Fee,
                    ),
            ).to.be.true();
            expect(
                transferFromAsync
                    .getCall(3)
                    .calledWith(
                        zrxTokenAddress,
                        takerAddress,
                        feeRecipient,
                        bigNumberMatch(takerFee),
                        TradeSide.Taker,
                        TransferType.Fee,
                    ),
            ).to.be.true();
        });
        it('should correctly round the fillMakerTokenAmount', async () => {
            const makerTokenAmount = new BigNumber(3);
            const takerTokenAmount = new BigNumber(1);
            const signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerAddress,
                takerAddress,
                makerTokenAmount,
                takerTokenAmount,
            );
            await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
                exchangeTransferSimulator,
                signedOrder,
                takerTokenAmount,
                takerAddress,
                zrxTokenAddress,
            );
            // tslint:disable-next-line:custom-no-magic-numbers
            expect(transferFromAsync.callCount).to.be.equal(4);
            const makerFillAmount = transferFromAsync.getCall(0).args[3];
            expect(makerFillAmount).to.be.bignumber.equal(makerTokenAmount);
        });
        it('should correctly round the makerFeeAmount', async () => {
            const makerFee = new BigNumber(2);
            const takerFee = new BigNumber(4);
            const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                makerTokenAddress,
                takerTokenAddress,
                makerFee,
                takerFee,
                makerAddress,
                takerAddress,
                fillableAmount,
                constants.NULL_ADDRESS,
            );
            const fillTakerTokenAmount = fillableAmount.div(2).round(0);
            await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
                exchangeTransferSimulator,
                signedOrder,
                fillTakerTokenAmount,
                takerAddress,
                zrxTokenAddress,
            );
            const makerPartialFee = makerFee.div(2);
            const takerPartialFee = takerFee.div(2);
            // tslint:disable-next-line:custom-no-magic-numbers
            expect(transferFromAsync.callCount).to.be.equal(4);
            const partialMakerFee = transferFromAsync.getCall(2).args[3];
            expect(partialMakerFee).to.be.bignumber.equal(makerPartialFee);
            const partialTakerFee = transferFromAsync.getCall(3).args[3];
            expect(partialTakerFee).to.be.bignumber.equal(takerPartialFee);
        });
    });
}); // tslint:disable-line:max-file-line-count