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
//! Build script for the Ostium Rust SDK
//!
//! This build script automatically fetches and generates Rust ABI bindings from the Ostium Python SDK.
//! It performs the following tasks:
//!
//! 1. **ABI Synchronization**: Downloads the latest ABI definitions from the Ostium Python SDK
//!    repository to ensure the Rust SDK stays in sync with the canonical contract interfaces.
//!
//! 2. **Python to JSON Conversion**: Parses Python ABI definitions (which use Python syntax
//!    like `True`, `False`, `None`) and converts them to valid JSON format for use in Rust.
//!
//! 3. **Rust Binding Generation**: Creates individual Rust modules for each contract ABI,
//!    exposing them as string constants that can be used with web3 libraries like ethers-rs.
//!
//! 4. **Module Organization**: Generates a `mod.rs` file that organizes all ABI modules
//!    and re-exports the ABI constants for easy access.
//!
//! The script only runs when:
//! - The `update-contracts` feature is enabled, OR
//! - The `src/abi/generated` directory doesn't exist
//!
//! This ensures ABIs are updated when explicitly requested or during initial setup,
//! but doesn't slow down regular builds by making unnecessary network requests.
//!
//! Generated files are placed in `src/abi/generated/` and follow the pattern:
//! - `{contract_name}.rs` - Individual ABI modules
//! - `mod.rs` - Module organization and re-exports
//!
//! Example usage of generated ABIs:
//! ```rust
//! use ostium_rust_sdk::abi::generated::SOME_CONTRACT_ABI;
//! let contract = Contract::from_json(provider, address, SOME_CONTRACT_ABI)?;
//! ```

use reqwest::blocking::Client;
use std::collections::HashMap;
use std::fs;
use std::path::Path;

const OSTIUM_PYTHON_SDK_ABI_URL: &str = "https://raw.githubusercontent.com/0xOstium/ostium-python-sdk/main/ostium_python_sdk/abi/abi.py";

// No longer needed - we're using ABIs directly from Python SDK

fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-env-changed=CARGO_FEATURE_UPDATE_CONTRACTS");

    // Only fetch ABIs if explicitly requested via feature flag
    let force_update = std::env::var("CARGO_FEATURE_UPDATE_CONTRACTS").is_ok();
    let abi_dir_exists = Path::new("src/abi/generated").exists();

    if force_update {
        // Explicit update requested
        if let Err(e) = fetch_and_generate_abis() {
            println!(
                "cargo:warning=Failed to fetch ABIs from Ostium Python SDK: {}",
                e
            );
            println!("cargo:warning=Using existing ABI definitions");
        }
    } else if !abi_dir_exists {
        // First-time setup: try to fetch ABIs, but don't fail the build if it doesn't work
        println!("cargo:warning=ABI directory doesn't exist, attempting initial fetch...");
        if let Err(e) = fetch_and_generate_abis() {
            println!(
                "cargo:warning=Failed to fetch ABIs during initial setup: {}",
                e
            );
            println!("cargo:warning=You may need to run 'cargo build --features update-contracts' to fetch ABIs");
            // Don't fail the build - let it continue without ABIs for now
        }
    }
    // If ABIs exist and no force update, do nothing (normal build)
}

fn fetch_and_generate_abis() -> Result<(), Box<dyn std::error::Error>> {
    println!("cargo:warning=Fetching latest ABIs from Ostium Python SDK...");

    let client = Client::new();

    // Fetch the Python ABI file
    let python_abi_content = client
        .get(OSTIUM_PYTHON_SDK_ABI_URL)
        .header("User-Agent", "ostium-rust-sdk")
        .send()?
        .text()?;

    // Parse the Python file to extract ABIs
    let abis = parse_python_abis(&python_abi_content)?;

    if abis.is_empty() {
        println!("cargo:warning=No ABIs found in the Python SDK");
        return Ok(());
    }

    // Create output directory
    fs::create_dir_all("src/abi/generated")?;

    // Check if any ABIs have actually changed
    let mut changes_detected = false;
    let mut updated_contracts = Vec::new();

    // Process each ABI and check for changes
    for (contract_name, abi_json) in &abis {
        if has_abi_changed(contract_name, abi_json)? {
            generate_rust_abi_binding(contract_name, abi_json)?;
            changes_detected = true;
            updated_contracts.push(contract_name.clone());
        }
    }

    // Only regenerate mod.rs if there were changes
    if changes_detected {
        generate_abi_mod(&abis)?;
        println!(
            "cargo:warning=Successfully updated {} ABIs from Python SDK: {}",
            updated_contracts.len(),
            updated_contracts.join(", ")
        );
    } else {
        println!("cargo:warning=All ABIs are up to date - no changes detected");
    }

    Ok(())
}

