-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcodegen.rs
More file actions
300 lines (278 loc) · 9.62 KB
/
Copy pathcodegen.rs
File metadata and controls
300 lines (278 loc) · 9.62 KB
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
//! Example: Generate Rust bindings from Move module ABI
//!
//! This example demonstrates how to use the code generation feature to create
//! type-safe Rust bindings from Move module ABIs.
//!
//! # Run with:
//! ```bash
//! cargo run --example codegen --features ed25519
//! ```
use aptos_sdk::{
api::response::{MoveFunction, MoveModuleABI, MoveStructDef, MoveStructField},
codegen::{GeneratorConfig, ModuleGenerator, MoveSourceParser},
};
fn main() -> anyhow::Result<()> {
// ANCHOR: create_abi
// In practice, you would load this from a JSON file or fetch from chain
let abi = MoveModuleABI {
address: "0xcafe".to_string(),
name: "my_token".to_string(),
exposed_functions: vec![
// An entry function for minting tokens
MoveFunction {
name: "mint".to_string(),
visibility: "public".to_string(),
is_entry: true,
is_view: false,
generic_type_params: vec![],
params: vec![
"&signer".to_string(),
"address".to_string(),
"u64".to_string(),
],
returns: vec![],
},
// An entry function for transferring tokens
MoveFunction {
name: "transfer".to_string(),
visibility: "public".to_string(),
is_entry: true,
is_view: false,
generic_type_params: vec![],
params: vec![
"&signer".to_string(),
"address".to_string(),
"u64".to_string(),
],
returns: vec![],
},
// A view function for getting balance
MoveFunction {
name: "balance".to_string(),
visibility: "public".to_string(),
is_entry: false,
is_view: true,
generic_type_params: vec![],
params: vec!["address".to_string()],
returns: vec!["u64".to_string()],
},
// A view function for getting total supply
MoveFunction {
name: "total_supply".to_string(),
visibility: "public".to_string(),
is_entry: false,
is_view: true,
generic_type_params: vec![],
params: vec![],
returns: vec!["u64".to_string()],
},
],
structs: vec![
MoveStructDef {
name: "TokenStore".to_string(),
is_native: false,
abilities: vec!["key".to_string()],
generic_type_params: vec![],
fields: vec![
MoveStructField {
name: "balance".to_string(),
typ: "u64".to_string(),
},
MoveStructField {
name: "owner".to_string(),
typ: "address".to_string(),
},
],
},
MoveStructDef {
name: "TokenInfo".to_string(),
is_native: false,
abilities: vec!["key".to_string()],
generic_type_params: vec![],
fields: vec![
MoveStructField {
name: "name".to_string(),
typ: "0x1::string::String".to_string(),
},
MoveStructField {
name: "symbol".to_string(),
typ: "0x1::string::String".to_string(),
},
MoveStructField {
name: "decimals".to_string(),
typ: "u8".to_string(),
},
MoveStructField {
name: "total_supply".to_string(),
typ: "u64".to_string(),
},
],
},
],
};
// ANCHOR_END: create_abi
// ANCHOR: move_source
// Move source provides parameter names and documentation
let move_source = r"
/// A token management module.
///
/// This module provides functionality for minting, transferring,
/// and querying token balances.
module 0xcafe::my_token {
use std::string::String;
/// Stores token balance for an account.
struct TokenStore has key {
/// The current balance.
balance: u64,
/// The account that owns this store.
owner: address,
}
/// Metadata about the token.
struct TokenInfo has key {
/// The human-readable name.
name: String,
/// The ticker symbol.
symbol: String,
/// Number of decimal places.
decimals: u8,
/// Total tokens in circulation.
total_supply: u64,
}
/// Mints new tokens to a recipient.
///
/// Only the admin can call this function.
///
/// # Arguments
/// * `admin` - The admin account authorized to mint
/// * `recipient` - The address to receive the minted tokens
/// * `amount` - The number of tokens to mint
public entry fun mint(
admin: &signer,
recipient: address,
amount: u64,
) {
// implementation
}
/// Transfers tokens from the sender to a recipient.
///
/// # Arguments
/// * `sender` - The account sending tokens
/// * `to` - The address to receive tokens
/// * `amount` - The number of tokens to transfer
public entry fun transfer(
sender: &signer,
to: address,
amount: u64,
) {
// implementation
}
/// Gets the token balance for an account.
///
/// Returns 0 if the account has no TokenStore.
#[view]
public fun balance(owner: address): u64 {
0
}
/// Gets the total supply of tokens.
#[view]
public fun total_supply(): u64 {
0
}
}
";
// Parse the Move source
let source_info = MoveSourceParser::parse(move_source);
println!("Parsed Move source:");
println!(
" - Functions: {:?}",
source_info.functions.keys().collect::<Vec<_>>()
);
println!(
" - Structs: {:?}",
source_info.structs.keys().collect::<Vec<_>>()
);
// ANCHOR_END: move_source
// ANCHOR: generate_without_source
// Generate without source info (uses generic names)
println!("\n=== Generated WITHOUT Move Source ===\n");
let config = GeneratorConfig::new()
.with_entry_functions(true)
.with_view_functions(true)
.with_structs(false); // Skip structs for brevity
let generator = ModuleGenerator::new(&abi, config.clone());
let code_without_source = generator.generate()?;
// Show just the transfer function
for line in code_without_source.lines() {
if line.contains("pub fn transfer")
|| line.contains("/// Entry function: `my_token::transfer`")
{
println!("{line}");
}
}
// ANCHOR_END: generate_without_source
// ANCHOR: generate_with_source
// Generate WITH source info (uses real parameter names and docs)
println!("\n=== Generated WITH Move Source ===\n");
let generator_with_source = ModuleGenerator::new(&abi, config).with_source_info(source_info);
let code_with_source = generator_with_source.generate()?;
// Show the transfer function with proper names
let mut in_transfer = false;
for line in code_with_source.lines() {
if line.contains("/// Transfers tokens") {
in_transfer = true;
}
if in_transfer {
println!("{line}");
if line.starts_with("pub fn transfer") {
break;
}
}
}
// ANCHOR_END: generate_with_source
println!("\n=== Full Generated Code (with source) ===\n");
// Generate full code with structs
let full_config = GeneratorConfig::new()
.with_entry_functions(true)
.with_view_functions(true)
.with_structs(true);
let full_source_info = MoveSourceParser::parse(move_source);
let full_generator = ModuleGenerator::new(&abi, full_config).with_source_info(full_source_info);
let full_code = full_generator.generate()?;
println!("{full_code}");
// ANCHOR: usage_example
// The generated code can be used like this:
//
// ```rust
// // Import the generated module
// mod my_token;
//
// use aptos_sdk::{Aptos, AptosConfig};
// use my_token::*;
//
// async fn example() -> anyhow::Result<()> {
// let aptos = Aptos::new(AptosConfig::devnet())?;
// let account = aptos.account().create_ed25519()?;
//
// // Use generated entry function with meaningful parameter names
// let payload = mint(recipient_address, 1000)?;
// aptos.sign_submit_and_wait(&account, payload, None).await?;
//
// // Use generated view function with proper parameter name
// let balance = view_balance(&aptos, owner_address).await?;
// println!("Balance: {:?}", balance);
//
// Ok(())
// }
// ```
// ANCHOR_END: usage_example
println!("\n=== CLI Usage ===\n");
println!("# Generate from ABI file only:");
println!("aptos-codegen --input abi.json --output src/generated/");
println!();
println!("# Generate with Move source for better names:");
println!("aptos-codegen --input abi.json --source my_token.move --output src/generated/");
println!();
println!("# Fetch from chain and generate:");
println!("aptos-codegen --module 0x1::coin --network testnet --output src/generated/");
Ok(())
}