aboutsummaryrefslogtreecommitdiffstats
path: root/packages/fill-scenarios/src/index.ts
blob: 14d5a26145d3b1dcf8a43682cb632c63196f26bf (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
import { formatters, orderFactory } from '@0xproject/order-utils';
import { Provider, SignedOrder, Token } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash';

import { artifacts } from './artifacts';
import { constants } from './constants';
import { DummyTokenContract } from './generated_contract_wrappers/dummy_token';
import { ExchangeContract } from './generated_contract_wrappers/exchange';
import { TokenContract } from './generated_contract_wrappers/token';

const INITIAL_COINBASE_TOKEN_SUPPLY_IN_UNITS = new BigNumber(100);

export class FillScenarios {
    private _web3Wrapper: Web3Wrapper;
    private _userAddresses: string[];
    private _tokens: Token[];
    private _coinbase: string;
    private _zrxTokenAddress: string;
    private _exchangeContractAddress: string;
    constructor(
        provider: Provider,
        userAddresses: string[],
        tokens: Token[],
        zrxTokenAddress: string,
        exchangeContractAddress: string,
    ) {
        this._web3Wrapper = new Web3Wrapper(provider);
        this._userAddresses = userAddresses;
        this._tokens = tokens;
        this._coinbase = userAddresses[0];
        this._zrxTokenAddress = zrxTokenAddress;
        this._exchangeContractAddress = exchangeContractAddress;
    }
    public async initTokenBalancesAsync() {
        for (const token of this._tokens) {
            if (token.symbol !== 'ZRX' && token.symbol !== 'WETH') {
                const dummyToken = new DummyTokenContract(
                    artifacts.DummyToken.abi,
                    token.address,
                    this._web3Wrapper.getProvider(),
                    this._web3Wrapper.getContractDefaults(),
                );
                const tokenSupply = Web3Wrapper.toBaseUnitAmount(
                    INITIAL_COINBASE_TOKEN_SUPPLY_IN_UNITS,
                    token.decimals,
                );
                const txHash = await dummyToken.setBalance.sendTransactionAsync(this._coinbase, tokenSupply, {
                    from: this._coinbase,
                });
                await this._web3Wrapper.awaitTransactionMinedAsync(txHash);
            }
        }
    }
    public async createFillableSignedOrderAsync(
        makerTokenAddress: string,
        takerTokenAddress: string,
        makerAddress: string,
        takerAddress: string,
        fillableAmount: BigNumber,
        expirationUnixTimestampSec?: BigNumber,
    ): Promise<SignedOrder> {
        return this.createAsymmetricFillableSignedOrderAsync(
            makerTokenAddress,
            takerTokenAddress,
            makerAddress,
            takerAddress,
            fillableAmount,
            fillableAmount,
            expirationUnixTimestampSec,
        );
    }
    public async createFillableSignedOrderWithFeesAsync(
        makerTokenAddress: string,
        takerTokenAddress: string,
        makerFee: BigNumber,
        takerFee: BigNumber,
        makerAddress: string,
        takerAddress: string,
        fillableAmount: BigNumber,
        feeRecepient: string,
        expirationUnixTimestampSec?: BigNumber,
    ): Promise<SignedOrder> {
        return this._createAsymmetricFillableSignedOrderWithFeesAsync(
            makerTokenAddress,
            takerTokenAddress,
            makerFee,
            takerFee,
            makerAddress,
            takerAddress,
            fillableAmount,
            fillableAmount,
            feeRecepient,
            expirationUnixTimestampSec,
        );
    }
    public async createAsymmetricFillableSignedOrderAsync(
        makerTokenAddress: string,
        takerTokenAddress: string,
        makerAddress: string,
        takerAddress: string,
        makerFillableAmount: BigNumber,
        takerFillableAmount: BigNumber,
        expirationUnixTimestampSec?: BigNumber,
    ): Promise<SignedOrder> {
        const makerFee = new BigNumber(0);
        const takerFee = new BigNumber(0);
        const feeRecepient = constants.NULL_ADDRESS;
        return this._createAsymmetricFillableSignedOrderWithFeesAsync(
            makerTokenAddress,
            takerTokenAddress,
            makerFee,
            takerFee,
            makerAddress,
            takerAddress,
            makerFillableAmount,
            takerFillableAmount,
            feeRecepient,
            expirationUnixTimestampSec,
        );
    }
    public async createPartiallyFilledSignedOrderAsync(
        makerTokenAddress: string,
        takerTokenAddress: string,
        takerAddress: string,
        fillableAmount: BigNumber,
        partialFillAmount: BigNumber,
    ) {
        const [makerAddress] = this._userAddresses;
        const signedOrder = await this.createAsymmetricFillableSignedOrderAsync(
            makerTokenAddress,
            takerTokenAddress,
            makerAddress,
            takerAddress,
            fillableAmount,
            fillableAmount,
        );
        const shouldThrowOnInsufficientBalanceOrAllowance = false;
        const exchangeInstance = new ExchangeContract(
            artifacts.Exchange.abi,
            signedOrder.exchangeContractAddress,
            this._web3Wrapper.getProvider(),
            this._web3Wrapper.getContractDefaults(),
        );

        const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(signedOrder);

        await exchangeInstance.fillOrder.sendTransactionAsync(
            orderAddresses,
            orderValues,
            partialFillAmount,
            shouldThrowOnInsufficientBalanceOrAllowance,
            signedOrder.ecSignature.v,
            signedOrder.ecSignature.r,
            signedOrder.ecSignature.s,
            { from: takerAddress },
        );
        return signedOrder;
    }
    private async _createAsymmetricFillableSignedOrderWithFeesAsync(
        makerTokenAddress: string,
        takerTokenAddress: string,
        makerFee: BigNumber,
        takerFee: BigNumber,
        makerAddress: string,
        takerAddress: string,
        makerFillableAmount: BigNumber,
        takerFillableAmount: BigNumber,
        feeRecepient: string,
        expirationUnixTimestampSec?: BigNumber,
    ): Promise<SignedOrder> {
        await Promise.all([
            this._increaseBalanceAndAllowanceAsync(makerTokenAddress, makerAddress, makerFillableAmount),
            this._increaseBalanceAndAllowanceAsync(takerTokenAddress, takerAddress, takerFillableAmount),
        ]);
        await Promise.all([
            this._increaseBalanceAndAllowanceAsync(this._zrxTokenAddress, makerAddress, makerFee),
            this._increaseBalanceAndAllowanceAsync(this._zrxTokenAddress, takerAddress, takerFee),
        ]);

        const signedOrder = await orderFactory.createSignedOrderAsync(
            this._web3Wrapper.getProvider(),
            makerAddress,
            takerAddress,
            makerFee,
            takerFee,
            makerFillableAmount,
            makerTokenAddress,
            takerFillableAmount,
            takerTokenAddress,
            this._exchangeContractAddress,
            feeRecepient,
            expirationUnixTimestampSec,
        );
        return signedOrder;
    }
    private async _increaseBalanceAndAllowanceAsync(
        tokenAddress: string,
        address: string,
        amount: BigNumber,
    ): Promise<void> {
        if (amount.isZero() || address === constants.NULL_ADDRESS) {
            return; // noop
        }
        await Promise.all([
            this._increaseBalanceAsync(tokenAddress, address, amount),
            this._increaseAllowanceAsync(tokenAddress, address, amount),
        ]);
    }
    private async _increaseBalanceAsync(tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
        const token = new TokenContract(
            artifacts.Token.abi,
            tokenAddress,
            this._web3Wrapper.getProvider(),
            this._web3Wrapper.getContractDefaults(),
        );
        await token.transfer.sendTransactionAsync(address, amount, {
            from: this._coinbase,
        });
    }
    private async _increaseAllowanceAsync(tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
        const tokenInstance = new TokenContract(
            artifacts.Token.abi,
            tokenAddress,
            this._web3Wrapper.getProvider(),
            this._web3Wrapper.getContractDefaults(),
        );
        const networkArtifactsIfExists = artifacts.TokenTransferProxy.networks[constants.TEST_RPC_NETWORK_ID];
        if (_.isUndefined(networkArtifactsIfExists)) {
            throw new Error(`Did not find network artifacts for networkId: ${constants.TEST_RPC_NETWORK_ID}`);
        }
        const proxyAddress = networkArtifactsIfExists.address;
        const oldMakerAllowance = await tokenInstance.allowance.callAsync(address, proxyAddress);
        const newMakerAllowance = oldMakerAllowance.plus(amount);

        await tokenInstance.approve.sendTransactionAsync(proxyAddress, newMakerAllowance, {
            from: address,
        });
    }
}