ostium-rust-sdk 0.1.0

Rust SDK for interacting with the Ostium trading platform on Arbitrum
Documentation
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
//! Unit tests for error mapping functionality
//!
//! These tests verify that contract errors are properly decoded into human-readable messages
//! and that appropriate suggestions are provided for common error scenarios.
//!
//! ## Test Coverage
//!
//! - **Contract Error Mapping**: Tests mapping of Ethereum contract error selectors to human-readable messages
//! - **Error Pattern Recognition**: Tests recognition of different error patterns (gas estimation, execution reverted, etc.)
//! - **Suggestion Generation**: Tests that appropriate suggestions are provided for different error types
//! - **Error Selector Extraction**: Tests extraction of error selectors from various error message formats
//! - **Error Data Structure**: Tests that error data contains all expected fields and metadata
//! - **Performance**: Tests that error mapping is fast enough for production use
//!
//! ## Error Types Covered
//!
//! - Contract-specific errors (WrongParams, PairNotListed, WrongLeverage, etc.)
//! - Network errors (InsufficientFunds, NonceTooLow, OutOfGas, etc.)
//! - Gas estimation errors (prefixed with "GasEstimation_")
//! - Unknown/unrecognized errors

use ostium_rust_sdk::{Network, OstiumClient};

/// Helper function to create a test client for error mapping tests
async fn create_test_client() -> OstiumClient {
    OstiumClient::new(Network::Testnet)
        .await
        .expect("Failed to create test client")
}

#[tokio::test]
async fn test_map_contract_error_wrong_params() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x5863f789";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "WrongParams");
    assert_eq!(message, "Contract error: WrongParams");
    assert_eq!(error_data.get("selector"), Some(&"0x5863f789".to_string()));
    assert_eq!(
        error_data.get("contract_error"),
        Some(&"WrongParams".to_string())
    );
    assert_eq!(error_data.get("original_error"), Some(&error.to_string()));
}

#[tokio::test]
async fn test_map_contract_error_pair_not_listed() {
    let client = create_test_client().await;
    let error = "Gas estimation failed: execution reverted with reason string '0xcb87b762'";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "GasEstimation_PairNotListed");
    assert_eq!(
        message,
        "Gas estimation failed due to contract error: PairNotListed"
    );
    assert_eq!(error_data.get("selector"), Some(&"0xcb87b762".to_string()));
    assert_eq!(
        error_data.get("contract_error"),
        Some(&"PairNotListed".to_string())
    );
}

#[tokio::test]
async fn test_map_contract_error_is_paused() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x1309a563";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "IsPaused");
    assert_eq!(message, "Contract error: IsPaused");
    assert_eq!(error_data.get("selector"), Some(&"0x1309a563".to_string()));
}

#[tokio::test]
async fn test_map_contract_error_wrong_leverage() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x35fe85c5";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "WrongLeverage");
    assert_eq!(message, "Contract error: WrongLeverage");
    assert_eq!(error_data.get("selector"), Some(&"0x35fe85c5".to_string()));
}

#[tokio::test]
async fn test_map_contract_error_below_min_lev_pos() {
    let client = create_test_client().await;
    let error = "execution reverted: 0xeca695e1";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "BelowMinLevPos");
    assert_eq!(message, "Contract error: BelowMinLevPos");
    assert_eq!(error_data.get("selector"), Some(&"0xeca695e1".to_string()));
}

#[tokio::test]
async fn test_map_contract_error_max_trades_per_pair() {
    let client = create_test_client().await;
    let error = "execution reverted: 0xe6f47fab";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "MaxTradesPerPairReached");
    assert_eq!(message, "Contract error: MaxTradesPerPairReached");
    assert_eq!(error_data.get("selector"), Some(&"0xe6f47fab".to_string()));
}

#[tokio::test]
async fn test_map_contract_error_wrong_tp() {
    let client = create_test_client().await;
    let error = "execution reverted: 0xa41bb918";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "WrongTP");
    assert_eq!(message, "Contract error: WrongTP");
    assert_eq!(error_data.get("selector"), Some(&"0xa41bb918".to_string()));
}

