-
Notifications
You must be signed in to change notification settings - Fork 5
/
createOrder.ts
535 lines (472 loc) · 14.6 KB
/
createOrder.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
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
import {
ActionInterface,
StateInterface,
CreateOrderInterface,
OrderInterface,
ForeignCallInterface,
MatchLogs,
} from "../faces";
import { isAddress, feeWallet, claimBalance } from "../utils";
export const CreateOrder = async (
state: StateInterface,
action: ActionInterface
): Promise<{
state: StateInterface;
result: {
status: "success" | "failure";
message: string;
};
}> => {
const caller = action.caller;
const input: CreateOrderInterface = action.input;
const pairs = state.pairs;
const usedPair = input.pair;
const qty = input.qty;
const price = input.price;
let tokenTx = input.transaction;
let balances = state.balances;
// test that pairs are valid contract strings
ContractAssert(
isAddress(usedPair[0]) && isAddress(usedPair[1]),
"One of two supplied pair tokens is invalid"
);
ContractAssert(
usedPair[0] === SmartWeave.contract.id ||
usedPair[1] === SmartWeave.contract.id,
"One of the two contracts in the pair isn't the current contract."
);
// validate price is a number
if (price) {
ContractAssert(typeof price === "number", "Price must be a number");
// validate price for limit orders
ContractAssert(
price === undefined || price === null || price > 0,
"Price must be greater than 0"
);
ContractAssert(Number.isInteger(price), "Price must be an integer");
}
if (!Number.isInteger(qty) || qty === undefined) {
throw new ContractError("Invalid value for quantity. Must be an integer.");
}
// ID of the transferred token is always first in pair
let contractID = usedPair[0];
if (contractID === SmartWeave.contract.id) {
// Set the tokenTx to be internal
tokenTx = "INTERNAL_TRANSFER";
// Transfer assets to the contract
if (qty <= 0 || caller === SmartWeave.contract.id) {
throw new ContractError("Invalid token transfer.");
}
if (balances[caller] < qty) {
throw new ContractError(
"Caller balance not high enough to send " + qty + " token(s)."
);
}
balances[caller] -= qty;
if (SmartWeave.contract.id in balances) {
balances[SmartWeave.contract.id] += qty;
} else {
balances[SmartWeave.contract.id] = qty;
}
} else {
if (tokenTx === undefined || tokenTx === null) {
throw new ContractError(
"No token transaction provided given the token in the order is from a different contract"
);
}
// Claim tokens from other contract
await claimBalance(contractID, tokenTx, qty);
}
/**
* Refund the order, if it is invalid
*/
const refundTransfer = async () => {
if (contractID === SmartWeave.contract.id) {
// No need to make a foreign call because the token is governed by this contract
balances[SmartWeave.contract.id] -= qty;
if (caller in balances) {
balances[caller] += qty;
} else {
balances[caller] = qty;
}
} else {
// @ts-expect-error
const result = await SmartWeave.contracts.write(contractID, {
function: "transfer",
target: caller,
qty,
});
// Check that it succeeded
if (result.type !== "ok") {
throw new ContractError(
`Unable to return order with txID: ${SmartWeave.transaction.id}`
);
}
}
};
let pairIndex = -1;
// find the pair index
for (let i = 0; i < pairs.length; i++) {
if (
(pairs[i].pair[0] === usedPair[0] && pairs[i].pair[1] === usedPair[1]) ||
(pairs[i].pair[0] === usedPair[1] && pairs[i].pair[1] === usedPair[0])
) {
pairIndex = i;
}
}
// test if the pair already exists
if (pairIndex === -1) {
// send back the funds
await refundTransfer();
// return state with the refund foreign call
// and the error message
return {
state,
result: {
status: "failure",
message: "This pair does not exist yet",
},
};
}
// Sort orderbook based on prices
let sortedOrderbook;
if (state.pairs[pairIndex].orders.length > 0) {
sortedOrderbook = state.pairs[pairIndex].orders.sort((a, b) =>
a.price > b.price ? 1 : -1
);
} else {
sortedOrderbook = [];
}
// get the dominant token from the pair
// it should always be the first one
const dominantToken = state.pairs[pairIndex].pair[0];
try {
// try invoking the match function
const { orderbook, foreignCalls, matches } = matchOrder(
{
pair: {
dominant: dominantToken,
from: contractID,
to: usedPair.find((val) => val !== contractID),
},
quantity: qty,
creator: caller,
transaction: SmartWeave.transaction.id,
transfer: tokenTx,
price,
},
sortedOrderbook
);
// Update orderbook accordingly
state.pairs[pairIndex].orders = orderbook;
// calculate latest price and push logs
// if the order had matches
if (matches.length > 0) {
// volume weighted average price
// how it is calculated:
// (volume_1 * price_1) + (volume_2 * price_2) + ...
// divided by
// volume_1 + volume_2 + ...
const vwap =
matches
.map(({ qty: volume, price }) => volume * price)
.reduce((a, b) => a + b, 0) /
matches.map(({ qty: volume }) => volume).reduce((a, b) => a + b, 0);
// update the latest price data
state.pairs[pairIndex].priceData = {
dominantToken,
block: SmartWeave.block.height,
vwap,
matchLogs: matches,
};
} else {
// if no matches, set the latest price data to empty
state.pairs[pairIndex].priceData = undefined;
}
// Update foreignCalls accordingly for tokens to be sent
for (let i = 0; i < foreignCalls.length; i++) {
// Skip making zero balance transfers
if (foreignCalls[i].input.qty <= 0) {
continue;
}
if (foreignCalls[i].contract === SmartWeave.contract.id) {
// No need to make a foreign call because the token is governed by this contract
balances[SmartWeave.contract.id] -= foreignCalls[i].input.qty;
if (foreignCalls[i].input.target in balances) {
balances[foreignCalls[i].input.target] +=
foreignCalls[i].input.qty;
} else {
balances[foreignCalls[i].input.target] =
foreignCalls[i].input.qty;
}
} else {
// @ts-expect-error
const result = await SmartWeave.contracts.write(
foreignCalls[i].contract,
foreignCalls[i].input
);
// Check that it succeeded
if (result.type !== "ok") {
throw new ContractError(
`Unable to fill order with txID: ${foreignCalls[i].txID}`
);
}
}
}
if (state.balances) {
state.balances = balances;
}
return {
state,
result: {
status: "success",
message: "Order created successfully",
},
};
} catch (e) {
// if the match function throws an error, refund the transfer
await refundTransfer();
// return state with the refund foreign call
// and the error message
return {
state,
result: {
status: "failure",
message: e.message,
},
};
}
};
export default function matchOrder(
input: {
/** Token of the new order */
pair: {
/** The dominant token to calculate the price for */
dominant: string;
/** ID of the token the user is trading from */
from: string;
/** ID of the token the user is trading for */
to: string;
};
/** Quantity of the order */
quantity: number;
/** Address of the order creator */
creator: string;
/** Interaction ID */
transaction: string;
/** Transfer transaction ID */
transfer: string;
/** Optional limit price of the order */
price?: number;
},
orderbook: OrderInterface[]
): {
orderbook: OrderInterface[];
foreignCalls: ForeignCallInterface[];
matches: MatchLogs;
} {
const orderType = input.price ? "limit" : "market";
const foreignCalls: ForeignCallInterface[] = [];
const matches: MatchLogs = [];
// orders that are made in the *reverse* direction as the current one
// this order can match with the reverse orders only
const reverseOrders = orderbook.filter(
(order) => input.pair.from !== order.token && order.id !== input.transaction
);
// if there are no orders against the token we are buying, we only push it
// but first, we check if it is a limit order
if (!reverseOrders.length) {
// ensure that the first order is a limit order
if (orderType !== "limit")
throw new Error('The first order for a pair can only be a "limit" order');
// push to the orderbook
orderbook.push({
id: input.transaction,
transfer: input.transfer,
creator: input.creator,
token: input.pair.from,
price: input.price,
quantity: Math.round(input.quantity),
originalQuantity: input.quantity,
});
return {
orderbook,
foreignCalls,
matches,
};
}
// the total amount of tokens the user would receive
// if the order type is "market", this changes
// for each order in the orderbook
// if it is a "limit" order, this will always
// be the same
let fillAmount: number;
// the total amount of tokens the user of
// the input order will receive
let receiveAmount = 0;
// the remaining tokens to be matched with an order
let remainingQuantity = input.quantity;
// loop through orders against this order
for (let i = 0; i < orderbook.length; i++) {
const currentOrder = orderbook[i];
// only loop orders that are against this order
if (
input.pair.from === currentOrder.token ||
currentOrder.id === input.transaction
)
continue;
// price of the current order reversed to the input token
const reversePrice = 1 / currentOrder.price;
// continue if the current order's price matches
// the input order's price (if the order is a limit order)
if (orderType === "limit" && input.price !== reversePrice) continue;
// set the total amount of tokens we would receive
// from this order
fillAmount = remainingQuantity * (input.price ?? reversePrice);
// the input order creator receives this much
// of the tokens from the current order
let receiveFromCurrent = 0;
// the input order is going to be completely filled
if (fillAmount <= currentOrder.quantity) {
// calculate receive amount
receiveFromCurrent = remainingQuantity * reversePrice;
// reduce the current order in the loop
currentOrder.quantity -= fillAmount;
// fill the remaining tokens
receiveAmount += receiveFromCurrent;
// send tokens to the current order's creator
if (remainingQuantity > 0) {
foreignCalls.push({
txID: SmartWeave.transaction.id,
contract: input.pair.from,
input: {
function: "transfer",
target: currentOrder.creator,
qty: Math.round(remainingQuantity * 0.98),
},
});
// send fee
foreignCalls.push({
txID: SmartWeave.transaction.id,
contract: input.pair.from,
input: {
function: "transfer",
target: feeWallet,
qty: Math.round(remainingQuantity * 0.02),
},
});
}
// no tokens left in the input order to be matched
remainingQuantity = 0;
} else {
// the input order is going to be partially filled
// but the current order will be
// calculate receive amount
receiveFromCurrent = currentOrder.quantity;
// add all the tokens from the current order to fill up
// the input order
receiveAmount += receiveFromCurrent;
// the amount the current order creator will receive
const sendAmount = receiveFromCurrent * currentOrder.price;
// reduce the remaining tokens to be matched
// by the amount the user is going to receive
// from this order
remainingQuantity -= sendAmount;
// send tokens to the current order's creator
foreignCalls.push({
txID: SmartWeave.transaction.id,
contract: input.pair.from,
input: {
function: "transfer",
target: currentOrder.creator,
qty: Math.round(sendAmount * 0.98),
},
});
// send fee
foreignCalls.push({
txID: SmartWeave.transaction.id,
contract: input.pair.from,
input: {
function: "transfer",
target: feeWallet,
qty: Math.round(sendAmount * 0.02),
},
});
// no tokens left in the current order to be matched
currentOrder.quantity = 0;
}
// calculate dominant token price
let dominantPrice = 0;
if (input.pair.dominant === input.pair.from) {
dominantPrice = input.price ?? reversePrice;
} else {
dominantPrice = currentOrder.price;
}
// push the match
matches.push({
id: currentOrder.id,
qty: receiveFromCurrent,
price: dominantPrice,
});
// if the current order is completely filled,
// remove it from the orderbook
if (currentOrder.quantity === 0) {
orderbook = orderbook.filter((val) => val.id !== currentOrder.id);
}
// if there are no more tokens to be matched,
// we can break the loop
if (remainingQuantity === 0) break;
}
if (remainingQuantity > 0) {
// if the input order is not completely filled,
// and it is a limit order, push it to the orderbook
if (orderType === "limit") {
orderbook.push({
id: input.transaction,
transfer: input.transfer,
creator: input.creator,
token: input.pair.from,
price: input.price,
quantity: Math.round(remainingQuantity),
originalQuantity: input.quantity,
});
} else {
// if the input order is not completely filled,
// and it is a market order, we return the funds
foreignCalls.push({
txID: SmartWeave.transaction.id,
contract: input.pair.from,
input: {
function: "transfer",
target: input.creator,
qty: remainingQuantity,
},
});
}
}
// send tokens to the input order's creator
foreignCalls.push({
txID: SmartWeave.transaction.id,
contract: input.pair.to,
input: {
function: "transfer",
target: input.creator,
qty: Math.round(receiveAmount * 0.98),
},
});
// send fee
foreignCalls.push({
txID: SmartWeave.transaction.id,
contract: input.pair.to,
input: {
function: "transfer",
target: feeWallet,
qty: Math.round(receiveAmount * 0.02),
},
});
return {
orderbook,
foreignCalls,
matches,
};
}