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
//! Access the in-game market to buy or sell resources.
//!
//! [Screeps documentation](https://docs.screeps.com/api/#Game-market)
use js_sys::{Array, JsString, Object};
use wasm_bindgen::{prelude::*, JsCast};

use crate::{
    constants::{ErrorCode, MarketResourceType, OrderType, ResourceType},
    local::{LodashFilter, RoomName},
    prelude::*,
};

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_name = "market")]
    type Market;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, getter, js_name = credits)]
    fn credits() -> f64;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, getter, js_name = incomingTransactions)]
    fn incoming_transactions() -> Array;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, getter, js_name = outgoingTransactions)]
    fn outgoing_transactions() -> Array;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, getter, js_name = orders)]
    fn orders() -> Object;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = calcTransactionCost)]
    fn calc_transaction_cost(amount: u32, room_1: &JsString, room_2: &JsString) -> u32;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = cancelOrder)]
    fn cancel_order(order_id: &JsString) -> i8;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = changeOrderPrice)]
    fn change_order_price(order_id: &JsString, new_price: f64) -> i8;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = createOrder)]
    fn create_order(order_parameters: &Object) -> i8;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = deal)]
    fn deal(order_id: &JsString, amount: u32, room_name: Option<&JsString>) -> i8;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = extendOrder)]
    fn extend_order(order_id: &JsString, add_amount: u32) -> i8;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = getAllOrders)]
    fn get_all_orders(filter: Option<&LodashFilter>) -> Array;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = getHistory)]
    fn get_history(resource: Option<ResourceType>) -> Option<Array>;

    #[wasm_bindgen(js_namespace = ["Game"], js_class = "market", static_method_of = Market, js_name = getOrderById)]
    fn get_order_by_id(order_id: &JsString) -> Option<Order>;
}

/// Your current credit balance.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.credits)
pub fn credits() -> f64 {
    Market::credits()
}

/// An [`Array`] of the last 100 [`Transaction`]s sent to your terminals.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.incomingTransactions)
pub fn incoming_transactions() -> Vec<Transaction> {
    Market::incoming_transactions()
        .iter()
        .map(Into::into)
        .collect()
}

/// An [`Array`] of the last 100 [`Transaction`]s sent from your terminals.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.outgoingTransactions)
pub fn outgoing_transactions() -> Vec<Transaction> {
    Market::outgoing_transactions()
        .iter()
        .map(Into::into)
        .collect()
}

/// An [`Object`] with your current buy and sell orders on the market, with
/// order ID [`JsString`] keys and [`MyOrder`] values.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.orders)
pub fn orders() -> JsHashMap<String, MyOrder> {
    Market::orders().into()
}

// todo maybe just implement a native version of this instead?
/// Get the amount of energy required to send a given amount of any resource
/// from one room to another.  See [`TERMINAL_SEND_COST_SCALE`] for
/// information about the calculation.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.calcTransactionCost)
///
/// [`TERMINAL_SEND_COST_SCALE`]: crate::constants::TERMINAL_SEND_COST_SCALE
pub fn calc_transaction_cost(amount: u32, room_1: &JsString, room_2: &JsString) -> u32 {
    Market::calc_transaction_cost(amount, room_1, room_2)
}

/// Cancel one of your existing orders on the market, without refunding
/// associated fees.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.cancelOrder)
pub fn cancel_order(order_id: &JsString) -> Result<(), ErrorCode> {
    ErrorCode::result_from_i8(Market::cancel_order(order_id))
}

/// Change the price of an existing order. If new_price is greater than old
/// price, you will be charged
/// (newPrice-oldPrice)*remainingAmount*[`MARKET_FEE`] credits.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.changeOrderPrice)
///
/// [`MARKET_FEE`]: crate::constants::MARKET_FEE
pub fn change_order_price(order_id: &JsString, new_price: f64) -> Result<(), ErrorCode> {
    ErrorCode::result_from_i8(Market::change_order_price(order_id, new_price))
}

// todo type to serialize call options into
/// Create a new order on the market.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.createOrder)
pub fn create_order(order_parameters: &Object) -> Result<(), ErrorCode> {
    ErrorCode::result_from_i8(Market::create_order(order_parameters))
}

