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
//! Type mapping between Move and Rust types.

use std::collections::HashMap;

/// A Rust type representation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RustType {
    /// The full type path (e.g., "`Vec<u8>`", "`AccountAddress`").
    pub path: String,
    /// Whether this type requires BCS serialization as an argument.
    pub needs_bcs: bool,
    /// Whether this type is a reference.
    pub is_ref: bool,
    /// Documentation for this type.
    pub doc: Option<String>,
}

impl RustType {
    /// Creates a new Rust type.
    #[must_use]
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            needs_bcs: true,
            is_ref: false,
            doc: None,
        }
    }

    /// Creates a type that doesn't need BCS serialization.
    #[must_use]
    pub fn primitive(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            needs_bcs: false,
            is_ref: false,
            doc: None,
        }
    }

    /// Creates a reference type.
    #[must_use]
    pub fn reference(mut self) -> Self {
        self.is_ref = true;
        self
    }

    /// Adds documentation.
    #[must_use]
    pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
        self.doc = Some(doc.into());
        self
    }

    /// Returns the type as a function argument type.
    pub fn as_arg_type(&self) -> String {
        if self.is_ref {
            format!("&{}", self.path)
        } else {
            self.path.clone()
        }
    }

    /// Returns the type as a return type.
    pub fn as_return_type(&self) -> String {
        self.path.clone()
    }
}

/// Maps Move types to Rust types.
#[derive(Debug, Clone)]
pub struct MoveTypeMapper {
    /// Custom type mappings.
    custom_mappings: HashMap<String, RustType>,
}

impl Default for MoveTypeMapper {
    fn default() -> Self {
        Self::new()
    }
}

impl MoveTypeMapper {
    /// Creates a new type mapper with default mappings.
    pub fn new() -> Self {
        Self {
            custom_mappings: HashMap::new(),
        }
    }

    /// Adds a custom type mapping.
    pub fn add_mapping(&mut self, move_type: impl Into<String>, rust_type: RustType) {
        self.custom_mappings.insert(move_type.into(), rust_type);
    }

    /// Maps a Move type string to a Rust type.
    pub fn map_type(&self, move_type: &str) -> RustType {
        // Check custom mappings first
        if let Some(rust_type) = self.custom_mappings.get(move_type) {
            return rust_type.clone();
        }

        // Handle primitive types
        match move_type {
            "bool" => RustType::primitive("bool"),
            "u8" => RustType::primitive("u8"),
            "u16" => RustType::primitive("u16"),
            "u32" => RustType::primitive("u32"),
            "u64" => RustType::primitive("u64"),
            "u128" => RustType::primitive("u128"),
            "u256" => RustType::new("U256"),
            "address" => RustType::new("AccountAddress"),
            "signer" | "&signer" => RustType::new("AccountAddress")
                .with_doc("Signer address (automatically set to sender)"),
            _ => self.map_complex_type(move_type),
        }
    }

    /// Maps complex Move types (vectors, structs, etc.)
    fn map_complex_type(&self, move_type: &str) -> RustType {
        // Handle vector types
        if move_type.starts_with("vector<") && move_type.ends_with('>') {
            let inner = &move_type[7..move_type.len() - 1];
            let inner_type = self.map_type(inner);

            // Special case: `vector<u8>` -> `Vec<u8>` (bytes)
            if inner == "u8" {
                return RustType::new("Vec<u8>").with_doc("Bytes");
            }

            return RustType::new(format!("Vec<{}>", inner_type.path));
        }

        // Handle Option types (0x1::option::Option<T>)
        if move_type.contains("::option::Option<")
            && let Some(start) = move_type.find("Option<")
        {
            let rest = &move_type[start + 7..];
            if let Some(end) = rest.rfind('>') {
                let inner = &rest[..end];
                let inner_type = self.map_type(inner);
                return RustType::new(format!("Option<{}>", inner_type.path));
            }
        }

        // Handle String type
        if move_type == "0x1::string::String" || move_type.ends_with("::string::String") {
            return RustType::new("String");
        }

        // Handle Object types
        if move_type.contains("::object::Object<") {
            return RustType::new("AccountAddress").with_doc("Object address");
        }

        // Handle generic struct types (e.g., 0x1::coin::Coin<0x1::aptos_coin::AptosCoin>)
        if move_type.contains("::") {
            // Use rsplit to avoid collecting into Vec - we only need the last part
            let part_count = move_type.matches("::").count() + 1;
            if part_count >= 3 {
                // Get the base struct name (without generics) using rsplit
                if let Some(struct_name) = move_type.rsplit("::").next() {
                    let base_name = struct_name.split('<').next().unwrap_or(struct_name);

                    // Create a pascal case name
                    let rust_name = to_pascal_case(base_name);
                    return RustType::new(rust_name).with_doc(format!("Move type: {move_type}"));
                }
            }
        }

        // Default: use serde_json::Value for unknown types
        RustType::new("serde_json::Value").with_doc(format!("Unknown Move type: {move_type}"))
    }

