aptos-sdk 0.4.1

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Build script helper for code generation.
//!
//! This module provides utilities for generating code at compile time via `build.rs`.
//!
//! # Example
//!
//! Add to your `build.rs`:
//!
//! ```rust,ignore
//! use aptos_sdk::codegen::build_helper;
//!
//! fn main() {
//!     // Generate from a local ABI file
//!     build_helper::generate_from_abi(
//!         "abi/my_module.json",
//!         "src/generated/",
//!     ).expect("code generation failed");
//!
//!     // Generate from multiple modules
//!     build_helper::generate_from_abis(&[
//!         "abi/coin.json",
//!         "abi/token.json",
//!     ], "src/generated/").expect("code generation failed");
//!
//!     // Rerun if ABI files change
//!     println!("cargo:rerun-if-changed=abi/");
//! }
//! ```
//!
//! # Directory Structure
//!
//! ```text
//! my_project/
//! ├── build.rs
//! ├── abi/
//! │   ├── my_module.json
//! │   └── another_module.json
//! └── src/
//!     └── generated/
//!         ├── mod.rs          (auto-generated)
//!         ├── my_module.rs
//!         └── another_module.rs
//! ```

use crate::api::response::MoveModuleABI;
use crate::codegen::{GeneratorConfig, ModuleGenerator, MoveSourceParser};
use crate::error::{AptosError, AptosResult};
use std::fs;
use std::path::Path;

/// Returns true if `name` is a Rust keyword that cannot be used as a module name.
fn is_rust_keyword(name: &str) -> bool {
    matches!(
        name,
        "as" | "break"
            | "const"
            | "continue"
            | "crate"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "fn"
            | "for"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "pub"
            | "ref"
            | "return"
            | "self"
            | "Self"
            | "static"
            | "struct"
            | "super"
            | "trait"
            | "true"
            | "type"
            | "unsafe"
            | "use"
            | "where"
            | "while"
            | "async"
            | "await"
            | "dyn"
    )
}

/// Validates that a module name is a safe Rust identifier (no path traversal, injection, or keywords).
///
/// # Security
///
/// This prevents:
/// - Path traversal attacks via names like `../../../tmp/evil`
/// - Invalid `pub mod` declarations in generated mod.rs (e.g., `pub mod fn;`)
fn validate_module_name(name: &str) -> AptosResult<()> {
    if name.is_empty() {
        return Err(AptosError::Config(
            "module name cannot be empty".to_string(),
        ));
    }

    // Must be a valid Rust identifier: starts with letter or underscore,
    // contains only alphanumeric or underscore characters
    let mut chars = name.chars();
    let first = chars.next().unwrap(); // safe: name is non-empty
    if !first.is_ascii_alphabetic() && first != '_' {
        return Err(AptosError::Config(format!(
            "invalid module name '{name}': must start with a letter or underscore"
        )));
    }

    if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
        return Err(AptosError::Config(format!(
            "invalid module name '{name}': must contain only ASCII alphanumeric characters or underscores"
        )));
    }

    if is_rust_keyword(name) {
        return Err(AptosError::Config(format!(
            "invalid module name '{name}': Rust keywords cannot be used as module names"
        )));
    }

    Ok(())
}

/// Configuration for build-time code generation.
#[derive(Debug, Clone)]
pub struct BuildConfig {
    /// Generator configuration.
    pub generator_config: GeneratorConfig,
    /// Whether to generate a `mod.rs` file.
    pub generate_mod_file: bool,
    /// Whether to print build instructions to cargo.
    pub print_cargo_instructions: bool,
}

impl Default for BuildConfig {
    fn default() -> Self {
        Self {
            generator_config: GeneratorConfig::default(),
            generate_mod_file: true,
            print_cargo_instructions: true,
        }
    }
}

impl BuildConfig {
    /// Creates a new build configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets whether to generate a mod.rs file.
    #[must_use]
    pub fn with_mod_file(mut self, enabled: bool) -> Self {
        self.generate_mod_file = enabled;
        self
    }

    /// Sets the generator configuration.
    #[must_use]
    pub fn with_generator_config(mut self, config: GeneratorConfig) -> Self {
        self.generator_config = config;
        self
    }

