-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathorders.rs
345 lines (283 loc) · 13.4 KB
/
orders.rs
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
// Copyright (c) 2024 RBB S.r.l
// opensource@mintlayer.org
// SPDX-License-Identifier: MIT
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/mintlayer/mintlayer-core/blob/master/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common::chain::{make_order_id, OrderAccountCommand, OrderData};
use super::*;
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test]
async fn create_fill_conclude_order(#[case] seed: Seed) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();
let task = tokio::spawn(async move {
let web_server_state = {
let mut rng = make_seedable_rng(seed);
let chain_config = create_unit_test_config();
let chainstate_blocks = {
let mut tf = TestFramework::builder(&mut rng)
.with_chain_config(chain_config.clone())
.build();
// Issue and mint some tokens to create an order with different currencies
let issue_and_mint_result =
helpers::issue_and_mint_tokens_from_genesis(&mut rng, &mut tf);
// Create order
let order_data = OrderData::new(
Destination::AnyoneCanSpend,
OutputValue::Coin(Amount::from_atoms(10)),
OutputValue::TokenV1(issue_and_mint_result.token_id, Amount::from_atoms(10)),
);
let order_id = make_order_id(&issue_and_mint_result.tokens_outpoint);
let tx_1 = TransactionBuilder::new()
.add_input(
TxInput::Utxo(issue_and_mint_result.tokens_outpoint),
InputWitness::NoSignature(None),
)
.add_output(TxOutput::CreateOrder(Box::new(order_data)))
.build();
let tx_1_id = tx_1.transaction().get_id();
let block1 = tf.make_block_builder().add_transaction(tx_1.clone()).build(&mut rng);
tf.process_block(block1.clone(), BlockSource::Local).unwrap();
// Fill order
let tx2 = TransactionBuilder::new()
.add_input(
TxInput::Utxo(issue_and_mint_result.change_outpoint),
InputWitness::NoSignature(None),
)
.add_input(
TxInput::OrderAccountCommand(OrderAccountCommand::FillOrder(
order_id,
Amount::from_atoms(1),
Destination::AnyoneCanSpend,
)),
InputWitness::NoSignature(None),
)
.add_output(TxOutput::Transfer(
OutputValue::TokenV1(issue_and_mint_result.token_id, Amount::from_atoms(1)),
Destination::AnyoneCanSpend,
))
.build();
let tx_2_id = tx2.transaction().get_id();
let block2 = tf.make_block_builder().add_transaction(tx2).build(&mut rng);
tf.process_block(block2.clone(), BlockSource::Local).unwrap();
// Conclude order
let tx3 = TransactionBuilder::new()
.add_input(
TxInput::OrderAccountCommand(OrderAccountCommand::ConcludeOrder {
order_id,
filled_amount: Amount::from_atoms(1),
remaining_give_amount: Amount::from_atoms(9),
}),
InputWitness::NoSignature(None),
)
.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(1)),
Destination::AnyoneCanSpend,
))
.add_output(TxOutput::Transfer(
OutputValue::TokenV1(issue_and_mint_result.token_id, Amount::from_atoms(9)),
Destination::AnyoneCanSpend,
))
.build();
let tx_3_id = tx3.transaction().get_id();
let block3 = tf.make_block_builder().add_transaction(tx3).build(&mut rng);
tf.process_block(block3.clone(), BlockSource::Local).unwrap();
_ = tx.send((
block1.get_id().to_hash().encode_hex::<String>(),
tx_1_id.to_hash().encode_hex::<String>(),
block2.get_id().to_hash().encode_hex::<String>(),
tx_2_id.to_hash().encode_hex::<String>(),
block3.get_id().to_hash().encode_hex::<String>(),
tx_3_id.to_hash().encode_hex::<String>(),
));
vec![
issue_and_mint_result.issue_block,
issue_and_mint_result.mint_block,
block1,
block2,
block3,
]
};
let storage = {
let mut storage = TransactionalApiServerInMemoryStorage::new(&chain_config);
let mut db_tx = storage.transaction_rw().await.unwrap();
db_tx.reinitialize_storage(&chain_config).await.unwrap();
db_tx.commit().await.unwrap();
storage
};
let chain_config = Arc::new(chain_config);
let mut local_node = BlockchainState::new(Arc::clone(&chain_config), storage);
local_node.scan_genesis(chain_config.genesis_block()).await.unwrap();
local_node.scan_blocks(BlockHeight::new(0), chainstate_blocks).await.unwrap();
ApiServerWebServerState {
db: Arc::new(local_node.storage().clone_storage().await),
chain_config: Arc::clone(&chain_config),
rpc: Arc::new(DummyRPC {}),
cached_values: Arc::new(CachedValues {
feerate_points: RwLock::new((get_time(), vec![])),
}),
time_getter: Default::default(),
}
};
web_server(listener, web_server_state, true).await
});
let (block1_id, tx1_id, block2_id, tx2_id, block3_id, tx3_id) = rx.await.unwrap();
let check_url = |url| async move {
let response = reqwest::get(format!("http://{}:{}{url}", addr.ip(), addr.port()))
.await
.unwrap();
assert_eq!(response.status(), 200);
};
check_url(format!("/api/v2/block/{block1_id}")).await;
check_url(format!("/api/v2/block/{block2_id}")).await;
check_url(format!("/api/v2/block/{block3_id}")).await;
check_url(format!("/api/v2/transaction/{tx1_id}")).await;
check_url(format!("/api/v2/transaction/{tx2_id}")).await;
check_url(format!("/api/v2/transaction/{tx3_id}")).await;
task.abort();
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test]
async fn order_pairs(#[case] seed: Seed) {
use common::{chain::tokens::TokenId, primitives::H256};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();
let task = tokio::spawn(async move {
let web_server_state = {
let mut rng = make_seedable_rng(seed);
let chain_config = create_unit_test_config();
let chainstate_blocks = {
let mut tf = TestFramework::builder(&mut rng)
.with_chain_config(chain_config.clone())
.build();
// Issue and mint some tokens to create an order with different currencies
let issue_and_mint_result =
helpers::issue_and_mint_tokens_from_genesis(&mut rng, &mut tf);
// Create order
let order_data = OrderData::new(
Destination::AnyoneCanSpend,
OutputValue::Coin(Amount::from_atoms(10)),
OutputValue::TokenV1(issue_and_mint_result.token_id, Amount::from_atoms(10)),
);
let order_id = make_order_id(&issue_and_mint_result.tokens_outpoint);
let tx_1 = TransactionBuilder::new()
.add_input(
TxInput::Utxo(issue_and_mint_result.tokens_outpoint),
InputWitness::NoSignature(None),
)
.add_output(TxOutput::CreateOrder(Box::new(order_data)))
.build();
let block1 = tf.make_block_builder().add_transaction(tx_1.clone()).build(&mut rng);
tf.process_block(block1.clone(), BlockSource::Local).unwrap();
_ = tx.send((
Address::new(&chain_config, order_id).unwrap().into_string(),
chain_config.coin_ticker().to_owned(),
Address::new(&chain_config, issue_and_mint_result.token_id)
.unwrap()
.into_string(),
));
vec![issue_and_mint_result.issue_block, issue_and_mint_result.mint_block, block1]
};
let storage = {
let mut storage = TransactionalApiServerInMemoryStorage::new(&chain_config);
let mut db_tx = storage.transaction_rw().await.unwrap();
db_tx.reinitialize_storage(&chain_config).await.unwrap();
db_tx.commit().await.unwrap();
storage
};
let chain_config = Arc::new(chain_config);
let mut local_node = BlockchainState::new(Arc::clone(&chain_config), storage);
local_node.scan_genesis(chain_config.genesis_block()).await.unwrap();
local_node.scan_blocks(BlockHeight::new(0), chainstate_blocks).await.unwrap();
ApiServerWebServerState {
db: Arc::new(local_node.storage().clone_storage().await),
chain_config: Arc::clone(&chain_config),
rpc: Arc::new(DummyRPC {}),
cached_values: Arc::new(CachedValues {
feerate_points: RwLock::new((get_time(), vec![])),
}),
time_getter: Default::default(),
}
};
web_server(listener, web_server_state, true).await
});
let (order_id, ml, tkn) = rx.await.unwrap();
// ML_TKN
{
let url = format!("/api/v2/order/pair/{}_{}?offset=0&items={}", ml, tkn, 1);
let response = reqwest::get(format!("http://{}:{}{url}", addr.ip(), addr.port()))
.await
.unwrap();
assert_eq!(response.status(), 200);
let body = response.text().await.unwrap();
let body: serde_json::Value = serde_json::from_str(&body).unwrap();
let arr_body = body.as_array().unwrap();
assert_eq!(arr_body.len(), 1);
assert_eq!(
arr_body[0].as_object().unwrap().get("order_id").unwrap(),
&serde_json::Value::String(order_id.clone())
);
}
// TKN_ML
{
let url = format!("/api/v2/order/pair/{}_{}?offset=0&items={}", tkn, ml, 1);
let response = reqwest::get(format!("http://{}:{}{url}", addr.ip(), addr.port()))
.await
.unwrap();
assert_eq!(response.status(), 200);
let body = response.text().await.unwrap();
let body: serde_json::Value = serde_json::from_str(&body).unwrap();
let arr_body = body.as_array().unwrap();
assert_eq!(arr_body.len(), 1);
assert_eq!(
arr_body[0].as_object().unwrap().get("order_id").unwrap(),
&serde_json::Value::String(order_id)
);
}
let mut rng = make_seedable_rng(seed);
// Random ticker
let random_ticker = test_utils::random_ascii_alphanumeric_string(&mut rng, 3..5);
let url = format!(
"/api/v2/order/pair/{}_{}?offset=0&items={}",
random_ticker, ml, 1
);
let response = reqwest::get(format!("http://{}:{}{url}", addr.ip(), addr.port()))
.await
.unwrap();
assert_eq!(response.status(), 400);
let body = response.text().await.unwrap();
let body: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(body["error"].as_str().unwrap(), "Invalid token Id");
// Random token
let chain_config = create_unit_test_config();
let random_token_id = TokenId::new(H256::random_using(&mut rng));
let random_token_id = Address::new(&chain_config, random_token_id).unwrap().into_string();
let url = format!(
"/api/v2/order/pair/{}_{}?offset=0&items={}",
random_token_id, ml, 1
);
let response = reqwest::get(format!("http://{}:{}{url}", addr.ip(), addr.port()))
.await
.unwrap();
assert_eq!(response.status(), 200);
let body = response.text().await.unwrap();
let body: serde_json::Value = serde_json::from_str(&body).unwrap();
let arr_body = body.as_array().unwrap();
assert!(arr_body.is_empty());
task.abort();
}