-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathorder.ts
353 lines (324 loc) · 15.3 KB
/
order.ts
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
import { BigNumber } from "bignumber.js";
import BN = require("bn.js");
import ABI = require("ethereumjs-abi");
import { Bitstream } from "./bitstream";
import { Context } from "./context";
import { getEIP712Message } from "./eip712";
import { ensure } from "./ensure";
import { MultiHashUtil } from "./multihash";
import { OrderInfo, Spendable, TokenType } from "./types";
export class OrderUtil {
private context: Context;
private zeroBytes32 = "0x" + "0".repeat(64);
constructor(context: Context) {
this.context = context;
}
public async updateBrokerAndInterceptor(order: OrderInfo) {
if (!order.broker) {
order.broker = order.owner;
} else {
const returnValue = await this.context.orderBrokerRegistry.methods.getBroker(
order.owner,
order.broker,
).call();
order.valid = order.valid && ensure(returnValue.registered, "order broker is not registered");
// order.brokerInterceptor =
// (brokerInterceptor === "0x0000000000000000000000000000000000000000") ?
// undefined : returnValue.brokerInterceptor;
}
}
public async validateInfo(order: OrderInfo) {
let valid = true;
valid = valid && ensure(order.version === 0, "unsupported order version");
valid = valid && ensure(order.owner ? true : false, "invalid order owner");
valid = valid && ensure(order.tokenS ? true : false, "invalid order tokenS");
valid = valid && ensure(order.tokenB ? true : false, "invalid order tokenB");
valid = valid && ensure(order.amountS !== 0, "invalid order amountS");
valid = valid && ensure(order.amountB !== 0, "invalid order amountB");
valid = valid && ensure(order.waiveFeePercentage <= this.context.feePercentageBase, "invalid waive percentage");
valid = valid && ensure(order.waiveFeePercentage >= -this.context.feePercentageBase, "invalid waive percentage");
valid = valid && ensure(order.tokenSFeePercentage < this.context.feePercentageBase, "invalid tokenS percentage");
valid = valid && ensure(order.tokenBFeePercentage < this.context.feePercentageBase, "invalid tokenB percentage");
valid = valid && ensure(order.walletSplitPercentage <= 100, "invalid wallet split percentage");
if (order.dualAuthAddr) {
valid = valid && ensure(order.dualAuthSig && order.dualAuthSig.length > 0, "missing dual author signature");
}
const blockTimestamp = this.context.blockTimestamp;
valid = valid && ensure(order.validSince <= blockTimestamp, "order is too early to match");
valid = valid && ensure(order.validUntil ? order.validUntil > blockTimestamp : true, "order is expired");
// We only support ERC20 for now
valid = valid && ensure(
(order.tokenTypeS === TokenType.ERC20 && order.trancheS === this.zeroBytes32),
"invalid trancheS",
);
valid = valid && ensure(
(order.tokenTypeB === TokenType.ERC20 && order.trancheB === this.zeroBytes32),
"invalid trancheB",
);
valid = valid && ensure(
(order.tokenTypeFee === TokenType.ERC20),
"invalid tokenTypeFee",
);
valid = valid && ensure(
(order.tokenTypeS === TokenType.ERC20 && order.transferDataS === "0x"),
"invalid transferDataS",
);
// This emulates the revert in solidity with invalid enum values
assert(order.tokenTypeS < TokenType.COUNT, "invalid opcode");
assert(order.tokenTypeB < TokenType.COUNT, "invalid opcode");
assert(order.tokenTypeFee < TokenType.COUNT, "invalid opcode");
order.valid = order.valid && valid;
}
public validateAllOrNone(order: OrderInfo) {
order.valid = order.valid && ensure(order.filledAmountS.eq(order.amountS), "allOrNone not completely filled");
}
public async checkBrokerSignature(order: OrderInfo) {
let signatureValid = true;
// If the order was already partially filled we don't have to check the signature again
if (order.filledAmountS.gt(0)) {
signatureValid = true;
} else if (!order.sig) {
const orderHashHex = "0x" + order.hash.toString("hex");
const isRegistered = await this.context.orderRegistry.methods.isOrderHashRegistered(order.broker,
orderHashHex).call();
const isOnchainOrder = await this.context.orderBook.methods.orderSubmitted(orderHashHex).call();
signatureValid = isRegistered || isOnchainOrder;
} else {
const multiHashUtil = new MultiHashUtil();
signatureValid = multiHashUtil.verifySignature(order.broker, order.hash, order.sig);
}
order.valid = order.valid && ensure(signatureValid, "invalid order signature");
}
public checkDualAuthSignature(order: OrderInfo, miningHash: Buffer) {
if (order.dualAuthSig) {
const multiHashUtil = new MultiHashUtil();
const signatureValid = multiHashUtil.verifySignature(order.dualAuthAddr, miningHash, order.dualAuthSig);
order.valid = order.valid && ensure(signatureValid, "invalid order dual auth signature");
}
}
public toTypedData(order: OrderInfo) {
const typedData = {
types: {
EIP712Domain: [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
],
Order: [
{ name: "amountS", type: "uint" },
{ name: "amountB", type: "uint" },
{ name: "feeAmount", type: "uint" },
{ name: "validSince", type: "uint" },
{ name: "validUntil", type: "uint" },
{ name: "owner", type: "address" },
{ name: "tokenS", type: "address" },
{ name: "tokenB", type: "address" },
{ name: "dualAuthAddr", type: "address" },
{ name: "broker", type: "address" },
{ name: "orderInterceptor", type: "address" },
{ name: "wallet", type: "address" },
{ name: "tokenRecipient", type: "address" },
{ name: "feeToken", type: "address" },
{ name: "walletSplitPercentage", type: "uint16" },
{ name: "tokenSFeePercentage", type: "uint16" },
{ name: "tokenBFeePercentage", type: "uint16" },
{ name: "allOrNone", type: "bool" },
{ name: "tokenTypeS", type: "uint8" },
{ name: "tokenTypeB", type: "uint8" },
{ name: "tokenTypeFee", type: "uint8" },
{ name: "trancheS", type: "bytes32" },
{ name: "trancheB", type: "bytes32" },
{ name: "transferDataS", type: "bytes" },
],
},
primaryType: "Order",
domain: {
name: "Loopring Protocol",
version: "2",
},
message: {
amountS: this.toBN(order.amountS),
amountB: this.toBN(order.amountB),
feeAmount: this.toBN(order.feeAmount),
validSince: order.validSince ? this.toBN(order.validSince) : this.toBN(0),
validUntil: order.validUntil ? this.toBN(order.validUntil) : this.toBN(0),
owner: order.owner,
tokenS: order.tokenS,
tokenB: order.tokenB,
dualAuthAddr: order.dualAuthAddr ? order.dualAuthAddr : "",
broker: order.broker ? order.broker : "",
orderInterceptor: order.orderInterceptor ? order.orderInterceptor : "",
wallet: order.walletAddr ? order.walletAddr : "",
tokenRecipient: order.tokenRecipient,
feeToken: order.feeToken,
walletSplitPercentage: order.walletSplitPercentage,
tokenSFeePercentage: order.tokenSFeePercentage,
tokenBFeePercentage: order.tokenBFeePercentage,
allOrNone: order.allOrNone,
tokenTypeS: order.tokenTypeS ? order.tokenTypeS : TokenType.ERC20,
tokenTypeB: order.tokenTypeB ? order.tokenTypeB : TokenType.ERC20,
tokenTypeFee: order.tokenTypeFee ? order.tokenTypeFee : TokenType.ERC20,
trancheS: order.trancheS ? order.trancheS : "",
trancheB: order.trancheB ? order.trancheB : "",
transferDataS: order.transferDataS ? order.transferDataS : "",
},
};
return typedData;
}
public toTypedDataJSON(order: OrderInfo) {
// BN outputs hex numbers in toJSON, but signTypedData expects decimal numbers
const replacer = (key: any, value: any) => {
if (key === "amountS" || key === "amountB" || key === "feeAmount" ||
key === "validSince" || key === "validUntil") {
return "" + parseInt(value, 16);
}
return value;
};
const typedData = this.toTypedData(order);
const json = JSON.stringify(typedData, replacer);
return json;
}
public getOrderHash(order: OrderInfo) {
const typedData = this.toTypedData(order);
const orderHash = getEIP712Message(typedData);
return orderHash;
}
public toOrderBookSubmitParams(orderInfo: OrderInfo) {
const emptyAddr = "0x" + "0".repeat(40);
const zeroBytes32 = "0x" + "0".repeat(64);
const data = new Bitstream();
data.addAddress(orderInfo.owner, 32);
data.addAddress(orderInfo.tokenS, 32);
data.addAddress(orderInfo.tokenB, 32);
data.addNumber(orderInfo.amountS, 32);
data.addNumber(orderInfo.amountB, 32);
data.addNumber(orderInfo.validSince, 32);
data.addAddress(orderInfo.broker ? orderInfo.broker : emptyAddr, 32);
data.addAddress(orderInfo.orderInterceptor ? orderInfo.orderInterceptor : emptyAddr, 32);
data.addAddress(orderInfo.walletAddr ? orderInfo.walletAddr : emptyAddr, 32);
data.addNumber(orderInfo.validUntil ? orderInfo.validUntil : 0, 32);
data.addNumber(orderInfo.allOrNone ? 1 : 0, 32);
data.addAddress(orderInfo.feeToken ? orderInfo.feeToken : emptyAddr, 32);
data.addNumber(orderInfo.feeAmount ? orderInfo.feeAmount : 0, 32);
data.addNumber(orderInfo.tokenSFeePercentage ? orderInfo.tokenSFeePercentage : 0, 32);
data.addNumber(orderInfo.tokenBFeePercentage ? orderInfo.tokenBFeePercentage : 0, 32);
data.addAddress(orderInfo.tokenRecipient ? orderInfo.tokenRecipient : orderInfo.owner, 32);
data.addNumber(orderInfo.walletSplitPercentage ? orderInfo.walletSplitPercentage : 0, 32);
data.addNumber(orderInfo.tokenTypeS ? orderInfo.tokenTypeS : TokenType.ERC20, 32);
data.addNumber(orderInfo.tokenTypeB ? orderInfo.tokenTypeB : TokenType.ERC20, 32);
data.addNumber(orderInfo.tokenTypeFee ? orderInfo.tokenTypeFee : TokenType.ERC20, 32);
data.addHex(orderInfo.trancheS ? orderInfo.trancheS : zeroBytes32);
data.addHex(orderInfo.trancheB ? orderInfo.trancheB : zeroBytes32);
if (orderInfo.transferDataS) {
data.addNumber((orderInfo.transferDataS.length - 2) / 2, 32);
data.addHex(orderInfo.transferDataS);
} else {
data.addNumber(0, 32);
}
return data.getData();
}
public checkP2P(orderInfo: OrderInfo) {
orderInfo.P2P = (orderInfo.tokenSFeePercentage > 0 || orderInfo.tokenBFeePercentage > 0);
}
public async getSpendableS(order: OrderInfo) {
const spendable = await this.getSpendable(order.tokenS,
order.owner,
order.broker,
order.brokerInterceptor,
order.tokenSpendableS,
order.brokerSpendableS);
return spendable;
}
public async getSpendableFee(order: OrderInfo) {
const spendable = await this.getSpendable(order.feeToken,
order.owner,
order.broker,
order.brokerInterceptor,
order.tokenSpendableFee,
order.brokerSpendableFee);
return spendable;
}
public async reserveAmountS(order: OrderInfo,
amount: BigNumber) {
const spendableS = await this.getSpendableS(order);
assert(spendableS.gte(amount), "spendableS >= reserve amount");
order.tokenSpendableS.reserved = order.tokenSpendableS.reserved.plus(amount);
if (order.brokerInterceptor) {
order.brokerSpendableS.reserved = order.brokerSpendableS.reserved.plus(amount);
}
}
public async reserveAmountFee(order: OrderInfo,
amount: BigNumber) {
assert((await this.getSpendableFee(order)).gte(amount), "spendableFee >= reserve amount");
order.tokenSpendableFee.reserved = order.tokenSpendableFee.reserved.plus(amount);
if (order.brokerInterceptor) {
order.brokerSpendableFee.reserved = order.brokerSpendableFee.reserved.plus(amount);
}
}
public resetReservations(order: OrderInfo) {
order.tokenSpendableS.reserved = new BigNumber(0);
order.tokenSpendableFee.reserved = new BigNumber(0);
if (order.brokerInterceptor) {
order.tokenSpendableS.reserved = new BigNumber(0);
order.tokenSpendableFee.reserved = new BigNumber(0);
}
}
public async getERC20Spendable(spender: string,
tokenAddress: string,
owner: string) {
const token = this.context.ERC20Contract;
token.options.address = tokenAddress;
const balance = await token.methods.balanceOf(owner).call();
const allowance = await token.methods.allowance(owner, spender).call();
const spendable = BigNumber.min(balance, allowance);
return new BigNumber(spendable.toString());
}
public async getBrokerAllowance(tokenAddr: string,
owner: string,
broker: string,
brokerInterceptor: string) {
try {
return await this.context.BrokerInterceptorContract.at(brokerInterceptor).getAllowance(
owner,
broker,
tokenAddr,
);
} catch {
return new BigNumber(0);
}
}
private async getSpendable(token: string,
owner: string,
broker: string,
brokerInterceptor: string,
tokenSpendable: Spendable,
brokerSpendable: Spendable) {
if (!tokenSpendable.initialized) {
tokenSpendable.amount = await this.getERC20Spendable(this.context.tradeDelegate.options.address,
token,
owner);
tokenSpendable.initialized = true;
// Testing
tokenSpendable.initialAmount = tokenSpendable.amount;
}
let spendable = tokenSpendable.amount.minus(tokenSpendable.reserved);
assert(spendable.gte(0), "spendable >= 0");
if (brokerInterceptor) {
if (!brokerSpendable.initialized) {
brokerSpendable.amount = await this.getBrokerAllowance(token,
owner,
broker,
brokerInterceptor);
brokerSpendable.initialized = true;
// Testing
brokerSpendable.initialAmount = brokerSpendable.amount;
}
const brokerSpendableAmount = brokerSpendable.amount.minus(brokerSpendable.reserved);
assert(brokerSpendableAmount.gte(0), "brokerSpendable >= 0");
spendable = (brokerSpendableAmount.lt(spendable)) ? brokerSpendableAmount : spendable;
}
return spendable;
}
private toBN(n: number) {
return new BN((new BigNumber(n)).toString(10), 10);
}
}