#[tokio::test]
async fn test_map_contract_error_wrong_sl() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x083fbd78";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "WrongSL");
    assert_eq!(message, "Contract error: WrongSL");
    assert_eq!(error_data.get("selector"), Some(&"0x083fbd78".to_string()));
}

#[tokio::test]
async fn test_map_contract_error_insufficient_funds() {
    let client = create_test_client().await;
    let error = "insufficient funds for gas * price + value";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "InsufficientFunds");
    assert_eq!(message, "Insufficient funds for transaction");
    assert_eq!(error_data.get("original_error"), Some(&error.to_string()));
}

#[tokio::test]
async fn test_map_contract_error_nonce_too_low() {
    let client = create_test_client().await;
    let error = "nonce too low";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "NonceTooLow");
    assert_eq!(message, "Transaction nonce is too low");
    assert_eq!(error_data.get("original_error"), Some(&error.to_string()));
}

#[tokio::test]
async fn test_map_contract_error_out_of_gas() {
    let client = create_test_client().await;
    let error = "gas required exceeds allowance or always failing transaction";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "OutOfGas");
    assert_eq!(message, "Transaction requires more gas than allowed");
    assert_eq!(error_data.get("original_error"), Some(&error.to_string()));
}

#[tokio::test]
async fn test_map_contract_error_underpriced_replacement() {
    let client = create_test_client().await;
    let error = "replacement transaction underpriced";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "UnderpricedReplacement");
    assert_eq!(message, "Replacement transaction gas price too low");
    assert_eq!(error_data.get("original_error"), Some(&error.to_string()));
}

#[tokio::test]
async fn test_map_contract_error_unknown_selector() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x99999999";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "UnknownError");
    assert_eq!(message, error);
    assert_eq!(error_data.get("original_error"), Some(&error.to_string()));
}

#[tokio::test]
async fn test_map_contract_error_no_selector() {
    let client = create_test_client().await;
    let error = "Some random error without selector";

    let (message, error_type, error_data) = client.map_contract_error(error);

    assert_eq!(error_type, "UnknownError");
    assert_eq!(message, error);
    assert_eq!(error_data.get("original_error"), Some(&error.to_string()));
}

#[tokio::test]
async fn test_map_contract_error_with_suggestions_wrong_params() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x5863f789";

    let (message, error_type, error_data, suggestion) =
        client.map_contract_error_with_suggestions(error);

    assert_eq!(error_type, "WrongParams");
    assert_eq!(message, "Contract error: WrongParams");
    assert!(suggestion.is_some());
    assert_eq!(
        suggestion.unwrap(),
        "Check that all parameters (collateral, leverage, prices) are within valid ranges"
    );
    assert_eq!(
        error_data.get("suggestion"),
        Some(
            &"Check that all parameters (collateral, leverage, prices) are within valid ranges"
                .to_string()
        )
    );
}

#[tokio::test]
async fn test_map_contract_error_with_suggestions_pair_not_listed() {
    let client = create_test_client().await;
    let error = "execution reverted: 0xcb87b762";

    let (_, error_type, error_data, suggestion) = client.map_contract_error_with_suggestions(error);

    assert_eq!(error_type, "PairNotListed");
    assert!(suggestion.is_some());
    assert_eq!(
        suggestion.unwrap(),
        "Verify the trading pair symbol is correct and supported"
    );
    assert_eq!(
        error_data.get("suggestion"),
        Some(&"Verify the trading pair symbol is correct and supported".to_string())
    );
}

#[tokio::test]
async fn test_map_contract_error_with_suggestions_wrong_leverage() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x35fe85c5";

    let (_, error_type, _, suggestion) = client.map_contract_error_with_suggestions(error);

    assert_eq!(error_type, "WrongLeverage");
    assert!(suggestion.is_some());
    assert_eq!(
        suggestion.unwrap(),
        "Adjust leverage to be within the allowed range for this pair"
    );
}

