aboutsummaryrefslogtreecommitdiffstats
path: root/packages/contracts/test/utils/match_order_tester.ts
blob: 7d763c6df63bef5e4b1079007e86fbd68b1af77e (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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
import { assetDataUtils, orderHashUtils } from '@0xproject/order-utils';
import { AssetProxyId, SignedOrder } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai';
import * as _ from 'lodash';

import { TransactionReceiptWithDecodedLogs } from '../../../../node_modules/ethereum-types';

import { chaiSetup } from './chai_setup';
import { ERC20Wrapper } from './erc20_wrapper';
import { ERC721Wrapper } from './erc721_wrapper';
import { ExchangeWrapper } from './exchange_wrapper';
import {
    ERC20BalancesByOwner,
    ERC721TokenIdsByOwner,
    OrderInfo,
    OrderStatus,
    TransferAmountsByMatchOrders as TransferAmounts,
    TransferAmountsLoggedByMatchOrders as LoggedTransferAmounts,
} from './types';

chaiSetup.configure();
const expect = chai.expect;

export class MatchOrderTester {
    private readonly _exchangeWrapper: ExchangeWrapper;
    private readonly _erc20Wrapper: ERC20Wrapper;
    private readonly _erc721Wrapper: ERC721Wrapper;
    private readonly _feeTokenAddress: string;
    /// @dev Checks values from the logs produced by Exchange.matchOrders against the expected transfer amounts.
    ///      Values include the amounts transferred from the left/right makers and taker, along with
    ///      the fees paid on each matched order. These are also the return values of MatchOrders.
    /// @param signedOrderLeft First matched order.
    /// @param signedOrderRight Second matched order.
    /// @param transactionReceipt Transaction receipt and logs produced by Exchange.matchOrders.
    /// @param takerAddress Address of taker (account that called Exchange.matchOrders)
    /// @param expectedTransferAmounts Expected amounts transferred as a result of order matching.
    private static async _verifyLogsAsync(
        signedOrderLeft: SignedOrder,
        signedOrderRight: SignedOrder,
        transactionReceipt: TransactionReceiptWithDecodedLogs,
        takerAddress: string,
        expectedTransferAmounts: TransferAmounts,
    ): Promise<void> {
        // Should have two logs -- one for each order.
        expect(transactionReceipt.logs.length, 'Checking number of logs').to.be.equal(2);
        // First log is for left fill
        const leftLog = (transactionReceipt.logs[0] as any).args as LoggedTransferAmounts;
        expect(leftLog.makerAddress, 'Checking logged maker address of left order').to.be.equal(
            signedOrderLeft.makerAddress,
        );
        expect(leftLog.takerAddress, 'Checking logged taker address of right order').to.be.equal(takerAddress);
        const amountBoughtByLeftMaker = new BigNumber(leftLog.takerAssetFilledAmount);
        const amountSoldByLeftMaker = new BigNumber(leftLog.makerAssetFilledAmount);
        const feePaidByLeftMaker = new BigNumber(leftLog.makerFeePaid);
        const feePaidByTakerLeft = new BigNumber(leftLog.takerFeePaid);
        // Second log is for right fill
        const rightLog = (transactionReceipt.logs[1] as any).args as LoggedTransferAmounts;
        expect(rightLog.makerAddress, 'Checking logged maker address of right order').to.be.equal(
            signedOrderRight.makerAddress,
        );
        expect(rightLog.takerAddress, 'Checking loggerd taker address of right order').to.be.equal(takerAddress);
        const amountBoughtByRightMaker = new BigNumber(rightLog.takerAssetFilledAmount);
        const amountSoldByRightMaker = new BigNumber(rightLog.makerAssetFilledAmount);
        const feePaidByRightMaker = new BigNumber(rightLog.makerFeePaid);
        const feePaidByTakerRight = new BigNumber(rightLog.takerFeePaid);
        // Derive amount received by taker
        const amountReceivedByTaker = amountSoldByLeftMaker.sub(amountBoughtByRightMaker);
        // Verify log values - left order
        expect(
            expectedTransferAmounts.amountBoughtByLeftMaker,
            'Checking logged amount bought by left maker',
        ).to.be.bignumber.equal(amountBoughtByLeftMaker);
        expect(
            expectedTransferAmounts.amountSoldByLeftMaker,
            'Checking logged amount sold by left maker',
        ).to.be.bignumber.equal(amountSoldByLeftMaker);
        expect(
            expectedTransferAmounts.feePaidByLeftMaker,
            'Checking logged fee paid by left maker',
        ).to.be.bignumber.equal(feePaidByLeftMaker);
        expect(
            expectedTransferAmounts.feePaidByTakerLeft,
            'Checking logged fee paid on left order by taker',
        ).to.be.bignumber.equal(feePaidByTakerLeft);
        // Verify log values - right order
        expect(
            expectedTransferAmounts.amountBoughtByRightMaker,
            'Checking logged amount bought by right maker',
        ).to.be.bignumber.equal(amountBoughtByRightMaker);
        expect(
            expectedTransferAmounts.amountSoldByRightMaker,
            'Checking logged amount sold by right maker',
        ).to.be.bignumber.equal(amountSoldByRightMaker);
        expect(
            expectedTransferAmounts.feePaidByRightMaker,
            'Checking logged fee paid by right maker',
        ).to.be.bignumber.equal(feePaidByRightMaker);
        expect(
            expectedTransferAmounts.feePaidByTakerRight,
            'Checking logged fee paid on right order by taker',
        ).to.be.bignumber.equal(feePaidByTakerRight);
        // Verify derived amount received by taker
        expect(
            expectedTransferAmounts.amountReceivedByTaker,
            'Checking logged amount received by taker',
        ).to.be.bignumber.equal(amountReceivedByTaker);
    }
    /// @dev Verifies all expected ERC20 and ERC721 account holdings match the real holdings.
    /// @param expectedERC20BalancesByOwner Expected ERC20 balances.
    /// @param realERC20BalancesByOwner Real ERC20 balances.
    /// @param expectedERC721TokenIdsByOwner Expected ERC721 token owners.
    /// @param realERC721TokenIdsByOwner Real ERC20 token owners.
    private static async _verifyAllKnownBalancesAsync(
        expectedERC20BalancesByOwner: ERC20BalancesByOwner,
        realERC20BalancesByOwner: ERC20BalancesByOwner,
        expectedERC721TokenIdsByOwner: ERC721TokenIdsByOwner,
        realERC721TokenIdsByOwner: ERC721TokenIdsByOwner,
    ): Promise<void> {
        // ERC20 Balances
        const areERC20BalancesEqual = _.isEqual(expectedERC20BalancesByOwner, realERC20BalancesByOwner);
        expect(areERC20BalancesEqual, 'Checking all known ERC20 account balances').to.be.true();
        // ERC721 Token Ids
        const sortedExpectedNewERC721TokenIdsByOwner = _.mapValues(expectedERC721TokenIdsByOwner, tokenIdsByOwner => {
            _.mapValues(tokenIdsByOwner, tokenIds => {
                _.sortBy(tokenIds);
            });
        });
        const sortedNewERC721TokenIdsByOwner = _.mapValues(realERC721TokenIdsByOwner, tokenIdsByOwner => {
            _.mapValues(tokenIdsByOwner, tokenIds => {
                _.sortBy(tokenIds);
            });
        });
        const areERC721TokenIdsEqual = _.isEqual(
            sortedExpectedNewERC721TokenIdsByOwner,
            sortedNewERC721TokenIdsByOwner,
        );
        expect(areERC721TokenIdsEqual, 'Checking all known ERC721 account balances').to.be.true();
    }
    /// @dev Constructs new MatchOrderTester.
    /// @param exchangeWrapper Used to call to the Exchange.
    /// @param erc20Wrapper Used to fetch ERC20 balances.
    /// @param erc721Wrapper Used to fetch ERC721 token owners.
    /// @param feeTokenAddress Address of ERC20 fee token.
    constructor(
        exchangeWrapper: ExchangeWrapper,
        erc20Wrapper: ERC20Wrapper,
        erc721Wrapper: ERC721Wrapper,
        feeTokenAddress: string,
    ) {
        this._exchangeWrapper = exchangeWrapper;
        this._erc20Wrapper = erc20Wrapper;
        this._erc721Wrapper = erc721Wrapper;
        this._feeTokenAddress = feeTokenAddress;
    }
    /// @dev Matches two complementary orders and verifies results.
    ///      Validation either succeeds or throws.
    /// @param signedOrderLeft First matched order.
    /// @param signedOrderRight Second matched order.
    /// @param takerAddress Address of taker (the address who matched the two orders)
    /// @param erc20BalancesByOwner Current ERC20 balances.
    /// @param erc721TokenIdsByOwner Current ERC721 token owners.
    /// @param expectedTransferAmounts Expected amounts transferred as a result of order matching.
    /// @param initialLeftOrderFilledAmount How much left order has been filled, prior to matching orders.
    /// @param initialRightOrderFilledAmount How much the right order has been filled, prior to matching orders.
    /// @return New ERC20 balances & ERC721 token owners.
    public async matchOrdersAndVerifyBalancesAsync(
        signedOrderLeft: SignedOrder,
        signedOrderRight: SignedOrder,
        takerAddress: string,
        erc20BalancesByOwner: ERC20BalancesByOwner,
        erc721TokenIdsByOwner: ERC721TokenIdsByOwner,
        expectedTransferAmounts: TransferAmounts,
        initialLeftOrderFilledAmount?: BigNumber,
        initialRightOrderFilledAmount?: BigNumber,
    ): Promise<[ERC20BalancesByOwner, ERC721TokenIdsByOwner]> {
        // Assign default values to optional parameters if undefined
        if (initialLeftOrderFilledAmount === undefined) {
            initialLeftOrderFilledAmount = new BigNumber(0);
        }
        if (initialRightOrderFilledAmount === undefined) {
            initialRightOrderFilledAmount = new BigNumber(0);
        }
        // Verify initial order states
        await this._verifyInitialOrderStatesAsync(
            signedOrderLeft,
            signedOrderRight,
            initialLeftOrderFilledAmount,
            initialRightOrderFilledAmount,
        );
        // Match left & right orders
        const transactionReceipt = await this._exchangeWrapper.matchOrdersAsync(
            signedOrderLeft,
            signedOrderRight,
            takerAddress,
        );
        const newERC20BalancesByOwner = await this._erc20Wrapper.getBalancesAsync();
        const newERC721TokenIdsByOwner = await this._erc721Wrapper.getBalancesAsync();
        // Verify logs
        await MatchOrderTester._verifyLogsAsync(
            signedOrderLeft,
            signedOrderRight,
            transactionReceipt,
            takerAddress,
            expectedTransferAmounts,
        );
        // Verify exchange state
        await this._verifyExchangeStateAsync(
            signedOrderLeft,
            signedOrderRight,
            initialLeftOrderFilledAmount,
            initialRightOrderFilledAmount,
            expectedTransferAmounts,
        );
        // Verify balances of makers, taker, and fee recipients
        await this._verifyBalancesAsync(
            signedOrderLeft,
            signedOrderRight,
            erc20BalancesByOwner,
            erc721TokenIdsByOwner,
            newERC20BalancesByOwner,
            newERC721TokenIdsByOwner,
            expectedTransferAmounts,
            takerAddress,
        );
        return [newERC20BalancesByOwner, newERC721TokenIdsByOwner];
    }
    /// @dev Verifies initial exchange state for the left and right orders.
    /// @param signedOrderLeft First matched order.
    /// @param signedOrderRight Second matched order.
    /// @param expectedOrderFilledAmountLeft How much left order has been filled, prior to matching orders.
    /// @param expectedOrderFilledAmountRight How much the right order has been filled, prior to matching orders.
    private async _verifyInitialOrderStatesAsync(
        signedOrderLeft: SignedOrder,
        signedOrderRight: SignedOrder,
        expectedOrderFilledAmountLeft: BigNumber,
        expectedOrderFilledAmountRight: BigNumber,
    ): Promise<void> {
        // Verify left order initial state
        const orderTakerAssetFilledAmountLeft = await this._exchangeWrapper.getTakerAssetFilledAmountAsync(
            orderHashUtils.getOrderHashHex(signedOrderLeft),
        );
        expect(expectedOrderFilledAmountLeft, 'Checking inital state of left order').to.be.bignumber.equal(
            orderTakerAssetFilledAmountLeft,
        );
        // Verify right order initial state
        const orderTakerAssetFilledAmountRight = await this._exchangeWrapper.getTakerAssetFilledAmountAsync(
            orderHashUtils.getOrderHashHex(signedOrderRight),
        );
        expect(expectedOrderFilledAmountRight, 'Checking inital state of right order').to.be.bignumber.equal(
            orderTakerAssetFilledAmountRight,
        );
    }
    /// @dev Verifies the exchange state against the expected amounts transferred by from matching orders.
    /// @param signedOrderLeft First matched order.
    /// @param signedOrderRight Second matched order.
    /// @param initialLeftOrderFilledAmount How much left order has been filled, prior to matching orders.
    /// @param initialRightOrderFilledAmount How much the right order has been filled, prior to matching orders.
    /// @return TransferAmounts A struct containing the expected transfer amounts.
    private async _verifyExchangeStateAsync(
        signedOrderLeft: SignedOrder,
        signedOrderRight: SignedOrder,
        initialLeftOrderFilledAmount: BigNumber,
        initialRightOrderFilledAmount: BigNumber,
        expectedTransferAmounts: TransferAmounts,
    ): Promise<void> {
        // Verify state for left order: amount bought by left maker
        let amountBoughtByLeftMaker = await this._exchangeWrapper.getTakerAssetFilledAmountAsync(
            orderHashUtils.getOrderHashHex(signedOrderLeft),
        );
        amountBoughtByLeftMaker = amountBoughtByLeftMaker.minus(initialLeftOrderFilledAmount);
        expect(
            expectedTransferAmounts.amountBoughtByLeftMaker,
            'Checking exchange state for left order',
        ).to.be.bignumber.equal(amountBoughtByLeftMaker);
        // Verify state for right order: amount bought by right maker
        let amountBoughtByRightMaker = await this._exchangeWrapper.getTakerAssetFilledAmountAsync(
            orderHashUtils.getOrderHashHex(signedOrderRight),
        );
        amountBoughtByRightMaker = amountBoughtByRightMaker.minus(initialRightOrderFilledAmount);
        expect(
            expectedTransferAmounts.amountBoughtByRightMaker,
            'Checking exchange state for right order',
        ).to.be.bignumber.equal(amountBoughtByRightMaker);
        // Verify left order status
        const maxAmountBoughtByLeftMaker = signedOrderLeft.takerAssetAmount.minus(initialLeftOrderFilledAmount);
        const leftOrderInfo: OrderInfo = await this._exchangeWrapper.getOrderInfoAsync(signedOrderLeft);
        const leftExpectedStatus = expectedTransferAmounts.amountBoughtByLeftMaker.equals(maxAmountBoughtByLeftMaker)
            ? OrderStatus.FULLY_FILLED
            : OrderStatus.FILLABLE;
        expect(leftOrderInfo.orderStatus as OrderStatus, 'Checking exchange status for left order').to.be.equal(
            leftExpectedStatus,
        );
        // Verify right order status
        const maxAmountBoughtByRightMaker = signedOrderRight.takerAssetAmount.minus(initialRightOrderFilledAmount);
        const rightOrderInfo: OrderInfo = await this._exchangeWrapper.getOrderInfoAsync(signedOrderRight);
        const rightExpectedStatus = expectedTransferAmounts.amountBoughtByRightMaker.equals(maxAmountBoughtByRightMaker)
            ? OrderStatus.FULLY_FILLED
            : OrderStatus.FILLABLE;
        expect(rightOrderInfo.orderStatus as OrderStatus, 'Checking exchange status for right order').to.be.equal(
            rightExpectedStatus,
        );
    }
    /// @dev Verifies account balances after matching orders.
    /// @param signedOrderLeft First matched order.
    /// @param signedOrderRight Second matched order.
    /// @param initialERC20BalancesByOwner ERC20 balances prior to order matching.
    /// @param initialERC721TokenIdsByOwner ERC721 token owners prior to order matching.
    /// @param finalERC20BalancesByOwner ERC20 balances after order matching.
    /// @param finalERC721TokenIdsByOwner ERC721 token owners after order matching.
    /// @param expectedTransferAmounts Expected amounts transferred as a result of order matching.
    /// @param takerAddress Address of taker (account that called Exchange.matchOrders).
    private async _verifyBalancesAsync(
        signedOrderLeft: SignedOrder,
        signedOrderRight: SignedOrder,
        initialERC20BalancesByOwner: ERC20BalancesByOwner,
        initialERC721TokenIdsByOwner: ERC721TokenIdsByOwner,
        finalERC20BalancesByOwner: ERC20BalancesByOwner,
        finalERC721TokenIdsByOwner: ERC721TokenIdsByOwner,
        expectedTransferAmounts: TransferAmounts,
        takerAddress: string,
    ): Promise<void> {
        let expectedERC20BalancesByOwner: ERC20BalancesByOwner;
        let expectedERC721TokenIdsByOwner: ERC721TokenIdsByOwner;
        [expectedERC20BalancesByOwner, expectedERC721TokenIdsByOwner] = this._calculateExpectedBalances(
            signedOrderLeft,
            signedOrderRight,
            takerAddress,
            initialERC20BalancesByOwner,
            initialERC721TokenIdsByOwner,
            expectedTransferAmounts,
        );
        // Verify balances of makers, taker, and fee recipients
        await this._verifyMakerTakerAndFeeRecipientBalancesAsync(
            signedOrderLeft,
            signedOrderRight,
            expectedERC20BalancesByOwner,
            finalERC20BalancesByOwner,
            expectedERC721TokenIdsByOwner,
            finalERC721TokenIdsByOwner,
            takerAddress,
        );
        // Verify balances for all known accounts
        await MatchOrderTester._verifyAllKnownBalancesAsync(
            expectedERC20BalancesByOwner,
            finalERC20BalancesByOwner,
            expectedERC721TokenIdsByOwner,
            finalERC721TokenIdsByOwner,
        );
    }
    /// @dev Calculates the expected balances of order makers, fee recipients, and the taker,
    ///      as a result of matching two orders.
    /// @param signedOrderRight First matched order.
    /// @param signedOrderRight Second matched order.
    /// @param takerAddress Address of taker (the address who matched the two orders)
    /// @param erc20BalancesByOwner Current ERC20 balances.
    /// @param erc721TokenIdsByOwner Current ERC721 token owners.
    /// @param expectedTransferAmounts Expected amounts transferred as a result of order matching.
    /// @return Expected ERC20 balances & ERC721 token owners after orders have been matched.
    private _calculateExpectedBalances(
        signedOrderLeft: SignedOrder,
        signedOrderRight: SignedOrder,
        takerAddress: string,
        erc20BalancesByOwner: ERC20BalancesByOwner,
        erc721TokenIdsByOwner: ERC721TokenIdsByOwner,
        expectedTransferAmounts: TransferAmounts,
    ): [ERC20BalancesByOwner, ERC721TokenIdsByOwner] {
        const makerAddressLeft = signedOrderLeft.makerAddress;
        const makerAddressRight = signedOrderRight.makerAddress;
        const feeRecipientAddressLeft = signedOrderLeft.feeRecipientAddress;
        const feeRecipientAddressRight = signedOrderRight.feeRecipientAddress;
        // Operations are performed on copies of the balances
        const expectedNewERC20BalancesByOwner = _.cloneDeep(erc20BalancesByOwner);
        const expectedNewERC721TokenIdsByOwner = _.cloneDeep(erc721TokenIdsByOwner);
        // Left Maker Asset (Right Taker Asset)
        const makerAssetProxyIdLeft = assetDataUtils.decodeAssetProxyId(signedOrderLeft.makerAssetData);
        if (makerAssetProxyIdLeft === AssetProxyId.ERC20) {
            // Decode asset data
            const erc20AssetData = assetDataUtils.decodeERC20AssetData(signedOrderLeft.makerAssetData);
            const makerAssetAddressLeft = erc20AssetData.tokenAddress;
            const takerAssetAddressRight = makerAssetAddressLeft;
            // Left Maker
            expectedNewERC20BalancesByOwner[makerAddressLeft][makerAssetAddressLeft] = expectedNewERC20BalancesByOwner[
                makerAddressLeft
            ][makerAssetAddressLeft].minus(expectedTransferAmounts.amountSoldByLeftMaker);
            // Right Maker
            expectedNewERC20BalancesByOwner[makerAddressRight][
                takerAssetAddressRight
            ] = expectedNewERC20BalancesByOwner[makerAddressRight][takerAssetAddressRight].add(
                expectedTransferAmounts.amountBoughtByRightMaker,
            );
            // Taker
            expectedNewERC20BalancesByOwner[takerAddress][makerAssetAddressLeft] = expectedNewERC20BalancesByOwner[
                takerAddress
            ][makerAssetAddressLeft].add(expectedTransferAmounts.amountReceivedByTaker);
        } else if (makerAssetProxyIdLeft === AssetProxyId.ERC721) {
            // Decode asset data
            const erc721AssetData = assetDataUtils.decodeERC721AssetData(signedOrderLeft.makerAssetData);
            const makerAssetAddressLeft = erc721AssetData.tokenAddress;
            const makerAssetIdLeft = erc721AssetData.tokenId;
            const takerAssetAddressRight = makerAssetAddressLeft;
            const takerAssetIdRight = makerAssetIdLeft;
            // Left Maker
            _.remove(expectedNewERC721TokenIdsByOwner[makerAddressLeft][makerAssetAddressLeft], makerAssetIdLeft);
            // Right Maker
            expectedNewERC721TokenIdsByOwner[makerAddressRight][takerAssetAddressRight].push(takerAssetIdRight);
            // Taker: Since there is only 1 asset transferred, the taker does not receive any of the left maker asset.
        }
        // Left Taker Asset (Right Maker Asset)
        // Note: This exchange is only between the order makers: the Taker does not receive any of the left taker asset.
        const takerAssetProxyIdLeft = assetDataUtils.decodeAssetProxyId(signedOrderLeft.takerAssetData);
        if (takerAssetProxyIdLeft === AssetProxyId.ERC20) {
            // Decode asset data
            const erc20AssetData = assetDataUtils.decodeERC20AssetData(signedOrderLeft.takerAssetData);
            const takerAssetAddressLeft = erc20AssetData.tokenAddress;
            const makerAssetAddressRight = takerAssetAddressLeft;
            // Left Maker
            expectedNewERC20BalancesByOwner[makerAddressLeft][takerAssetAddressLeft] = expectedNewERC20BalancesByOwner[
                makerAddressLeft
            ][takerAssetAddressLeft].add(expectedTransferAmounts.amountBoughtByLeftMaker);
            // Right Maker
            expectedNewERC20BalancesByOwner[makerAddressRight][
                makerAssetAddressRight
            ] = expectedNewERC20BalancesByOwner[makerAddressRight][makerAssetAddressRight].minus(
                expectedTransferAmounts.amountSoldByRightMaker,
            );
        } else if (takerAssetProxyIdLeft === AssetProxyId.ERC721) {
            // Decode asset data
            const erc721AssetData = assetDataUtils.decodeERC721AssetData(signedOrderRight.makerAssetData);
            const makerAssetAddressRight = erc721AssetData.tokenAddress;
            const makerAssetIdRight = erc721AssetData.tokenId;
            const takerAssetAddressLeft = makerAssetAddressRight;
            const takerAssetIdLeft = makerAssetIdRight;
            // Right Maker
            _.remove(expectedNewERC721TokenIdsByOwner[makerAddressRight][makerAssetAddressRight], makerAssetIdRight);
            // Left Maker
            expectedNewERC721TokenIdsByOwner[makerAddressLeft][takerAssetAddressLeft].push(takerAssetIdLeft);
        }
        // Left Maker Fees
        expectedNewERC20BalancesByOwner[makerAddressLeft][this._feeTokenAddress] = expectedNewERC20BalancesByOwner[
            makerAddressLeft
        ][this._feeTokenAddress].minus(expectedTransferAmounts.feePaidByLeftMaker);
        // Right Maker Fees
        expectedNewERC20BalancesByOwner[makerAddressRight][this._feeTokenAddress] = expectedNewERC20BalancesByOwner[
            makerAddressRight
        ][this._feeTokenAddress].minus(expectedTransferAmounts.feePaidByRightMaker);
        // Taker Fees
        expectedNewERC20BalancesByOwner[takerAddress][this._feeTokenAddress] = expectedNewERC20BalancesByOwner[
            takerAddress
        ][this._feeTokenAddress].minus(
            expectedTransferAmounts.feePaidByTakerLeft.add(expectedTransferAmounts.feePaidByTakerRight),
        );
        // Left Fee Recipient Fees
        expectedNewERC20BalancesByOwner[feeRecipientAddressLeft][
            this._feeTokenAddress
        ] = expectedNewERC20BalancesByOwner[feeRecipientAddressLeft][this._feeTokenAddress].add(
            expectedTransferAmounts.feePaidByLeftMaker.add(expectedTransferAmounts.feePaidByTakerLeft),
        );
        // Right Fee Recipient Fees
        expectedNewERC20BalancesByOwner[feeRecipientAddressRight][
            this._feeTokenAddress
        ] = expectedNewERC20BalancesByOwner[feeRecipientAddressRight][this._feeTokenAddress].add(
            expectedTransferAmounts.feePaidByRightMaker.add(expectedTransferAmounts.feePaidByTakerRight),
        );

        return [expectedNewERC20BalancesByOwner, expectedNewERC721TokenIdsByOwner];
    }
    /// @dev
    /// @param signedOrderLeft First matched order.
    /// @param signedOrderRight Second matched order.
    /// @param expectedERC20BalancesByOwner Expected ERC20 balances.
    /// @param realERC20BalancesByOwner Real ERC20 balances.
    /// @param expectedERC721TokenIdsByOwner Expected ERC721 token owners.
    /// @param realERC721TokenIdsByOwner Real ERC20 token owners.
    /// @param takerAddress Address of taker (account that called Exchange.matchOrders).
    private async _verifyMakerTakerAndFeeRecipientBalancesAsync(
        signedOrderLeft: SignedOrder,
        signedOrderRight: SignedOrder,
        expectedERC20BalancesByOwner: ERC20BalancesByOwner,
        realERC20BalancesByOwner: ERC20BalancesByOwner,
        expectedERC721TokenIdsByOwner: ERC721TokenIdsByOwner,
        realERC721TokenIdsByOwner: ERC721TokenIdsByOwner,
        takerAddress: string,
    ): Promise<void> {
        // Individual balance comparisons
        const makerAssetProxyIdLeft = assetDataUtils.decodeAssetProxyId(signedOrderLeft.makerAssetData);
        const makerERC20AssetDataLeft =
            makerAssetProxyIdLeft === AssetProxyId.ERC20
                ? assetDataUtils.decodeERC20AssetData(signedOrderLeft.makerAssetData)
                : assetDataUtils.decodeERC721AssetData(signedOrderLeft.makerAssetData);
        const makerAssetAddressLeft = makerERC20AssetDataLeft.tokenAddress;
        const makerAssetProxyIdRight = assetDataUtils.decodeAssetProxyId(signedOrderRight.makerAssetData);
        const makerERC20AssetDataRight =
            makerAssetProxyIdRight === AssetProxyId.ERC20
                ? assetDataUtils.decodeERC20AssetData(signedOrderRight.makerAssetData)
                : assetDataUtils.decodeERC721AssetData(signedOrderRight.makerAssetData);
        const makerAssetAddressRight = makerERC20AssetDataRight.tokenAddress;
        if (makerAssetProxyIdLeft === AssetProxyId.ERC20) {
            expect(
                realERC20BalancesByOwner[signedOrderLeft.makerAddress][makerAssetAddressLeft],
                'Checking left maker egress ERC20 account balance',
            ).to.be.bignumber.equal(expectedERC20BalancesByOwner[signedOrderLeft.makerAddress][makerAssetAddressLeft]);
            expect(
                realERC20BalancesByOwner[signedOrderRight.makerAddress][makerAssetAddressLeft],
                'Checking right maker ingress ERC20 account balance',
            ).to.be.bignumber.equal(expectedERC20BalancesByOwner[signedOrderRight.makerAddress][makerAssetAddressLeft]);
            expect(
                realERC20BalancesByOwner[takerAddress][makerAssetAddressLeft],
                'Checking taker ingress ERC20 account balance',
            ).to.be.bignumber.equal(expectedERC20BalancesByOwner[takerAddress][makerAssetAddressLeft]);
        } else if (makerAssetProxyIdLeft === AssetProxyId.ERC721) {
            expect(
                realERC721TokenIdsByOwner[signedOrderLeft.makerAddress][makerAssetAddressLeft].sort(),
                'Checking left maker egress ERC721 account holdings',
            ).to.be.deep.equal(
                expectedERC721TokenIdsByOwner[signedOrderLeft.makerAddress][makerAssetAddressLeft].sort(),
            );
            expect(
                realERC721TokenIdsByOwner[signedOrderRight.makerAddress][makerAssetAddressLeft].sort(),
                'Checking right maker ERC721 account holdings',
            ).to.be.deep.equal(
                expectedERC721TokenIdsByOwner[signedOrderRight.makerAddress][makerAssetAddressLeft].sort(),
            );
            expect(
                realERC721TokenIdsByOwner[takerAddress][makerAssetAddressLeft].sort(),
                'Checking taker ingress ERC721 account holdings',
            ).to.be.deep.equal(expectedERC721TokenIdsByOwner[takerAddress][makerAssetAddressLeft].sort());
        } else {
            throw new Error(`Unhandled Asset Proxy ID: ${makerAssetProxyIdLeft}`);
        }
        if (makerAssetProxyIdRight === AssetProxyId.ERC20) {
            expect(
                realERC20BalancesByOwner[signedOrderLeft.makerAddress][makerAssetAddressRight],
                'Checking left maker ingress ERC20 account balance',
            ).to.be.bignumber.equal(expectedERC20BalancesByOwner[signedOrderLeft.makerAddress][makerAssetAddressRight]);
            expect(
                realERC20BalancesByOwner[signedOrderRight.makerAddress][makerAssetAddressRight],
                'Checking right maker egress ERC20 account balance',
            ).to.be.bignumber.equal(
                expectedERC20BalancesByOwner[signedOrderRight.makerAddress][makerAssetAddressRight],
            );
        } else if (makerAssetProxyIdRight === AssetProxyId.ERC721) {
            expect(
                realERC721TokenIdsByOwner[signedOrderLeft.makerAddress][makerAssetAddressRight].sort(),
                'Checking left maker ingress ERC721 account holdings',
            ).to.be.deep.equal(
                expectedERC721TokenIdsByOwner[signedOrderLeft.makerAddress][makerAssetAddressRight].sort(),
            );
            expect(
                realERC721TokenIdsByOwner[signedOrderRight.makerAddress][makerAssetAddressRight],
                'Checking right maker agress ERC721 account holdings',
            ).to.be.deep.equal(expectedERC721TokenIdsByOwner[signedOrderRight.makerAddress][makerAssetAddressRight]);
        } else {
            throw new Error(`Unhandled Asset Proxy ID: ${makerAssetProxyIdRight}`);
        }
        // Paid fees
        expect(
            realERC20BalancesByOwner[signedOrderLeft.makerAddress][this._feeTokenAddress],
            'Checking left maker egress ERC20 account fees',
        ).to.be.bignumber.equal(expectedERC20BalancesByOwner[signedOrderLeft.makerAddress][this._feeTokenAddress]);
        expect(
            realERC20BalancesByOwner[signedOrderRight.makerAddress][this._feeTokenAddress],
            'Checking right maker egress ERC20 account fees',
        ).to.be.bignumber.equal(expectedERC20BalancesByOwner[signedOrderRight.makerAddress][this._feeTokenAddress]);
        expect(
            realERC20BalancesByOwner[takerAddress][this._feeTokenAddress],
            'Checking taker egress ERC20 account fees',
        ).to.be.bignumber.equal(expectedERC20BalancesByOwner[takerAddress][this._feeTokenAddress]);
        // Received fees
        expect(
            realERC20BalancesByOwner[signedOrderLeft.feeRecipientAddress][this._feeTokenAddress],
            'Checking left fee recipient ingress ERC20 account fees',
        ).to.be.bignumber.equal(
            expectedERC20BalancesByOwner[signedOrderLeft.feeRecipientAddress][this._feeTokenAddress],
        );
        expect(
            realERC20BalancesByOwner[signedOrderRight.feeRecipientAddress][this._feeTokenAddress],
            'Checking right fee receipient ingress ERC20 account fees',
        ).to.be.bignumber.equal(
            expectedERC20BalancesByOwner[signedOrderRight.feeRecipientAddress][this._feeTokenAddress],
        );
    }
} // tslint:disable-line:max-file-line-count