miden_lib/utils/
script_builder.rs

1use alloc::string::String;
2use alloc::sync::Arc;
3
4use miden_objects::assembly::diagnostics::NamedSource;
5use miden_objects::assembly::{
6    Assembler,
7    DefaultSourceManager,
8    Library,
9    LibraryPath,
10    SourceManagerSync,
11};
12use miden_objects::note::NoteScript;
13use miden_objects::transaction::TransactionScript;
14
15use crate::errors::ScriptBuilderError;
16use crate::transaction::TransactionKernel;
17
18// SCRIPT BUILDER
19// ================================================================================================
20
21/// A builder for compiling note scripts and transaction scripts with optional library dependencies.
22///
23/// The ScriptBuilder simplifies the process of creating transaction scripts by providing:
24/// - A clean API for adding multiple libraries with static or dynamic linking
25/// - Automatic assembler configuration with all added libraries
26/// - Debug mode support
27/// - Builder pattern support for method chaining
28///
29/// ## Static vs Dynamic Linking
30///
31/// **Static Linking** (`link_static_library()` / `with_statically_linked_library()`):
32/// - Use when you control and know the library code
33/// - The library code is copied into the script code
34/// - Best for most user-written libraries and dependencies
35/// - Results in larger script size but ensures the code is always available
36///
37/// **Dynamic Linking** (`link_dynamic_library()` / `with_dynamically_linked_library()`):
38/// - Use when making Foreign Procedure Invocation (FPI) calls
39/// - The library code is available on-chain and referenced, not copied
40/// - Results in smaller script size but requires the code to be available on-chain
41///
42/// ## Typical Workflow
43///
44/// 1. Create a new ScriptBuilder with debug mode preference
45/// 2. Add any required modules using `link_module()` or `with_linked_module()`
46/// 3. Add libraries using `link_static_library()` / `link_dynamic_library()` as appropriate
47/// 4. Compile your script with `compile_note_script()` or `compile_tx_script()`
48///
49/// Note that the compilation methods consume the ScriptBuilder, so if you need to compile
50/// multiple scripts with the same configuration, you should clone the builder first.
51///
52/// ## Builder Pattern Example
53///
54/// ```no_run
55/// # use anyhow::Context;
56/// # use miden_lib::utils::ScriptBuilder;
57/// # use miden_objects::assembly::Library;
58/// # use miden_stdlib::StdLibrary;
59/// # fn example() -> anyhow::Result<()> {
60/// # let module_code = "export.test push.1 add end";
61/// # let script_code = "begin nop end";
62/// # // Create sample libraries for the example
63/// # let my_lib = StdLibrary::default().into(); // Convert StdLibrary to Library
64/// # let fpi_lib = StdLibrary::default().into();
65/// let script = ScriptBuilder::default()
66///     .with_linked_module("my::module", module_code).context("failed to link module")?
67///     .with_statically_linked_library(&my_lib).context("failed to link static library")?
68///     .with_dynamically_linked_library(&fpi_lib).context("failed to link dynamic library")?  // For FPI calls
69///     .compile_tx_script(script_code).context("failed to compile tx script")?;
70/// # Ok(())
71/// # }
72/// ```
73///
74/// # Note
75/// The ScriptBuilder automatically includes the `miden` and `std` libraries, which
76/// provide access to transaction kernel procedures. Due to being available on-chain
77/// these libraries are linked dynamically and do not add to the size of built script.
78#[derive(Clone)]
79pub struct ScriptBuilder {
80    assembler: Assembler,
81    source_manager: Arc<dyn SourceManagerSync>,
82}
83
84impl ScriptBuilder {
85    // CONSTRUCTORS
86    // --------------------------------------------------------------------------------------------
87
88    /// Creates a new ScriptBuilder with the specified debug mode.
89    ///
90    /// # Arguments
91    /// * `in_debug_mode` - Whether to enable debug mode in the assembler
92    pub fn new(in_debug_mode: bool) -> Self {
93        let source_manager = Arc::new(DefaultSourceManager::default());
94        let assembler = TransactionKernel::assembler_with_source_manager(source_manager.clone())
95            .with_debug_mode(in_debug_mode);
96        Self { assembler, source_manager }
97    }
98
99    /// Creates a new ScriptBuilder with the specified source manager.
100    ///
101    /// The returned builder is instantiated with debug mode enabled.
102    ///
103    /// # Arguments
104    /// * `source_manager` - The source manager to use with the internal `Assembler`
105    pub fn with_source_manager(source_manager: Arc<dyn SourceManagerSync>) -> Self {
106        let assembler = TransactionKernel::assembler_with_source_manager(source_manager.clone())
107            .with_debug_mode(true);
108        Self { assembler, source_manager }
109    }
110
111    // LIBRARY MANAGEMENT
112    // --------------------------------------------------------------------------------------------
113
114    /// Compiles and links a module to the script builder.
115    ///
116    /// This method compiles the provided module code and adds it directly to the assembler
117    /// for use in script compilation.
118    ///
119    /// # Arguments
120    /// * `module_path` - The path identifier for the module (e.g., "my_lib::my_module")
121    /// * `module_code` - The source code of the module to compile and link
122    ///
123    /// # Errors
124    /// Returns an error if:
125    /// - The module path is invalid
126    /// - The module code cannot be parsed
127    /// - The module cannot be assembled
128    pub fn link_module(
129        &mut self,
130        module_path: impl AsRef<str>,
131        module_code: impl AsRef<str>,
132    ) -> Result<(), ScriptBuilderError> {
133        // Parse the library path
134        let lib_path = LibraryPath::new(module_path.as_ref()).map_err(|err| {
135            ScriptBuilderError::build_error_with_source(
136                format!("invalid module path: {}", module_path.as_ref()),
137                err,
138            )
139        })?;
140
141        let module = NamedSource::new(format!("{lib_path}"), String::from(module_code.as_ref()));
142
143        self.assembler.compile_and_statically_link(module).map_err(|err| {
144            ScriptBuilderError::build_error_with_report("failed to assemble module", err)
145        })?;
146
147        Ok(())
148    }
149
150    /// Statically links the given library.
151    ///
152    /// Static linking means the library code is copied into the script code.
153    /// Use this for most libraries that are not available on-chain.
154    ///
155    /// # Arguments
156    /// * `library` - The compiled library to statically link
157    ///
158    /// # Errors
159    /// Returns an error if:
160    /// - adding the library to the assembler failed
161    pub fn link_static_library(&mut self, library: &Library) -> Result<(), ScriptBuilderError> {
162        self.assembler.link_static_library(library).map_err(|err| {
163            ScriptBuilderError::build_error_with_report("failed to add static library", err)
164        })
165    }
166
167    /// Dynamically links a library.
168    ///
169    /// This is useful to dynamically link the [`Library`] of a foreign account
170    /// that is invoked using foreign procedure invocation (FPI). Its code is available
171    /// on-chain and so it does not have to be copied into the script code.
172    ///
173    /// For all other use cases not involving FPI, link the library statically.
174    ///
175    /// # Arguments
176    /// * `library` - The compiled library to dynamically link
177    ///
178    /// # Errors
179    /// Returns an error if the library cannot be added to the assembler
180    pub fn link_dynamic_library(&mut self, library: &Library) -> Result<(), ScriptBuilderError> {
181        self.assembler.link_dynamic_library(library).map_err(|err| {
182            ScriptBuilderError::build_error_with_report("failed to add dynamic library", err)
183        })
184    }
185
186    /// Builder-style method to statically link a library and return the modified builder.
187    ///
188    /// This enables method chaining for convenient builder patterns.
189    ///
190    /// # Arguments
191    /// * `library` - The compiled library to statically link
192    ///
193    /// # Errors
194    /// Returns an error if the library cannot be added to the assembler
195    pub fn with_statically_linked_library(
196        mut self,
197        library: &Library,
198    ) -> Result<Self, ScriptBuilderError> {
199        self.link_static_library(library)?;
200        Ok(self)
201    }
202
203    /// Builder-style method to dynamically link a library and return the modified builder.
204    ///
205    /// This enables method chaining for convenient builder patterns.
206    ///
207    /// # Arguments
208    /// * `library` - The compiled library to dynamically link
209    ///
210    /// # Errors
211    /// Returns an error if the library cannot be added to the assembler
212    pub fn with_dynamically_linked_library(
213        mut self,
214        library: &Library,
215    ) -> Result<Self, ScriptBuilderError> {
216        self.link_dynamic_library(library)?;
217        Ok(self)
218    }
219
220    /// Builder-style method to link a module and return the modified builder.
221    ///
222    /// This enables method chaining for convenient builder patterns.
223    ///
224    /// # Arguments
225    /// * `module_path` - The path identifier for the module (e.g., "my_lib::my_module")
226    /// * `module_code` - The source code of the module to compile and link
227    ///
228    /// # Errors
229    /// Returns an error if the module cannot be compiled or added to the assembler
230    pub fn with_linked_module(
231        mut self,
232        module_path: impl AsRef<str>,
233        module_code: impl AsRef<str>,
234    ) -> Result<Self, ScriptBuilderError> {
235        self.link_module(module_path, module_code)?;
236        Ok(self)
237    }
238
239    // SCRIPT COMPILATION
240    // --------------------------------------------------------------------------------------------
241
242    /// Compiles a transaction script with the provided program code.
243    ///
244    /// The compiled script will have access to all modules that have been added to this builder.
245    ///
246    /// # Arguments
247    /// * `program` - The transaction script source code
248    ///
249    /// # Errors
250    /// Returns an error if:
251    /// - The transaction script compilation fails
252    pub fn compile_tx_script(
253        self,
254        tx_script: impl AsRef<str>,
255    ) -> Result<TransactionScript, ScriptBuilderError> {
256        let assembler = self.assembler;
257
258        let program = assembler.assemble_program(tx_script.as_ref()).map_err(|err| {
259            ScriptBuilderError::build_error_with_report("failed to compile transaction script", err)
260        })?;
261        Ok(TransactionScript::new(program))
262    }
263
264    /// Compiles a note script with the provided program code.
265    ///
266    /// The compiled script will have access to all modules that have been added to this builder.
267    ///
268    /// # Arguments
269    /// * `program` - The note script source code
270    ///
271    /// # Errors
272    /// Returns an error if:
273    /// - The note script compilation fails
274    pub fn compile_note_script(
275        self,
276        program: impl AsRef<str>,
277    ) -> Result<NoteScript, ScriptBuilderError> {
278        let assembler = self.assembler;
279
280        let program = assembler.assemble_program(program.as_ref()).map_err(|err| {
281            ScriptBuilderError::build_error_with_report("failed to compile note script", err)
282        })?;
283        Ok(NoteScript::new(program))
284    }
285
286    // ACCESSORS
287    // --------------------------------------------------------------------------------------------
288
289    /// Access the [`Assembler`]'s [`SourceManagerSync`].
290    pub fn source_manager(&self) -> Arc<dyn SourceManagerSync> {
291        self.source_manager.clone()
292    }
293
294    // TESTING CONVENIENCE FUNCTIONS
295    // --------------------------------------------------------------------------------------------
296
297    /// Returns a [`ScriptBuilder`] with the mock account and faucet libraries.
298    ///
299    /// This script builder includes the [`MockAccountCodeExt::mock_account_library`][account_lib]
300    /// and [`MockAccountCodeExt::mock_faucet_library`][faucet_lib], which are the standard
301    /// testing account libraries.
302    ///
303    /// [account_lib]: crate::testing::mock_account_code::MockAccountCodeExt::mock_account_library
304    /// [faucet_lib]: crate::testing::mock_account_code::MockAccountCodeExt::mock_faucet_library
305    #[cfg(any(feature = "testing", test))]
306    pub fn with_mock_libraries() -> Result<Self, ScriptBuilderError> {
307        use miden_objects::account::AccountCode;
308
309        use crate::testing::mock_account_code::MockAccountCodeExt;
310
311        Self::new(true)
312            .with_dynamically_linked_library(&AccountCode::mock_account_library())?
313            .with_dynamically_linked_library(&AccountCode::mock_faucet_library())
314    }
315}
316
317impl Default for ScriptBuilder {
318    fn default() -> Self {
319        Self::new(true)
320    }
321}
322
323// TESTS
324// ================================================================================================
325
326#[cfg(test)]
327mod tests {
328    use anyhow::Context;
329
330    use super::*;
331
332    #[test]
333    fn test_script_builder_new() {
334        let _builder = ScriptBuilder::default();
335        // Test that the builder can be created successfully
336    }
337
338    #[test]
339    fn test_script_builder_basic_script_compilation() -> anyhow::Result<()> {
340        let builder = ScriptBuilder::default();
341        builder
342            .compile_tx_script("begin nop end")
343            .context("failed to compile basic tx script")?;
344        Ok(())
345    }
346
347    #[test]
348    fn test_create_library_and_create_tx_script() -> anyhow::Result<()> {
349        let script_code = "
350            use.external_contract::counter_contract
351            begin
352                call.counter_contract::increment
353            end
354        ";
355
356        let account_code = "
357            use.miden::account
358            use.std::sys
359            export.increment
360                push.0
361                exec.account::get_item
362                push.1 add
363                push.0
364                exec.account::set_item
365                exec.sys::truncate_stack
366            end
367        ";
368
369        let library_path = "external_contract::counter_contract";
370
371        let mut builder_with_lib = ScriptBuilder::default();
372        builder_with_lib
373            .link_module(library_path, account_code)
374            .context("failed to link module")?;
375        builder_with_lib
376            .compile_tx_script(script_code)
377            .context("failed to compile tx script")?;
378
379        Ok(())
380    }
381
382    #[test]
383    fn test_compile_library_and_add_to_builder() -> anyhow::Result<()> {
384        let script_code = "
385            use.external_contract::counter_contract
386            begin
387                call.counter_contract::increment
388            end
389        ";
390
391        let account_code = "
392            use.miden::account
393            use.std::sys
394            export.increment
395                push.0
396                exec.account::get_item
397                push.1 add
398                push.0
399                exec.account::set_item
400                exec.sys::truncate_stack
401            end
402        ";
403
404        let library_path = "external_contract::counter_contract";
405
406        // Test single library
407        let mut builder_with_lib = ScriptBuilder::default();
408        builder_with_lib
409            .link_module(library_path, account_code)
410            .context("failed to link module")?;
411        builder_with_lib
412            .compile_tx_script(script_code)
413            .context("failed to compile tx script")?;
414
415        // Test multiple libraries
416        let mut builder_with_libs = ScriptBuilder::default();
417        builder_with_libs
418            .link_module(library_path, account_code)
419            .context("failed to link first module")?;
420        builder_with_libs
421            .link_module("test::lib", "export.test nop end")
422            .context("failed to link second module")?;
423        builder_with_libs
424            .compile_tx_script(script_code)
425            .context("failed to compile tx script with multiple libraries")?;
426
427        Ok(())
428    }
429
430    #[test]
431    fn test_builder_style_chaining() -> anyhow::Result<()> {
432        let script_code = "
433            use.external_contract::counter_contract
434            begin
435                call.counter_contract::increment
436            end
437        ";
438
439        let account_code = "
440            use.miden::account
441            use.std::sys
442            export.increment
443                push.0
444                exec.account::get_item
445                push.1 add
446                push.0
447                exec.account::set_item
448                exec.sys::truncate_stack
449            end
450        ";
451
452        // Test builder-style chaining with modules
453        let builder = ScriptBuilder::default()
454            .with_linked_module("external_contract::counter_contract", account_code)
455            .context("failed to link module")?;
456
457        builder.compile_tx_script(script_code).context("failed to compile tx script")?;
458
459        Ok(())
460    }
461
462    #[test]
463    fn test_multiple_chained_modules() -> anyhow::Result<()> {
464        let script_code =
465            "use.test::lib1 use.test::lib2 begin exec.lib1::test1 exec.lib2::test2 end";
466
467        // Test chaining multiple modules
468        let builder = ScriptBuilder::default()
469            .with_linked_module("test::lib1", "export.test1 push.1 add end")
470            .context("failed to link first module")?
471            .with_linked_module("test::lib2", "export.test2 push.2 add end")
472            .context("failed to link second module")?;
473
474        builder.compile_tx_script(script_code).context("failed to compile tx script")?;
475
476        Ok(())
477    }
478
479    #[test]
480    fn test_static_and_dynamic_linking() -> anyhow::Result<()> {
481        let script_code = "
482            use.external_contract::contract_1
483            use.external_contract::contract_2
484
485            begin
486                call.contract_1::increment_1
487                call.contract_2::increment_2
488            end
489        ";
490
491        let account_code_1 = "
492            use.miden::account
493            use.std::sys
494            export.increment_1
495                push.0
496                exec.account::get_item
497                push.1 add
498                push.0
499                exec.account::set_item
500                exec.sys::truncate_stack
501            end
502        ";
503
504        let account_code_2 = "
505            use.miden::account
506            use.std::sys
507            export.increment_2
508                push.0
509                exec.account::get_item
510                push.2 add
511                push.0
512                exec.account::set_item
513                exec.sys::truncate_stack
514            end
515        ";
516
517        // Create libraries using the assembler
518        let temp_assembler = TransactionKernel::assembler();
519
520        let static_lib = temp_assembler
521            .clone()
522            .assemble_library([NamedSource::new("external_contract::contract_1", account_code_1)])
523            .map_err(|e| anyhow::anyhow!("failed to assemble static library: {}", e))?;
524
525        let dynamic_lib = temp_assembler
526            .assemble_library([NamedSource::new("external_contract::contract_2", account_code_2)])
527            .map_err(|e| anyhow::anyhow!("failed to assemble dynamic library: {}", e))?;
528
529        // Test linking both static and dynamic libraries
530        let builder = ScriptBuilder::default()
531            .with_statically_linked_library(&static_lib)
532            .context("failed to link static library")?
533            .with_dynamically_linked_library(&dynamic_lib)
534            .context("failed to link dynamic library")?;
535
536        builder
537            .compile_tx_script(script_code)
538            .context("failed to compile tx script with static and dynamic libraries")?;
539
540        Ok(())
541    }
542}