#[tokio::test]
async fn test_map_contract_error_with_suggestions_insufficient_funds() {
    let client = create_test_client().await;
    let error = "insufficient funds for gas * price + value";

    let (_, error_type, _, suggestion) = client.map_contract_error_with_suggestions(error);

    assert_eq!(error_type, "InsufficientFunds");
    assert!(suggestion.is_some());
    assert_eq!(
        suggestion.unwrap(),
        "Ensure sufficient USDC balance and allowance for the trade"
    );
}

#[tokio::test]
async fn test_map_contract_error_with_suggestions_no_suggestion() {
    let client = create_test_client().await;
    let error = "Some unknown error";

    let (_, error_type, _, suggestion) = client.map_contract_error_with_suggestions(error);

    assert_eq!(error_type, "UnknownError");
    assert!(suggestion.is_none());
}

#[tokio::test]
async fn test_get_error_description_all_selectors() {
    let client = create_test_client().await;

    // Test all known error selectors
    let test_cases = vec![
        (
            "0x5863f789",
            "Wrong parameters provided to the contract function",
        ),
        ("0xcb87b762", "Trading pair is not listed or supported"),
        ("0x1309a563", "Contract is currently paused"),
        ("0x093650d5", "Caller is not the contract governor"),
        ("0x2a19e833", "Caller is not a contract manager"),
        ("0x084986e7", "Operation is already completed"),
        ("0x432b6c83", "Caller is not authorized for trades upkeep"),
        ("0xe6f47fab", "Maximum number of trades per pair reached"),
        ("0x5c12ea62", "Maximum pending market orders reached"),
        ("0x35fe85c5", "Leverage value is outside allowed range"),
        ("0x80a71fc5", "Collateral amount exceeds maximum allowed"),
        (
            "0xeca695e1",
            "Position size is below minimum leverage requirement",
        ),
        ("0xa41bb918", "Take profit price is invalid"),
        ("0x083fbd78", "Stop loss price is invalid"),
        ("0x17e08e97", "Trade not found"),
        ("0xdd9397bb", "Trigger order is pending"),
        ("0xf77a8069", "Market is already closed"),
        ("0xa35ee470", "Limit order not found"),
        ("0x46c4ede2", "Exposure limits exceeded"),
        ("0xefa9e5be", "No trade found for timeout"),
        ("0x5ac89f62", "Not your order"),
        ("0x1add0915", "Not an open market timeout order"),
        ("0x3e0b1869", "Must wait for timeout period"),
        ("0xc7fe4d00", "Not a close market timeout order"),
    ];

    for (selector, expected_description) in test_cases {
        let description = client.get_error_description(selector);
        assert!(
            description.is_some(),
            "Description should exist for selector {}",
            selector
        );
        assert_eq!(description.unwrap(), expected_description);
    }
}

#[tokio::test]
async fn test_get_error_description_unknown_selector() {
    let client = create_test_client().await;

    let description = client.get_error_description("0x99999999");
    assert!(description.is_none());
}

#[tokio::test]
async fn test_extract_error_selector_various_formats() {
    let client = create_test_client().await;

    // Test various error message formats
    let test_cases = vec![
        ("execution reverted: 0x5863f789", Some("0x5863f789")),
        ("Gas estimation failed: 0xcb87b762", Some("0xcb87b762")),
        ("Error with 0x1309a563 in the middle", Some("0x1309a563")),
        (
            "Multiple selectors 0x5863f789 and 0xcb87b762",
            Some("0x5863f789"),
        ), // Should return first
        ("No selector here", None),
        ("Invalid selector 0x123", None), // Too short
        ("Invalid selector 0x123456789", Some("0x12345678")), // Takes first 8 hex chars after 0x
        ("Invalid selector 0xgggggggg", None), // Invalid hex
        ("0X5863F789", Some("0x5863f789")), // Should handle uppercase
    ];

    for (error_msg, expected) in test_cases {
        let result = client.extract_error_selector(error_msg);
        assert_eq!(
            result.as_deref(),
            expected,
            "Failed for input: {}",
            error_msg
        );
    }
}

