initial commit
This commit is contained in:
305
core/engine/src/lib.rs
Normal file
305
core/engine/src/lib.rs
Normal file
@@ -0,0 +1,305 @@
|
||||
//! # Rhailib Engine
|
||||
//!
|
||||
//! The central Rhai scripting engine for the heromodels ecosystem. This crate provides
|
||||
//! a unified interface for creating, configuring, and executing Rhai scripts with access
|
||||
//! to all business domain modules.
|
||||
//!
|
||||
//! ## Features
|
||||
//!
|
||||
//! - **Unified Engine Creation**: Pre-configured Rhai engine with all DSL modules
|
||||
//! - **Script Execution Utilities**: Direct evaluation, file-based execution, and AST compilation
|
||||
//! - **Mock Database System**: Complete testing environment with seeded data
|
||||
//! - **Feature-Based Architecture**: Modular compilation based on required domains
|
||||
//!
|
||||
//! ## Quick Start
|
||||
//!
|
||||
//! ```rust
|
||||
//! use rhailib_engine::{create_heromodels_engine, eval_script};
|
||||
//!
|
||||
//! // Create a fully configured engine
|
||||
//! let engine = create_heromodels_engine();
|
||||
//!
|
||||
//! // Execute a business logic script
|
||||
//! let result = eval_script(&engine, r#"
|
||||
//! let company = new_company()
|
||||
//! .name("Acme Corp")
|
||||
//! .business_type("global");
|
||||
//! company.name
|
||||
//! "#)?;
|
||||
//!
|
||||
//! println!("Company name: {}", result.as_string().unwrap());
|
||||
//! ```
|
||||
//!
|
||||
//! ## Available Features
|
||||
//!
|
||||
//! - `calendar` (default): Calendar and event management
|
||||
//! - `finance` (default): Financial accounts, assets, and marketplace
|
||||
//! - `flow`: Workflow and approval processes
|
||||
//! - `legal`: Contract and legal document management
|
||||
//! - `projects`: Project and task management
|
||||
//! - `biz`: Business operations and entities
|
||||
|
||||
use rhai::{Engine, EvalAltResult, Scope, AST};
|
||||
use rhailib_dsl;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
/// Mock database module for testing and examples
|
||||
pub mod mock_db;
|
||||
|
||||
/// Creates a fully configured Rhai engine with all available DSL modules.
|
||||
///
|
||||
/// This function creates a new Rhai engine instance, configures it with appropriate
|
||||
/// limits and settings, and registers all available business domain modules based
|
||||
/// on enabled features.
|
||||
///
|
||||
/// # Engine Configuration
|
||||
///
|
||||
/// The engine is configured with the following limits:
|
||||
/// - **Expression Depth**: 128 levels for both expressions and functions
|
||||
/// - **String Size**: 10 MB maximum
|
||||
/// - **Array Size**: 10,000 elements maximum
|
||||
/// - **Map Size**: 10,000 key-value pairs maximum
|
||||
///
|
||||
/// # Registered Modules
|
||||
///
|
||||
/// All enabled DSL modules are automatically registered, including:
|
||||
/// - Business operations (companies, products, sales, shareholders)
|
||||
/// - Financial models (accounts, assets, marketplace)
|
||||
/// - Content management (collections, images, PDFs, books)
|
||||
/// - Workflow management (flows, steps, signatures)
|
||||
/// - And more based on enabled features
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A fully configured `Engine` instance ready for script execution.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use rhailib_engine::create_heromodels_engine;
|
||||
///
|
||||
/// let engine = create_heromodels_engine();
|
||||
///
|
||||
/// // Engine is now ready to execute scripts with access to all DSL functions
|
||||
/// let result = engine.eval::<String>(r#"
|
||||
/// let company = new_company().name("Test Corp");
|
||||
/// company.name
|
||||
/// "#).unwrap();
|
||||
/// assert_eq!(result, "Test Corp");
|
||||
/// ```
|
||||
pub fn create_heromodels_engine() -> Engine {
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Configure engine settings
|
||||
engine.set_max_expr_depths(128, 128);
|
||||
engine.set_max_string_size(10 * 1024 * 1024); // 10 MB
|
||||
engine.set_max_array_size(10 * 1024); // 10K elements
|
||||
engine.set_max_map_size(10 * 1024); // 10K elements
|
||||
|
||||
// Register all heromodels Rhai modules
|
||||
rhailib_dsl::register_dsl_modules(&mut engine);
|
||||
|
||||
engine
|
||||
}
|
||||
|
||||
// /// Register all heromodels Rhai modules with the engine
|
||||
// pub fn register_all_modules(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
// // Register the calendar module if the feature is enabled
|
||||
// heromodels::models::access::register_access_rhai_module(engine, db.clone());
|
||||
// #[cfg(feature = "calendar")]
|
||||
// heromodels::models::calendar::register_calendar_rhai_module(engine, db.clone());
|
||||
// heromodels::models::contact::register_contact_rhai_module(engine, db.clone());
|
||||
// heromodels::models::library::register_library_rhai_module(engine, db.clone());
|
||||
// heromodels::models::circle::register_circle_rhai_module(engine, db.clone());
|
||||
|
||||
// // Register the flow module if the feature is enabled
|
||||
// #[cfg(feature = "flow")]
|
||||
// heromodels::models::flow::register_flow_rhai_module(engine, db.clone());
|
||||
|
||||
// // // Register the finance module if the feature is enabled
|
||||
// // #[cfg(feature = "finance")]
|
||||
// // heromodels::models::finance::register_finance_rhai_module(engine, db.clone());
|
||||
|
||||
// // Register the legal module if the feature is enabled
|
||||
// #[cfg(feature = "legal")]
|
||||
// heromodels::models::legal::register_legal_rhai_module(engine, db.clone());
|
||||
|
||||
// // Register the projects module if the feature is enabled
|
||||
// #[cfg(feature = "projects")]
|
||||
// heromodels::models::projects::register_projects_rhai_module(engine, db.clone());
|
||||
|
||||
// // Register the biz module if the feature is enabled
|
||||
// #[cfg(feature = "biz")]
|
||||
// heromodels::models::biz::register_biz_rhai_module(engine, db.clone());
|
||||
|
||||
// println!("Heromodels Rhai modules registered successfully.");
|
||||
// }
|
||||
|
||||
/// Evaluates a Rhai script string and returns the result.
|
||||
///
|
||||
/// This function provides a convenient way to execute Rhai script strings directly
|
||||
/// using the provided engine. It's suitable for one-off script execution or when
|
||||
/// the script content is dynamically generated.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `engine` - The Rhai engine to use for script execution
|
||||
/// * `script` - The Rhai script content as a string
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Ok(Dynamic)` - The result of script execution
|
||||
/// * `Err(Box<EvalAltResult>)` - Script compilation or execution error
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use rhailib_engine::{create_heromodels_engine, eval_script};
|
||||
///
|
||||
/// let engine = create_heromodels_engine();
|
||||
/// let result = eval_script(&engine, r#"
|
||||
/// let x = 42;
|
||||
/// let y = 8;
|
||||
/// x + y
|
||||
/// "#)?;
|
||||
/// assert_eq!(result.as_int().unwrap(), 50);
|
||||
/// ```
|
||||
pub fn eval_script(
|
||||
engine: &Engine,
|
||||
script: &str,
|
||||
) -> Result<rhai::Dynamic, Box<rhai::EvalAltResult>> {
|
||||
engine.eval::<rhai::Dynamic>(script)
|
||||
}
|
||||
|
||||
/// Evaluates a Rhai script from a file and returns the result.
|
||||
///
|
||||
/// This function reads a Rhai script from the filesystem and executes it using
|
||||
/// the provided engine. It handles file reading errors gracefully and provides
|
||||
/// meaningful error messages.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `engine` - The Rhai engine to use for script execution
|
||||
/// * `file_path` - Path to the Rhai script file
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Ok(Dynamic)` - The result of script execution
|
||||
/// * `Err(Box<EvalAltResult>)` - File reading, compilation, or execution error
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use rhailib_engine::{create_heromodels_engine, eval_file};
|
||||
/// use std::path::Path;
|
||||
///
|
||||
/// let engine = create_heromodels_engine();
|
||||
/// let result = eval_file(&engine, Path::new("scripts/business_logic.rhai"))?;
|
||||
/// println!("Script result: {:?}", result);
|
||||
/// ```
|
||||
///
|
||||
/// # Error Handling
|
||||
///
|
||||
/// File reading errors are converted to Rhai `ErrorSystem` variants with
|
||||
/// descriptive messages including the file path that failed to load.
|
||||
pub fn eval_file(
|
||||
engine: &Engine,
|
||||
file_path: &Path,
|
||||
) -> Result<rhai::Dynamic, Box<rhai::EvalAltResult>> {
|
||||
match fs::read_to_string(file_path) {
|
||||
Ok(script_content) => engine.eval::<rhai::Dynamic>(&script_content),
|
||||
Err(io_err) => Err(Box::new(EvalAltResult::ErrorSystem(
|
||||
format!("Failed to read script file: {}", file_path.display()),
|
||||
Box::new(io_err),
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Compiles a Rhai script string into an Abstract Syntax Tree (AST).
|
||||
///
|
||||
/// This function compiles a Rhai script into an AST that can be executed multiple
|
||||
/// times with different scopes. This is more efficient than re-parsing the script
|
||||
/// for each execution when the same script needs to be run repeatedly.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `engine` - The Rhai engine to use for compilation
|
||||
/// * `script` - The Rhai script content as a string
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Ok(AST)` - The compiled Abstract Syntax Tree
|
||||
/// * `Err(Box<EvalAltResult>)` - Script compilation error
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use rhailib_engine::{create_heromodels_engine, compile_script, run_ast};
|
||||
/// use rhai::Scope;
|
||||
///
|
||||
/// let engine = create_heromodels_engine();
|
||||
/// let ast = compile_script(&engine, r#"
|
||||
/// let company = new_company().name(company_name);
|
||||
/// save_company(company)
|
||||
/// "#)?;
|
||||
///
|
||||
/// // Execute the compiled script multiple times with different variables
|
||||
/// let mut scope1 = Scope::new();
|
||||
/// scope1.push("company_name", "Acme Corp");
|
||||
/// let result1 = run_ast(&engine, &ast, &mut scope1)?;
|
||||
///
|
||||
/// let mut scope2 = Scope::new();
|
||||
/// scope2.push("company_name", "Tech Startup");
|
||||
/// let result2 = run_ast(&engine, &ast, &mut scope2)?;
|
||||
/// ```
|
||||
pub fn compile_script(engine: &Engine, script: &str) -> Result<AST, Box<rhai::EvalAltResult>> {
|
||||
Ok(engine.compile(script)?)
|
||||
}
|
||||
|
||||
/// Executes a compiled Rhai script AST with the provided scope.
|
||||
///
|
||||
/// This function runs a pre-compiled AST using the provided engine and scope.
|
||||
/// The scope can contain variables and functions that will be available to
|
||||
/// the script during execution.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `engine` - The Rhai engine to use for execution
|
||||
/// * `ast` - The compiled Abstract Syntax Tree to execute
|
||||
/// * `scope` - Mutable scope containing variables and functions for the script
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Ok(Dynamic)` - The result of script execution
|
||||
/// * `Err(Box<EvalAltResult>)` - Script execution error
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use rhailib_engine::{create_heromodels_engine, compile_script, run_ast};
|
||||
/// use rhai::Scope;
|
||||
///
|
||||
/// let engine = create_heromodels_engine();
|
||||
/// let ast = compile_script(&engine, "x + y")?;
|
||||
///
|
||||
/// let mut scope = Scope::new();
|
||||
/// scope.push("x", 10_i64);
|
||||
/// scope.push("y", 32_i64);
|
||||
///
|
||||
/// let result = run_ast(&engine, &ast, &mut scope)?;
|
||||
/// assert_eq!(result.as_int().unwrap(), 42);
|
||||
/// ```
|
||||
///
|
||||
/// # Performance Notes
|
||||
///
|
||||
/// Using compiled ASTs is significantly more efficient than re-parsing scripts
|
||||
/// for repeated execution, especially for complex scripts or when executing
|
||||
/// the same logic with different input parameters.
|
||||
pub fn run_ast(
|
||||
engine: &Engine,
|
||||
ast: &AST,
|
||||
scope: &mut Scope,
|
||||
) -> Result<rhai::Dynamic, Box<rhai::EvalAltResult>> {
|
||||
engine.eval_ast_with_scope(scope, ast)
|
||||
}
|
374
core/engine/src/mock_db.rs
Normal file
374
core/engine/src/mock_db.rs
Normal file
@@ -0,0 +1,374 @@
|
||||
use chrono::Utc;
|
||||
use heromodels::db::hero::OurDB;
|
||||
use heromodels::db::{Collection, Db}; // Import both Db and Collection traits
|
||||
use heromodels::models::calendar::{Calendar, Event};
|
||||
use heromodels_core::Model; // Import Model trait to use build method
|
||||
use std::env;
|
||||
use std::sync::Arc;
|
||||
|
||||
// Import finance models
|
||||
use heromodels::models::finance::account::Account;
|
||||
use heromodels::models::finance::asset::{Asset, AssetType};
|
||||
use heromodels::models::finance::marketplace::{Listing, ListingType};
|
||||
|
||||
// Conditionally import other modules based on features
|
||||
#[cfg(feature = "flow")]
|
||||
use heromodels::models::flow::{Flow, FlowStep, SignatureRequirement};
|
||||
|
||||
#[cfg(feature = "legal")]
|
||||
use heromodels::models::legal::{
|
||||
Contract, ContractRevision, ContractSigner, ContractStatus, SignerStatus,
|
||||
};
|
||||
|
||||
#[cfg(feature = "projects")]
|
||||
use heromodels::models::projects::{ItemType, Priority, Project, Status as ProjectStatus};
|
||||
|
||||
/// Create a mock in-memory database for examples
|
||||
pub fn create_mock_db() -> Arc<OurDB> {
|
||||
// Create a temporary directory for the database files
|
||||
let temp_dir = env::temp_dir().join("engine_examples");
|
||||
std::fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");
|
||||
|
||||
// Create a new OurDB instance with reset=true to ensure it's clean
|
||||
let db = OurDB::new(temp_dir, true).expect("Failed to create OurDB instance");
|
||||
|
||||
Arc::new(db)
|
||||
}
|
||||
|
||||
/// Seed the mock database with some initial data for all modules
|
||||
pub fn seed_mock_db(db: Arc<OurDB>) {
|
||||
// Seed calendar data
|
||||
seed_calendar_data(db.clone());
|
||||
|
||||
// Seed finance data
|
||||
seed_finance_data(db.clone());
|
||||
|
||||
// Seed flow data if the feature is enabled
|
||||
#[cfg(feature = "flow")]
|
||||
seed_flow_data(db.clone());
|
||||
|
||||
// Seed legal data if the feature is enabled
|
||||
#[cfg(feature = "legal")]
|
||||
seed_legal_data(db.clone());
|
||||
|
||||
// Seed projects data if the feature is enabled
|
||||
#[cfg(feature = "projects")]
|
||||
seed_projects_data(db.clone());
|
||||
|
||||
println!("Mock database seeded with initial data for all enabled modules.");
|
||||
}
|
||||
|
||||
/// Seed the mock database with calendar data
|
||||
fn seed_calendar_data(db: Arc<OurDB>) {
|
||||
// Create a calendar
|
||||
let mut calendar = Calendar::new(None, "Work Calendar".to_string());
|
||||
calendar.description = Some("My work schedule".to_string());
|
||||
|
||||
// Store the calendar in the database
|
||||
let (_calendar_id, _updated_calendar) = db
|
||||
.collection::<Calendar>()
|
||||
.expect("Failed to get Calendar collection")
|
||||
.set(&calendar)
|
||||
.expect("Failed to store calendar");
|
||||
|
||||
// Create an event
|
||||
let now = Utc::now().timestamp();
|
||||
let end_time = now + 3600; // Add 1 hour in seconds
|
||||
|
||||
// Use the builder pattern for Event
|
||||
let event = Event::new()
|
||||
.title("Team Meeting".to_string())
|
||||
.reschedule(now, end_time)
|
||||
.location("Conference Room A".to_string())
|
||||
.description("Weekly sync".to_string())
|
||||
// .add_attendee(Attendee::new(1))
|
||||
// .add_attendee(Attendee::new(2))
|
||||
.build();
|
||||
|
||||
// // Add attendees to the event using the builder pattern
|
||||
// let attendee1 = Attendee::new(1);
|
||||
// let attendee2 = Attendee::new(2);
|
||||
|
||||
// // Add attendees using the builder pattern
|
||||
// event = event.add_attendee(attendee1);
|
||||
// event = event.add_attendee(attendee2);
|
||||
|
||||
// Call build and capture the returned value
|
||||
// let event = event.build();
|
||||
|
||||
// Store the event in the database first to get its ID
|
||||
let (event_id, updated_event) = db
|
||||
.collection()
|
||||
.expect("Failed to get Event collection")
|
||||
.set(&event)
|
||||
.expect("Failed to store event");
|
||||
|
||||
// Add the event ID to the calendar
|
||||
calendar = calendar.add_event(event_id as i64);
|
||||
|
||||
// Store the calendar in the database
|
||||
let (_calendar_id, updated_calendar) = db
|
||||
.collection::<Calendar>()
|
||||
.expect("Failed to get Calendar collection")
|
||||
.set(&calendar)
|
||||
.expect("Failed to store calendar");
|
||||
|
||||
println!("Mock database seeded with calendar data:");
|
||||
println!(
|
||||
" - Added calendar: {} (ID: {})",
|
||||
updated_calendar.name, updated_calendar.base_data.id
|
||||
);
|
||||
println!(
|
||||
" - Added event: {} (ID: {})",
|
||||
updated_event.title, updated_event.base_data.id
|
||||
);
|
||||
}
|
||||
|
||||
/// Seed the mock database with flow data
|
||||
#[cfg(feature = "flow")]
|
||||
fn seed_flow_data(db: Arc<OurDB>) {
|
||||
// Create a flow
|
||||
let mut flow = Flow::new(0, "Document Approval".to_string());
|
||||
|
||||
// Set flow properties using the builder pattern
|
||||
flow = flow.status("draft".to_string());
|
||||
flow = flow.name("Document Approval Flow".to_string());
|
||||
|
||||
// Create flow steps
|
||||
let mut step1 = FlowStep::new(0, 1);
|
||||
step1 = step1.description("Initial review by legal team".to_string());
|
||||
step1 = step1.status("pending".to_string());
|
||||
|
||||
let mut step2 = FlowStep::new(0, 2);
|
||||
step2 = step2.description("Approval by department head".to_string());
|
||||
step2 = step2.status("pending".to_string());
|
||||
|
||||
// Add signature requirements
|
||||
let mut req1 = SignatureRequirement::new(
|
||||
0,
|
||||
1,
|
||||
"Legal Team".to_string(),
|
||||
"Please review this document".to_string(),
|
||||
);
|
||||
let mut req2 = SignatureRequirement::new(
|
||||
0,
|
||||
2,
|
||||
"Department Head".to_string(),
|
||||
"Please approve this document".to_string(),
|
||||
);
|
||||
|
||||
// Add steps to flow
|
||||
flow = flow.add_step(step1);
|
||||
flow = flow.add_step(step2);
|
||||
|
||||
// Store in the database
|
||||
let (_, updated_flow) = db
|
||||
.collection::<Flow>()
|
||||
.expect("Failed to get Flow collection")
|
||||
.set(&flow)
|
||||
.expect("Failed to store flow");
|
||||
|
||||
// Store signature requirements in the database
|
||||
let (_, updated_req1) = db
|
||||
.collection::<SignatureRequirement>()
|
||||
.expect("Failed to get SignatureRequirement collection")
|
||||
.set(&req1)
|
||||
.expect("Failed to store signature requirement");
|
||||
|
||||
let (_, updated_req2) = db
|
||||
.collection::<SignatureRequirement>()
|
||||
.expect("Failed to get SignatureRequirement collection")
|
||||
.set(&req2)
|
||||
.expect("Failed to store signature requirement");
|
||||
|
||||
println!("Mock database seeded with flow data:");
|
||||
println!(
|
||||
" - Added flow: {} (ID: {})",
|
||||
updated_flow.name, updated_flow.base_data.id
|
||||
);
|
||||
println!(" - Added {} steps", updated_flow.steps.len());
|
||||
println!(
|
||||
" - Added signature requirements with IDs: {} and {}",
|
||||
updated_req1.base_data.id, updated_req2.base_data.id
|
||||
);
|
||||
}
|
||||
|
||||
/// Seed the mock database with legal data
|
||||
#[cfg(feature = "legal")]
|
||||
fn seed_legal_data(db: Arc<OurDB>) {
|
||||
// Create a contract
|
||||
let mut contract = Contract::new(None, "Service Agreement".to_string());
|
||||
contract.description = Some("Agreement for software development services".to_string());
|
||||
contract.status = ContractStatus::Draft;
|
||||
|
||||
// Create a revision
|
||||
let revision = ContractRevision::new(
|
||||
None,
|
||||
"Initial draft".to_string(),
|
||||
"https://example.com/contract/v1".to_string(),
|
||||
);
|
||||
|
||||
// Create signers
|
||||
let signer1 = ContractSigner::new(None, 1, "Client".to_string());
|
||||
let signer2 = ContractSigner::new(None, 2, "Provider".to_string());
|
||||
|
||||
// Add revision and signers to contract
|
||||
contract.add_revision(revision);
|
||||
contract.add_signer(signer1);
|
||||
contract.add_signer(signer2);
|
||||
|
||||
// Store in the database
|
||||
let (_, updated_contract) = db
|
||||
.collection::<Contract>()
|
||||
.expect("Failed to get Contract collection")
|
||||
.set(&contract)
|
||||
.expect("Failed to store contract");
|
||||
|
||||
println!("Mock database seeded with legal data:");
|
||||
println!(
|
||||
" - Added contract: {} (ID: {})",
|
||||
updated_contract.name, updated_contract.base_data.id
|
||||
);
|
||||
println!(
|
||||
" - Added {} revisions and {} signers",
|
||||
updated_contract.revisions.len(),
|
||||
updated_contract.signers.len()
|
||||
);
|
||||
}
|
||||
|
||||
/// Seed the mock database with projects data
|
||||
#[cfg(feature = "projects")]
|
||||
fn seed_projects_data(db: Arc<OurDB>) {
|
||||
// Create a project
|
||||
let mut project = Project::new(None, "Website Redesign".to_string());
|
||||
project.description = Some("Redesign the company website".to_string());
|
||||
project.status = ProjectStatus::InProgress;
|
||||
project.priority = Priority::High;
|
||||
|
||||
// Add members and tags
|
||||
project.add_member_id(1);
|
||||
project.add_member_id(2);
|
||||
project.add_tag("design".to_string());
|
||||
project.add_tag("web".to_string());
|
||||
|
||||
// Store in the database
|
||||
let (_, updated_project) = db
|
||||
.collection::<Project>()
|
||||
.expect("Failed to get Project collection")
|
||||
.set(&project)
|
||||
.expect("Failed to store project");
|
||||
|
||||
println!("Mock database seeded with projects data:");
|
||||
println!(
|
||||
" - Added project: {} (ID: {})",
|
||||
updated_project.name, updated_project.base_data.id
|
||||
);
|
||||
println!(
|
||||
" - Status: {}, Priority: {}",
|
||||
updated_project.status, updated_project.priority
|
||||
);
|
||||
println!(
|
||||
" - Added {} members and {} tags",
|
||||
updated_project.member_ids.len(),
|
||||
updated_project.tags.len()
|
||||
);
|
||||
}
|
||||
/// Seed the mock database with finance data
|
||||
fn seed_finance_data(db: Arc<OurDB>) {
|
||||
// Create a user account
|
||||
let mut account = Account::new()
|
||||
.name("Demo Account")
|
||||
.user_id(1)
|
||||
.description("Demo trading account")
|
||||
.ledger("ethereum")
|
||||
.address("0x1234567890abcdef1234567890abcdef12345678")
|
||||
.pubkey("0xabcdef1234567890abcdef1234567890abcdef12");
|
||||
|
||||
// Store the account in the database
|
||||
let (account_id, updated_account) = db
|
||||
.collection::<Account>()
|
||||
.expect("Failed to get Account collection")
|
||||
.set(&account)
|
||||
.expect("Failed to store account");
|
||||
|
||||
// Create an ERC20 token asset
|
||||
let token_asset = Asset::new()
|
||||
.name("HERO Token")
|
||||
.description("Herocode governance token")
|
||||
.amount(1000.0)
|
||||
.address("0x9876543210abcdef9876543210abcdef98765432")
|
||||
.asset_type(AssetType::Erc20)
|
||||
.decimals(18);
|
||||
|
||||
// Store the token asset in the database
|
||||
let (token_id, updated_token) = db
|
||||
.collection::<Asset>()
|
||||
.expect("Failed to get Asset collection")
|
||||
.set(&token_asset)
|
||||
.expect("Failed to store token asset");
|
||||
|
||||
// Create an NFT asset
|
||||
let nft_asset = Asset::new()
|
||||
.name("Herocode #1")
|
||||
.description("Unique digital collectible")
|
||||
.amount(1.0)
|
||||
.address("0xabcdef1234567890abcdef1234567890abcdef12")
|
||||
.asset_type(AssetType::Erc721)
|
||||
.decimals(0);
|
||||
|
||||
// Store the NFT asset in the database
|
||||
let (nft_id, updated_nft) = db
|
||||
.collection::<Asset>()
|
||||
.expect("Failed to get Asset collection")
|
||||
.set(&nft_asset)
|
||||
.expect("Failed to store NFT asset");
|
||||
|
||||
// Add assets to the account
|
||||
account = updated_account.add_asset(token_id);
|
||||
account = account.add_asset(nft_id);
|
||||
|
||||
// Update the account in the database
|
||||
let (_, updated_account) = db
|
||||
.collection::<Account>()
|
||||
.expect("Failed to get Account collection")
|
||||
.set(&account)
|
||||
.expect("Failed to store updated account");
|
||||
|
||||
// Create a listing for the NFT
|
||||
let listing = Listing::new()
|
||||
.seller_id(account_id)
|
||||
.asset_id(nft_id)
|
||||
.price(0.5)
|
||||
.currency("ETH")
|
||||
.listing_type(ListingType::Auction)
|
||||
.title("Rare Herocode NFT".to_string())
|
||||
.description("One of a kind digital collectible".to_string())
|
||||
.image_url(Some("hcttps://example.com/nft/1.png".to_string()))
|
||||
.add_tag("rare".to_string())
|
||||
.add_tag("collectible".to_string());
|
||||
|
||||
// Store the listing in the database
|
||||
let (_listing_id, updated_listing) = db
|
||||
.collection::<Listing>()
|
||||
.expect("Failed to get Listing collection")
|
||||
.set(&listing)
|
||||
.expect("Failed to store listing");
|
||||
|
||||
println!("Mock database seeded with finance data:");
|
||||
println!(
|
||||
" - Added account: {} (ID: {})",
|
||||
updated_account.name, updated_account.base_data.id
|
||||
);
|
||||
println!(
|
||||
" - Added token asset: {} (ID: {})",
|
||||
updated_token.name, updated_token.base_data.id
|
||||
);
|
||||
println!(
|
||||
" - Added NFT asset: {} (ID: {})",
|
||||
updated_nft.name, updated_nft.base_data.id
|
||||
);
|
||||
println!(
|
||||
" - Added listing: {} (ID: {})",
|
||||
updated_listing.title, updated_listing.base_data.id
|
||||
);
|
||||
}
|
Reference in New Issue
Block a user