fn parse_python_abis(
    python_content: &str,
) -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
    let mut abis = HashMap::new();

    // Parse the Python file to extract ABI definitions
    // Look for patterns like: contract_name_abi = [...]
    let lines: Vec<&str> = python_content.lines().collect();
    let mut current_abi_name = String::new();
    let mut current_abi_content = String::new();
    let mut in_abi = false;
    let mut bracket_count = 0;
    let mut line_number = 0;

    for line in lines {
        line_number += 1;
        let trimmed = line.trim();

        // Check if this line starts an ABI definition
        if trimmed.ends_with("_abi = [") {
            if let Some(name_part) = trimmed.strip_suffix("_abi = [") {
                current_abi_name = name_part.trim().to_string();
                current_abi_content = String::from("[\n");
                in_abi = true;
                bracket_count = 1;
                println!(
                    "cargo:warning=Found ABI definition: {} at line {}",
                    current_abi_name, line_number
                );
                continue;
            }
        }

        if in_abi {
            // Count brackets to know when the ABI definition ends
            for ch in trimmed.chars() {
                match ch {
                    '[' | '{' => bracket_count += 1,
                    ']' | '}' => bracket_count -= 1,
                    _ => {}
                }
            }

            current_abi_content.push_str(line);
            current_abi_content.push('\n');

            // If we've closed all brackets, we're done with this ABI
            if bracket_count == 0 {
                in_abi = false;

                // Convert Python format to JSON format
                match convert_python_to_json(&current_abi_content) {
                    Ok(json_abi) => {
                        // Extract contract name from variable name (remove _abi suffix)
                        let contract_name = if current_abi_name.ends_with("_abi") {
                            current_abi_name.trim_end_matches("_abi").to_string()
                        } else {
                            current_abi_name.clone()
                        };

                        println!(
                            "cargo:warning=Successfully parsed ABI for: {}",
                            contract_name
                        );
                        abis.insert(contract_name, json_abi);
                    }
                    Err(e) => {
                        println!(
                            "cargo:warning=Failed to parse ABI for {}: {}",
                            current_abi_name, e
                        );
                        println!(
                            "cargo:warning=ABI content length: {} characters",
                            current_abi_content.len()
                        );
                        // Continue processing other ABIs instead of failing completely
                    }
                }

                current_abi_name.clear();
                current_abi_content.clear();
            }
        }
    }

    // Check if we ended while still parsing an ABI
    if in_abi {
        println!(
            "cargo:warning=Warning: File ended while parsing ABI: {}",
            current_abi_name
        );
        println!("cargo:warning=Bracket count at end: {}", bracket_count);
    }

    if abis.is_empty() {
        println!("cargo:warning=No valid ABIs were parsed from the Python file");
        println!("cargo:warning=Total lines processed: {}", line_number);
    } else {
        let abi_names: Vec<String> = abis.keys().cloned().collect();
        println!(
            "cargo:warning=Successfully parsed {} ABIs: {}",
            abis.len(),
            abi_names.join(", ")
        );
    }

    Ok(abis)
}

fn convert_python_to_json(python_abi: &str) -> Result<String, Box<dyn std::error::Error>> {
    // Convert Python syntax to JSON syntax
    let mut json_content = python_abi
        .replace("True", "true")
        .replace("False", "false")
        .replace("None", "null");

    // Process line by line to handle comments and formatting
    json_content = json_content
        .lines()
        .map(|line| {
            // Remove Python comments (lines starting with # or inline comments)
            let line_without_comment = if let Some(comment_pos) = line.find('#') {
                // Check if the # is inside a string literal by counting quotes before it
                let before_comment = &line[..comment_pos];
                let quote_count = before_comment.matches('"').count();
                if quote_count % 2 == 0 {
                    // Even number of quotes means # is outside string, so it's a comment
                    before_comment.trim_end().to_string()
                } else {
                    // Odd number of quotes means # is inside string, keep the line
                    line.to_string()
                }
            } else {
                line.to_string()
            };

            // Handle trailing commas before closing brackets/braces
            let trimmed_no_comment = line_without_comment.trim();
            if trimmed_no_comment.ends_with(",}") {
                line_without_comment.replace(",}", "}")
            } else if trimmed_no_comment.ends_with(",]") {
                line_without_comment.replace(",]", "]")
            } else {
                line_without_comment
            }
        })
        .filter(|line| {
            let trimmed = line.trim();
            // Remove empty lines and lines that are just comments
            !trimmed.is_empty() && !trimmed.starts_with('#')
        })
        .collect::<Vec<String>>()
        .join("\n");

    // Clean up any remaining issues
    json_content = json_content.trim().to_string();

    // Remove any trailing content after the final closing bracket
    if let Some(last_bracket_pos) = json_content.rfind(']') {
        // Find if there's any non-whitespace content after the last bracket
        let after_bracket = &json_content[last_bracket_pos + 1..];
        if after_bracket.trim().is_empty() || after_bracket.trim().starts_with('#') {
            // Truncate at the last bracket if there's only whitespace or comments after
            json_content = json_content[..=last_bracket_pos].to_string();
        }
    }

    // Validate that it's proper JSON with better error reporting
    match serde_json::from_str::<serde_json::Value>(&json_content) {
        Ok(_) => Ok(json_content),
        Err(e) => {
            // Provide more detailed error information
            println!("cargo:warning=JSON parsing failed: {}", e);
            println!(
                "cargo:warning=Content length: {} characters",
                json_content.len()
            );

            // Show a snippet around the error location if possible
            if let Some(line_col) = extract_line_column_from_error(&e.to_string()) {
                let (line_num, col_num) = line_col;
                let lines: Vec<&str> = json_content.lines().collect();
                if line_num > 0 && line_num <= lines.len() {
                    println!(
                        "cargo:warning=Error near line {}: {}",
                        line_num,
                        lines[line_num - 1]
                    );
                    if col_num > 0 {
                        let pointer = " ".repeat(col_num.saturating_sub(1)) + "^";
                        println!("cargo:warning={}", pointer);
                    }
                }
            }

            Err(format!("Failed to parse ABI as JSON: {}", e).into())
        }
    }
}