    /// Sets whether to print cargo instructions.
    #[must_use]
    pub fn with_cargo_instructions(mut self, enabled: bool) -> Self {
        self.print_cargo_instructions = enabled;
        self
    }
}

/// Generates Rust code from a single ABI file.
///
/// # Arguments
///
/// * `abi_path` - Path to the ABI JSON file
/// * `output_dir` - Directory where generated code will be written
///
/// # Errors
///
/// Returns an error if:
/// * The ABI file cannot be read
/// * The ABI JSON cannot be parsed
/// * Code generation fails
/// * The output directory cannot be created
/// * The output file cannot be written
///
/// # Example
///
/// ```rust,ignore
/// build_helper::generate_from_abi("abi/coin.json", "src/generated/")?;
/// ```
pub fn generate_from_abi(
    abi_path: impl AsRef<Path>,
    output_dir: impl AsRef<Path>,
) -> AptosResult<()> {
    generate_from_abi_with_config(abi_path, output_dir, BuildConfig::default())
}

/// Generates Rust code from a single ABI file with custom configuration.
///
/// # Errors
///
/// Returns an error if:
/// * The ABI file cannot be read
/// * The ABI JSON cannot be parsed
/// * Code generation fails
/// * The output directory cannot be created
/// * The output file cannot be written
pub fn generate_from_abi_with_config(
    abi_path: impl AsRef<Path>,
    output_dir: impl AsRef<Path>,
    config: BuildConfig,
) -> AptosResult<()> {
    let abi_path = abi_path.as_ref();
    let output_dir = output_dir.as_ref();

    // Read and parse ABI
    let abi_content = fs::read_to_string(abi_path).map_err(|e| {
        AptosError::Config(format!(
            "Failed to read ABI file {}: {}",
            abi_path.display(),
            e
        ))
    })?;

    let abi: MoveModuleABI = serde_json::from_str(&abi_content)
        .map_err(|e| AptosError::Config(format!("Failed to parse ABI JSON: {e}")))?;

    // SECURITY: Validate module name to prevent path traversal
    validate_module_name(&abi.name)?;

    // Generate code
    let generator = ModuleGenerator::new(&abi, config.generator_config);
    let code = generator.generate()?;

    // Create output directory
    fs::create_dir_all(output_dir)
        .map_err(|e| AptosError::Config(format!("Failed to create output directory: {e}")))?;

    // Write output file
    let output_filename = format!("{}.rs", abi.name);
    let output_path = output_dir.join(&output_filename);

    fs::write(&output_path, &code)
        .map_err(|e| AptosError::Config(format!("Failed to write output file: {e}")))?;

    if config.print_cargo_instructions {
        println!("cargo:rerun-if-changed={}", abi_path.display());
    }

    Ok(())
}

/// Generates Rust code from multiple ABI files.
///
/// Also generates a `mod.rs` file that re-exports all generated modules.
///
/// # Arguments
///
/// * `abi_paths` - Paths to ABI JSON files
/// * `output_dir` - Directory where generated code will be written
///
/// # Errors
///
/// Returns an error if:
/// * Any ABI file cannot be read
/// * Any ABI JSON cannot be parsed
/// * Code generation fails for any module
/// * The output directory cannot be created
/// * Any output file cannot be written
/// * The `mod.rs` file cannot be written
///
/// # Example
///
/// ```rust,ignore
/// build_helper::generate_from_abis(&[
///     "abi/coin.json",
///     "abi/token.json",
/// ], "src/generated/")?;
/// ```
pub fn generate_from_abis(
    abi_paths: &[impl AsRef<Path>],
    output_dir: impl AsRef<Path>,
) -> AptosResult<()> {
    generate_from_abis_with_config(abi_paths, output_dir, &BuildConfig::default())
}