#[tokio::test]
async fn test_error_mapping_comprehensive_scenarios() {
    let client = create_test_client().await;

    // Test comprehensive error scenarios that might occur in real usage
    let scenarios = vec![
        (
            "Gas estimation failed: execution reverted with reason string '0x5863f789'",
            "GasEstimation_WrongParams",
            "Gas estimation failed due to contract error: WrongParams",
            Some(
                "Check that all parameters (collateral, leverage, prices) are within valid ranges",
            ),
        ),
        (
            "execution reverted: 0xe6f47fab",
            "MaxTradesPerPairReached",
            "Contract error: MaxTradesPerPairReached",
            Some("Close some existing positions before opening new ones"),
        ),
        (
            "insufficient balance for transfer",
            "InsufficientFunds",
            "Insufficient funds for transaction",
            Some("Ensure sufficient USDC balance and allowance for the trade"),
        ),
        (
            "gas required exceeds allowance",
            "OutOfGas",
            "Transaction requires more gas than allowed",
            Some("Increase gas limit for the transaction"),
        ),
    ];

    for (error_msg, expected_type, expected_message, expected_suggestion) in scenarios {
        let (message, error_type, error_data, suggestion) =
            client.map_contract_error_with_suggestions(error_msg);

        assert_eq!(
            error_type, expected_type,
            "Error type mismatch for: {}",
            error_msg
        );
        assert_eq!(
            message, expected_message,
            "Error message mismatch for: {}",
            error_msg
        );
        assert_eq!(
            suggestion.as_deref(),
            expected_suggestion,
            "Suggestion mismatch for: {}",
            error_msg
        );

        // Verify error data contains original error
        assert_eq!(
            error_data.get("original_error"),
            Some(&error_msg.to_string())
        );

        // If there's a suggestion, it should also be in error_data
        if let Some(suggestion_text) = &suggestion {
            assert_eq!(error_data.get("suggestion"), Some(suggestion_text));
        }
    }
}

#[tokio::test]
async fn test_error_data_structure() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x5863f789";

    let (_, _, error_data) = client.map_contract_error(error);

    // Verify error_data contains expected keys
    assert!(error_data.contains_key("original_error"));
    assert!(error_data.contains_key("selector"));
    assert!(error_data.contains_key("contract_error"));

    // Verify types
    assert!(error_data.get("original_error").unwrap().is_ascii());
    assert!(error_data.get("selector").unwrap().starts_with("0x"));
    assert!(!error_data.get("contract_error").unwrap().is_empty());
}

#[tokio::test]
async fn test_case_insensitive_selector_extraction() {
    let client = create_test_client().await;

    let test_cases = vec![
        "execution reverted: 0x5863f789",
        "execution reverted: 0x5863F789",
        "execution reverted: 0X5863f789",
        "execution reverted: 0X5863F789",
    ];

    for error_msg in test_cases {
        let result = client.extract_error_selector(error_msg);
        assert_eq!(
            result,
            Some("0x5863f789".to_string()),
            "Failed for: {}",
            error_msg
        );
    }
}

#[tokio::test]
async fn test_multiple_selectors_in_error() {
    let client = create_test_client().await;
    let error = "Multiple errors: 0x5863f789 and also 0xcb87b762 occurred";

    // Should extract the first valid selector
    let result = client.extract_error_selector(error);
    assert_eq!(result, Some("0x5863f789".to_string()));
}

#[tokio::test]
async fn test_error_mapping_performance() {
    let client = create_test_client().await;
    let error = "execution reverted: 0x5863f789";

    // Test that error mapping is fast enough for production use
    let start = std::time::Instant::now();

    for _ in 0..1000 {
        let _ = client.map_contract_error(error);
    }

    let duration = start.elapsed();
    assert!(
        duration.as_millis() < 100,
        "Error mapping should be fast, took {:?}",
        duration
    );
}