// Helper function to extract line and column from JSON error messages
fn extract_line_column_from_error(error_msg: &str) -> Option<(usize, usize)> {
    // Try to parse error messages like "trailing characters at line 1916 column 4"
    if let Some(line_start) = error_msg.find("line ") {
        if let Some(col_start) = error_msg.find(" column ") {
            let line_part = &error_msg[line_start + 5..col_start];
            let col_part = &error_msg[col_start + 8..];

            if let (Ok(line), Ok(col)) = (
                line_part.trim().parse::<usize>(),
                col_part
                    .split_whitespace()
                    .next()
                    .unwrap_or("0")
                    .parse::<usize>(),
            ) {
                return Some((line, col));
            }
        }
    }
    None
}

fn has_abi_changed(
    contract_name: &str,
    new_abi_json: &str,
) -> Result<bool, Box<dyn std::error::Error>> {
    let output_path = format!("src/abi/generated/{}.rs", contract_name.to_lowercase());

    // If file doesn't exist, it's a change
    if !Path::new(&output_path).exists() {
        return Ok(true);
    }

    // Read existing file and extract the ABI JSON
    let existing_content = fs::read_to_string(&output_path)?;

    // Extract the ABI JSON from the existing file using string parsing
    // Look for the pattern: pub const CONTRACT_ABI: &str = r###"..."###;
    if let Some(start_pos) = existing_content.find("r###\"") {
        if let Some(end_pos) = existing_content[start_pos + 5..].find("\"###") {
            let existing_abi_json = &existing_content[start_pos + 5..start_pos + 5 + end_pos];

            // Parse both ABIs and compare them (normalized)
            match (
                serde_json::from_str::<serde_json::Value>(existing_abi_json),
                serde_json::from_str::<serde_json::Value>(new_abi_json),
            ) {
                (Ok(existing_abi), Ok(new_abi)) => {
                    // Compare normalized JSON (this handles formatting differences)
                    Ok(existing_abi != new_abi)
                }
                _ => {
                    // If we can't parse either ABI, assume it's changed
                    Ok(true)
                }
            }
        } else {
            // Couldn't find end marker, assume it's changed
            Ok(true)
        }
    } else {
        // Couldn't find start marker, assume it's changed
        Ok(true)
    }
}

fn generate_rust_abi_binding(
    contract_name: &str,
    abi_json: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    println!(
        "cargo:warning=Generating ABI binding for: {}",
        contract_name
    );

    let contract_name_upper = contract_name.to_uppercase();

    let mut binding = String::new();
    binding.push_str(&format!(
        "//! Auto-generated ABI binding for {}\n",
        contract_name
    ));
    binding.push_str("//! Source: https://github.com/0xOstium/ostium-python-sdk\n\n");

    binding.push_str(&format!("/// Raw ABI JSON for {}\n", contract_name));
    binding.push_str(&format!(
        "pub const {}_ABI: &str = r###\"{}\"###;\n",
        contract_name_upper, abi_json
    ));

    let output_path = format!("src/abi/generated/{}.rs", contract_name.to_lowercase());
    fs::write(&output_path, binding)?;

    Ok(())
}

fn generate_abi_mod(abis: &HashMap<String, String>) -> Result<(), Box<dyn std::error::Error>> {
    let mut mod_content =
        String::from("//! Auto-generated module for ABIs from Ostium Python SDK\n\n");

    for contract_name in abis.keys() {
        let module_name = contract_name.to_lowercase();
        mod_content.push_str(&format!("pub mod {};\n", module_name));
    }

    mod_content.push('\n');

    // Re-export the ABI constants
    for contract_name in abis.keys() {
        let module_name = contract_name.to_lowercase();
        let const_name = format!("{}_ABI", contract_name.to_uppercase());
        mod_content.push_str(&format!("pub use {}::{};\n", module_name, const_name));
    }

    fs::write("src/abi/generated/mod.rs", mod_content)?;
    Ok(())
}