-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcancelOrder.ts
81 lines (69 loc) · 2.1 KB
/
cancelOrder.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
import {
ActionInterface,
StateInterface,
CancelOrderInterface,
} from "../faces";
import { isAddress } from "../utils";
export const CancelOrder = async (
state: StateInterface,
action: ActionInterface
): Promise<{
state: StateInterface;
result: {
status: "success" | "failure";
message: string;
};
}> => {
const caller = action.caller;
const input: CancelOrderInterface = action.input;
const orderTxID = input.orderID;
// Verify order ID
ContractAssert(isAddress(orderTxID), "Invalid order ID");
// Remap all orders into one array
const allOrders = state.pairs.map((pair) => pair.orders).flat(1);
// Get the order to cancel
const order = allOrders.find(({ id }) => id === orderTxID);
// Ensure that the order exists
ContractAssert(order !== undefined, "Order does not exist");
// Ensure that the creator of the order is the caller
ContractAssert(
order.creator === caller,
"Caller is not the creator of the order"
);
// Send back the *not* filled tokens to the creator of the order
if (order.token === SmartWeave.contract.id) {
// No need to make a foreign call because the token is governed by this contract
state.balances[SmartWeave.contract.id] -= order.quantity;
if (caller in state.balances) {
state.balances[caller] += order.quantity;
} else {
state.balances[caller] = order.quantity;
}
} else {
// @ts-expect-error
const result = await SmartWeave.contracts.write(order.token, {
function: "transfer",
target: caller,
qty: order.quantity,
});
// Check that it succeeded
if (result.type !== "ok") {
throw new ContractError(
`Unable to make claim with txID: ${SmartWeave.transaction.id}`
);
}
}
// The pair that the order belongs to
const acitvePair = state.pairs.find((pair) =>
pair.orders.find(({ id }) => id === orderTxID)
);
// Remove cancelled order
acitvePair.orders = acitvePair.orders.filter(({ id }) => id !== orderTxID);
return {
state,
result: {
status: "success",
message: "Order cancelled successfully",
},
};
};