/// Execute a trade on an order on the market. Name of a room with a
/// terminal from which to send or receive resources is required unless the
/// order is for an account resource.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.deal)
pub fn deal(
    order_id: &JsString,
    amount: u32,
    room_name: Option<RoomName>,
) -> Result<(), ErrorCode> {
    ErrorCode::result_from_i8(match room_name {
        Some(r) => Market::deal(order_id, amount, Some(&r.into())),
        None => Market::deal(order_id, amount, None),
    })
}

/// Adds more capacity to one of your existing orders, offering or
/// requesting more of the resource and incurring additional fees.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.extendOrder)
pub fn extend_order(order_id: &JsString, add_amount: u32) -> Result<(), ErrorCode> {
    ErrorCode::result_from_i8(Market::extend_order(order_id, add_amount))
}

/// Get all [`Order`]s on the market, with an optional
/// filter. Note that a `resourceType` filter has special handling in the engine
/// to be more efficient ([source]).
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.getAllOrders)
///
/// [source]: https://github.com/screeps/engine/blob/f7a09e637c20689084fcf4eb43eacdfd51d31476/src/game/market.js#L37
pub fn get_all_orders(filter: Option<&LodashFilter>) -> Vec<Order> {
    Market::get_all_orders(filter)
        .iter()
        .map(Into::into)
        .collect()
}

/// Get information about the price history on the market for the last 14
/// days for a given resource as an [`Array`] of [`OrderHistoryRecord`]s, or
/// for all resources if `None`. Warning: returns an empty [`Object`]
/// instead of an array if there is no history for the resource, verifying
/// the type is recommended before use if the market might be empty.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.getHistory)
pub fn get_history(resource: Option<ResourceType>) -> Vec<OrderHistoryRecord> {
    Market::get_history(resource)
        .map(|arr| arr.iter().map(Into::into).collect())
        .unwrap_or_else(Vec::new)
}

/// Get an object with information about a specific order, in the same
/// format as returned by [`get_all_orders`]
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.market.getOrderById)
pub fn get_order_by_id(order_id: &str) -> Option<Order> {
    let order_id: JsString = order_id.into();

    Market::get_order_by_id(&order_id)
}

#[wasm_bindgen]
extern "C" {
    /// An object that represents an order on the market.
    #[wasm_bindgen]
    #[derive(Debug)]
    pub type Order;
    /// The order ID, which can be used to retrieve the order, or execute a
    /// trade using [`MarketInfo::deal`].
    #[wasm_bindgen(method, getter)]
    pub fn id(this: &Order) -> JsString;
    /// Tick of order creation, `None` for intershard orders.
    #[wasm_bindgen(method, getter)]
    pub fn created(this: &Order) -> Option<u32>;
    // todo should be u64 but seems to panic at the moment, follow up
    /// Timestamp of order creation in milliseconds since epoch.
    #[wasm_bindgen(method, getter = createdTimestamp)]
    pub fn created_timestamp(this: &Order) -> f64;
    /// The [`OrderType`] of the order (whether the owner is looking to buy or
    /// sell the given resource).
    #[wasm_bindgen(method, getter = type)]
    pub fn order_type(this: &Order) -> OrderType;
    /// The resource type this order is for.
    #[wasm_bindgen(method, getter = resourceType)]
    pub fn resource_type(this: &Order) -> MarketResourceType;
    /// Room that owns the order, `None` for intershard orders.
    #[wasm_bindgen(method, getter = roomName)]
    pub fn room_name(this: &Order) -> Option<JsString>;
    /// The amount of resource currently ready to be traded (loaded in the
    /// terminal).
    #[wasm_bindgen(method, getter)]
    pub fn amount(this: &Order) -> u32;
    /// The total remaining amount of the resource to be traded before this
    /// order has been completely filled and removed.
    #[wasm_bindgen(method, getter = remainingAmount)]
    pub fn remaining_amount(this: &Order) -> u32;
    /// Price of the order per unit of the resource the order is for.
    #[wasm_bindgen(method, getter)]
    pub fn price(this: &Order) -> f64;
}