    /// Maps a Move type to a BCS argument encoding expression.
    pub fn to_bcs_arg(&self, move_type: &str, var_name: &str) -> String {
        let rust_type = self.map_type(move_type);

        if !rust_type.needs_bcs {
            // Primitives that don't need special handling
            return format!(
                "aptos_bcs::to_bytes(&{var_name}).map_err(|e| AptosError::Bcs(e.to_string()))?"
            );
        }

        // SECURITY: Use error propagation instead of .unwrap() to prevent
        // panics in generated code if BCS serialization fails.
        format!("aptos_bcs::to_bytes(&{var_name}).map_err(|e| AptosError::Bcs(e.to_string()))?")
    }

    /// Determines if a parameter should be excluded from the function signature.
    /// (e.g., &signer is always the sender)
    pub fn is_signer_param(&self, move_type: &str) -> bool {
        move_type == "&signer" || move_type == "signer"
    }
}

/// Converts a `snake_case` or other string to `PascalCase`.
pub fn to_pascal_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c == '_' || c == '-' || c == ' ' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    result
}

/// Converts a `PascalCase` or other string to `snake_case`.
pub fn to_snake_case(s: &str) -> String {
    let mut result = String::new();

    for (i, c) in s.chars().enumerate() {
        if c.is_ascii_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_ascii_lowercase());
        } else {
            result.push(c);
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_primitive_mapping() {
        let mapper = MoveTypeMapper::new();

        assert_eq!(mapper.map_type("bool").path, "bool");
        assert_eq!(mapper.map_type("u8").path, "u8");
        assert_eq!(mapper.map_type("u64").path, "u64");
        assert_eq!(mapper.map_type("u128").path, "u128");
        assert_eq!(mapper.map_type("address").path, "AccountAddress");
    }

    #[test]
    fn test_vector_mapping() {
        let mapper = MoveTypeMapper::new();

        assert_eq!(mapper.map_type("vector<u8>").path, "Vec<u8>");
        assert_eq!(
            mapper.map_type("vector<address>").path,
            "Vec<AccountAddress>"
        );
        assert_eq!(mapper.map_type("vector<u64>").path, "Vec<u64>");
    }

    #[test]
    fn test_string_mapping() {
        let mapper = MoveTypeMapper::new();

        assert_eq!(mapper.map_type("0x1::string::String").path, "String");
    }

    #[test]
    fn test_to_pascal_case() {
        assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
        assert_eq!(to_pascal_case("coin"), "Coin");
        assert_eq!(to_pascal_case("aptos_coin"), "AptosCoin");
    }

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("HelloWorld"), "hello_world");
        assert_eq!(to_snake_case("Coin"), "coin");
        assert_eq!(to_snake_case("AptosCoin"), "aptos_coin");
    }

    #[test]
    fn test_rust_type_new() {
        let rt = RustType::new("MyType");
        assert_eq!(rt.path, "MyType");
        assert!(rt.needs_bcs);
        assert!(!rt.is_ref);
        assert!(rt.doc.is_none());
    }

    #[test]
    fn test_rust_type_primitive() {
        let rt = RustType::primitive("u64");
        assert_eq!(rt.path, "u64");
        assert!(!rt.needs_bcs);
    }

    #[test]
    fn test_rust_type_reference() {
        let rt = RustType::new("MyType").reference();
        assert!(rt.is_ref);
        assert_eq!(rt.as_arg_type(), "&MyType");
    }

    #[test]
    fn test_rust_type_with_doc() {
        let rt = RustType::new("MyType").with_doc("My documentation");
        assert_eq!(rt.doc, Some("My documentation".to_string()));
    }

    #[test]
    fn test_rust_type_as_return_type() {
        let rt = RustType::new("MyType").reference();
        assert_eq!(rt.as_return_type(), "MyType"); // References don't affect return type
    }

    #[test]
    fn test_mapper_default() {
        let mapper = MoveTypeMapper::default();
        assert_eq!(mapper.map_type("bool").path, "bool");
    }

    #[test]
    fn test_mapper_custom_mapping() {
        let mut mapper = MoveTypeMapper::new();
        mapper.add_mapping("MyCustomType", RustType::new("CustomRustType"));
        assert_eq!(mapper.map_type("MyCustomType").path, "CustomRustType");
    }

    #[test]
    fn test_mapper_u256() {
        let mapper = MoveTypeMapper::new();
        assert_eq!(mapper.map_type("u256").path, "U256");
    }

    #[test]
    fn test_mapper_signer() {
        let mapper = MoveTypeMapper::new();
        assert_eq!(mapper.map_type("&signer").path, "AccountAddress");
        assert_eq!(mapper.map_type("signer").path, "AccountAddress");
    }

    #[test]
    fn test_mapper_nested_vector() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.map_type("vector<vector<u8>>");
        assert_eq!(result.path, "Vec<Vec<u8>>");
    }

    #[test]
    fn test_mapper_option_type() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.map_type("0x1::option::Option<u64>");
        assert_eq!(result.path, "Option<u64>");
    }

    #[test]
    fn test_mapper_object_type() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.map_type("0x1::object::Object<Token>");
        assert_eq!(result.path, "AccountAddress");
    }

    #[test]
    fn test_mapper_unknown_struct() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.map_type("0x1::module::SomeStruct");
        assert!(result.doc.is_some());
    }

    #[test]
    fn test_mapper_unknown_type() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.map_type("some_completely_unknown_thing");
        assert_eq!(result.path, "serde_json::Value");
    }

    #[test]
    fn test_to_bcs_arg_address() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.to_bcs_arg("address", "my_addr");
        assert!(result.contains("aptos_bcs::to_bytes"));
        assert!(result.contains("my_addr"));
    }

    #[test]
    fn test_to_bcs_arg_vector_u8() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.to_bcs_arg("vector<u8>", "my_bytes");
        assert!(result.contains("aptos_bcs::to_bytes"));
    }

    #[test]
    fn test_to_bcs_arg_vector_other() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.to_bcs_arg("vector<u64>", "my_vec");
        assert!(result.contains("aptos_bcs::to_bytes"));
    }

    #[test]
    fn test_to_bcs_arg_string() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.to_bcs_arg("0x1::string::String", "my_string");
        assert!(result.contains("aptos_bcs::to_bytes"));
    }

    #[test]
    fn test_to_bcs_arg_other_string() {
        let mapper = MoveTypeMapper::new();
        let result = mapper.to_bcs_arg("0xabc::my_module::string::String", "s");
        assert!(result.contains("aptos_bcs::to_bytes"));
    }

    #[test]
    fn test_is_signer_param() {
        let mapper = MoveTypeMapper::new();
        assert!(mapper.is_signer_param("&signer"));
        assert!(mapper.is_signer_param("signer"));
        assert!(!mapper.is_signer_param("address"));
        assert!(!mapper.is_signer_param("u64"));
    }

    #[test]
    fn test_to_pascal_case_with_spaces() {
        assert_eq!(to_pascal_case("hello world"), "HelloWorld");
    }

    #[test]
    fn test_to_pascal_case_with_dashes() {
        assert_eq!(to_pascal_case("hello-world"), "HelloWorld");
    }

    #[test]
    fn test_to_snake_case_single_word() {
        assert_eq!(to_snake_case("hello"), "hello");
    }

    #[test]
    fn test_to_snake_case_already_lowercase() {
        assert_eq!(to_snake_case("helloworld"), "helloworld");
    }
}