/// Generates Rust code from multiple ABI files with custom configuration.
///
/// # Errors
///
/// Returns an error if:
/// * Any ABI file cannot be read
/// * Any ABI JSON cannot be parsed
/// * Code generation fails for any module
/// * The output directory cannot be created
/// * Any output file cannot be written
/// * The `mod.rs` file cannot be written (if enabled)
pub fn generate_from_abis_with_config(
    abi_paths: &[impl AsRef<Path>],
    output_dir: impl AsRef<Path>,
    config: &BuildConfig,
) -> AptosResult<()> {
    let output_dir = output_dir.as_ref();
    let mut module_names = Vec::new();

    // Generate code for each ABI
    for abi_path in abi_paths {
        let abi_path = abi_path.as_ref();

        let abi_content = fs::read_to_string(abi_path).map_err(|e| {
            AptosError::Config(format!(
                "Failed to read ABI file {}: {}",
                abi_path.display(),
                e
            ))
        })?;

        let abi: MoveModuleABI = serde_json::from_str(&abi_content).map_err(|e| {
            AptosError::Config(format!(
                "Failed to parse ABI JSON from {}: {}",
                abi_path.display(),
                e
            ))
        })?;

        // SECURITY: Validate module name to prevent path traversal
        validate_module_name(&abi.name)?;

        let generator = ModuleGenerator::new(&abi, config.generator_config.clone());
        let code = generator.generate()?;

        // Create output directory
        fs::create_dir_all(output_dir)
            .map_err(|e| AptosError::Config(format!("Failed to create output directory: {e}")))?;

        // Write output file
        let output_filename = format!("{}.rs", abi.name);
        let output_path = output_dir.join(&output_filename);

        fs::write(&output_path, &code)
            .map_err(|e| AptosError::Config(format!("Failed to write output file: {e}")))?;

        module_names.push(abi.name);

        if config.print_cargo_instructions {
            println!("cargo:rerun-if-changed={}", abi_path.display());
        }
    }

    // Generate mod.rs
    if config.generate_mod_file && !module_names.is_empty() {
        let mod_content = generate_mod_file(&module_names);
        let mod_path = output_dir.join("mod.rs");

        fs::write(&mod_path, mod_content)
            .map_err(|e| AptosError::Config(format!("Failed to write mod.rs: {e}")))?;
    }

    Ok(())
}

/// Generates Rust code from an ABI file with Move source for better names.
///
/// # Arguments
///
/// * `abi_path` - Path to the ABI JSON file
/// * `source_path` - Path to the Move source file
/// * `output_dir` - Directory where generated code will be written
///
/// # Errors
///
/// Returns an error if:
/// * The ABI file cannot be read
/// * The ABI JSON cannot be parsed
/// * The Move source file cannot be read
/// * Code generation fails
/// * The output directory cannot be created
/// * The output file cannot be written
pub fn generate_from_abi_with_source(
    abi_path: impl AsRef<Path>,
    source_path: impl AsRef<Path>,
    output_dir: impl AsRef<Path>,
) -> AptosResult<()> {
    let abi_path = abi_path.as_ref();
    let source_path = source_path.as_ref();
    let output_dir = output_dir.as_ref();

    // Read and parse ABI
    let abi_content = fs::read_to_string(abi_path)
        .map_err(|e| AptosError::Config(format!("Failed to read ABI file: {e}")))?;

    let abi: MoveModuleABI = serde_json::from_str(&abi_content)
        .map_err(|e| AptosError::Config(format!("Failed to parse ABI JSON: {e}")))?;

    // Read and parse Move source
    let source_content = fs::read_to_string(source_path)
        .map_err(|e| AptosError::Config(format!("Failed to read Move source: {e}")))?;

    let source_info = MoveSourceParser::parse(&source_content);

    // SECURITY: Validate module name to prevent path traversal
    validate_module_name(&abi.name)?;

    // Generate code
    let generator =
        ModuleGenerator::new(&abi, GeneratorConfig::default()).with_source_info(source_info);
    let code = generator.generate()?;

    // Create output directory
    fs::create_dir_all(output_dir)
        .map_err(|e| AptosError::Config(format!("Failed to create output directory: {e}")))?;

    // Write output file
    let output_filename = format!("{}.rs", abi.name);
    let output_path = output_dir.join(&output_filename);

    fs::write(&output_path, &code)
        .map_err(|e| AptosError::Config(format!("Failed to write output file: {e}")))?;

    println!("cargo:rerun-if-changed={}", abi_path.display());
    println!("cargo:rerun-if-changed={}", source_path.display());

    Ok(())
}