// todo docs
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen]
    #[derive(Debug)]
    pub type Transaction;
    #[wasm_bindgen(method, getter = transactionId)]
    pub fn transaction_id(this: &Transaction) -> JsString;
    #[wasm_bindgen(method, getter)]
    pub fn time(this: &Transaction) -> u32;
    /// The player who sent resources for this transaction, or `None` if it was
    /// an NPC terminal
    #[wasm_bindgen(method, getter)]
    pub fn sender(this: &Transaction) -> Option<Player>;
    /// The recipient of the resources for this transaction, or `None` if it was
    /// an NPC terminal
    #[wasm_bindgen(method, getter)]
    pub fn recipient(this: &Transaction) -> Option<Player>;
    #[wasm_bindgen(method, getter = resourceType)]
    pub fn resource_type(this: &Transaction) -> ResourceType;
    #[wasm_bindgen(method, getter)]
    pub fn amount(this: &Transaction) -> u32;
    /// The room that sent resources for this transaction
    #[wasm_bindgen(method, getter)]
    pub fn from(this: &Transaction) -> JsString;
    /// The room that received resources in this transaction
    #[wasm_bindgen(method, getter)]
    pub fn to(this: &Transaction) -> JsString;
    /// The description set in the sender's `StructureTerminal::send()` call, if
    /// any
    #[wasm_bindgen(method, getter)]
    pub fn description(this: &Transaction) -> Option<JsString>;
    /// Information about the market order that this transaction was fulfilling,
    /// if any
    #[wasm_bindgen(method, getter = order)]
    pub fn order(this: &Transaction) -> Option<TransactionOrder>;
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen]
    #[derive(Debug)]
    pub type Player;
    #[wasm_bindgen(method, getter)]
    pub fn username(this: &Player) -> JsString;
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen]
    #[derive(Debug)]
    pub type TransactionOrder;
    #[wasm_bindgen(method, getter)]
    pub fn id(this: &TransactionOrder) -> JsString;
    #[wasm_bindgen(method, getter = type)]
    pub fn order_type(this: &TransactionOrder) -> OrderType;
    #[wasm_bindgen(method, getter)]
    pub fn price(this: &TransactionOrder) -> f64;
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen]
    #[derive(Debug)]
    pub type MyOrder;
    #[wasm_bindgen(method, getter)]
    pub fn id(this: &MyOrder) -> JsString;
    /// Tick of order creation, `None` for intershard orders
    #[wasm_bindgen(method, getter)]
    pub fn created(this: &MyOrder) -> Option<u32>;
    /// Timestamp of order creation in milliseconds since epoch
    #[wasm_bindgen(method, getter = createdTimestamp)]
    pub fn created_timestamp(this: &MyOrder) -> u64;
    #[wasm_bindgen(method, getter)]
    pub fn active(this: &MyOrder) -> bool;
    #[wasm_bindgen(method, getter = type)]
    pub fn order_type(this: &MyOrder) -> OrderType;
    #[wasm_bindgen(method, getter = resourceType)]
    pub fn resource_type(this: &MyOrder) -> MarketResourceType;
    /// Room that owns the order, `None` for intershard orders
    #[wasm_bindgen(method, getter = roomName)]
    pub fn room_name(this: &MyOrder) -> Option<JsString>;
    #[wasm_bindgen(method, getter)]
    pub fn amount(this: &MyOrder) -> u32;
    #[wasm_bindgen(method, getter = remainingAmount)]
    pub fn remaining_amount(this: &MyOrder) -> u32;
    #[wasm_bindgen(method, getter = totalAmount)]
    pub fn total_amount(this: &MyOrder) -> u32;
    #[wasm_bindgen(method, getter)]
    pub fn price(this: &MyOrder) -> f64;
}

impl JsCollectionFromValue for MyOrder {
    fn from_value(val: JsValue) -> Self {
        val.unchecked_into()
    }
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen]
    #[derive(Debug)]
    pub type OrderHistoryRecord;
    #[wasm_bindgen(method, getter = resourceType)]
    pub fn resource_type(this: &OrderHistoryRecord) -> MarketResourceType;
    /// Calendar date in string format, eg "2018-12-31"
    #[wasm_bindgen(method, getter)]
    pub fn date(this: &OrderHistoryRecord) -> JsString;
    /// Total number of transactions for this resource on this day
    #[wasm_bindgen(method, getter)]
    pub fn transactions(this: &OrderHistoryRecord) -> u32;
    /// Total volume of this resource bought and sold on this day
    #[wasm_bindgen(method, getter)]
    pub fn volume(this: &OrderHistoryRecord) -> u32;
    #[wasm_bindgen(method, getter = avgPrice)]
    pub fn avg_price(this: &OrderHistoryRecord) -> f64;
    #[wasm_bindgen(method, getter = stddevPrice)]
    pub fn stddev_price(this: &OrderHistoryRecord) -> f64;
}