/// Generates a mod.rs file for the given module names.
fn generate_mod_file(module_names: &[String]) -> String {
    use std::fmt::Write as _;
    let mut content = String::new();
    let _ = writeln!(&mut content, "//! Auto-generated module exports.");
    let _ = writeln!(&mut content, "//!");
    let _ = writeln!(
        &mut content,
        "//! This file was auto-generated by aptos-sdk codegen."
    );
    let _ = writeln!(&mut content, "//! Do not edit manually.");
    let _ = writeln!(&mut content);

    for name in module_names {
        // SECURITY: Module names are validated by validate_module_name() before reaching here,
        // but double-check they are safe identifiers to prevent code injection in mod.rs
        debug_assert!(
            !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
            "module name should have been validated"
        );
        let _ = writeln!(&mut content, "pub mod {name};");
    }
    let _ = writeln!(&mut content);

    // Re-export all modules
    let _ = writeln!(&mut content, "// Re-exports for convenience");
    for name in module_names {
        let _ = writeln!(&mut content, "pub use {name}::*;");
    }

    content
}

/// Scans a directory for ABI files and generates code for all of them.
///
/// # Arguments
///
/// * `abi_dir` - Directory containing ABI JSON files
/// * `output_dir` - Directory where generated code will be written
///
/// # Errors
///
/// Returns an error if:
/// * The directory cannot be read
/// * No JSON files are found in the directory
/// * Any ABI file cannot be read or parsed
/// * Code generation fails for any module
/// * The output directory cannot be created
/// * Any output file cannot be written
///
/// # Example
///
/// ```rust,ignore
/// build_helper::generate_from_directory("abi/", "src/generated/")?;
/// ```
pub fn generate_from_directory(
    abi_dir: impl AsRef<Path>,
    output_dir: impl AsRef<Path>,
) -> AptosResult<()> {
    let abi_dir = abi_dir.as_ref();

    let entries = fs::read_dir(abi_dir)
        .map_err(|e| AptosError::Config(format!("Failed to read ABI directory: {e}")))?;

    let abi_paths: Vec<_> = entries
        .filter_map(Result::ok)
        .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
        .map(|e| e.path())
        .collect();

    if abi_paths.is_empty() {
        return Err(AptosError::Config(format!(
            "No JSON files found in {}",
            abi_dir.display()
        )));
    }

    // Convert PathBuf to Path references for the function
    let path_refs: Vec<&Path> = abi_paths.iter().map(std::path::PathBuf::as_path).collect();
    generate_from_abis(&path_refs, output_dir)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;

    fn sample_abi_json() -> &'static str {
        r#"{
            "address": "0x1",
            "name": "coin",
            "exposed_functions": [
                {
                    "name": "transfer",
                    "visibility": "public",
                    "is_entry": true,
                    "is_view": false,
                    "generic_type_params": [{"constraints": []}],
                    "params": ["&signer", "address", "u64"],
                    "return": []
                }
            ],
            "structs": []
        }"#
    }

    #[test]
    fn test_generate_from_abi() {
        let temp_dir = TempDir::new().unwrap();
        let abi_path = temp_dir.path().join("coin.json");
        let output_dir = temp_dir.path().join("generated");

        // Write sample ABI
        let mut file = fs::File::create(&abi_path).unwrap();
        file.write_all(sample_abi_json().as_bytes()).unwrap();

        // Generate
        let config = BuildConfig::new().with_cargo_instructions(false);
        generate_from_abi_with_config(&abi_path, &output_dir, config).unwrap();

        // Verify output exists
        let output_path = output_dir.join("coin.rs");
        assert!(output_path.exists());

        // Verify content
        let content = fs::read_to_string(&output_path).unwrap();
        assert!(content.contains("Generated Rust bindings"));
        assert!(content.contains("pub fn transfer"));
    }

    #[test]
    fn test_generate_mod_file() {
        let modules = vec!["coin".to_string(), "token".to_string()];
        let mod_content = generate_mod_file(&modules);

        assert!(mod_content.contains("pub mod coin;"));
        assert!(mod_content.contains("pub mod token;"));
        assert!(mod_content.contains("pub use coin::*;"));
        assert!(mod_content.contains("pub use token::*;"));
    }

    #[test]
    fn test_build_config() {
        let config = BuildConfig::new()
            .with_mod_file(false)
            .with_cargo_instructions(false);

        assert!(!config.generate_mod_file);
        assert!(!config.print_cargo_instructions);
    }
}