fix: Fix all examples

This commit is contained in:
Mahmoud Emad 2025-05-17 16:03:00 +03:00
parent 57f59da43e
commit e4c50ca9d7
19 changed files with 166 additions and 80 deletions

View File

@ -1,8 +1,8 @@
// Get the database instance
let db = get_db();
// Create a new calendar
let calendar = calendar__builder(1);
// Create a new calendar with auto-generated ID (pass 0 for auto-generated ID)
let calendar = calendar__builder(0);
calendar.name = "My First Calendar";
set_description(calendar, "A calendar for testing Rhai integration");
@ -26,8 +26,8 @@ if calendar_exists(db, 1) {
print("Failed to retrieve calendar with ID 1");
}
// Create another calendar
let calendar2 = calendar__builder(2);
// Create another calendar with auto-generated ID
let calendar2 = calendar__builder(0);
calendar2.name = "My Second Calendar";
set_description(calendar2, "Another calendar for testing");

View File

@ -18,53 +18,54 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Register a function to get the database instance
engine.register_fn("get_db", move || db.clone());
// Register a calendar builder function
engine.register_fn("calendar__builder", |id: i64| {
Calendar::new(id as u32, "New Calendar")
let id_option = if id <= 0 { None } else { Some(id as u32) };
Calendar::new(id_option, "New Calendar")
});
// Register setter methods for Calendar properties
engine.register_fn("set_description", |calendar: &mut Calendar, desc: String| {
calendar.description = Some(desc);
});
// Register getter methods for Calendar properties
engine.register_fn("get_description", |calendar: Calendar| -> String {
calendar.description.clone().unwrap_or_default()
});
// Register getter for base_data.id
engine.register_fn("get_id", |calendar: Calendar| -> i64 {
calendar.base_data.id as i64
});
// Register additional functions needed by the script
engine.register_fn("set_calendar", |_db: Arc<OurDB>, _calendar: Calendar| {
// In a real implementation, this would save the calendar to the database
println!("Calendar saved: {}", _calendar.name);
});
engine.register_fn("get_calendar_by_id", |_db: Arc<OurDB>, id: i64| -> Calendar {
// In a real implementation, this would retrieve the calendar from the database
Calendar::new(id as u32, "Retrieved Calendar")
Calendar::new(Some(id as u32), "Retrieved Calendar")
});
// Register a function to check if a calendar exists
engine.register_fn("calendar_exists", |_db: Arc<OurDB>, id: i64| -> bool {
// In a real implementation, this would check if the calendar exists in the database
id == 1 || id == 2
});
// Define the function separately to use with the wrap_vec_return macro
fn get_all_calendars(_db: Arc<OurDB>) -> Vec<Calendar> {
// In a real implementation, this would retrieve all calendars from the database
vec![Calendar::new(1, "Calendar 1"), Calendar::new(2, "Calendar 2")]
vec![Calendar::new(Some(1), "Calendar 1"), Calendar::new(Some(2), "Calendar 2")]
}
// Register the function with the wrap_vec_return macro
engine.register_fn("get_all_calendars", wrap_vec_return!(get_all_calendars, Arc<OurDB> => Calendar));
engine.register_fn("delete_calendar_by_id", |_db: Arc<OurDB>, _id: i64| {
// In a real implementation, this would delete the calendar from the database
println!("Calendar deleted with ID: {}", _id);
@ -73,7 +74,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load and evaluate the Rhai script
let script_path = Path::new("examples/calendar_rhai/calendar.rhai");
let script = fs::read_to_string(script_path)?;
match engine.eval::<()>(&script) {
Ok(_) => println!("Script executed successfully!"),
Err(e) => eprintln!("Script execution failed: {}", e),

View File

@ -1,11 +1,16 @@
// heromodels/examples/governance_proposal_example/main.rs
use chrono::{Utc, Duration};
use heromodels::db::{Collection, Db};
use heromodels::models::governance::{Proposal, ProposalStatus, VoteEventStatus};
fn main() {
println!("Governance Proposal Model Example\n");
// Create a new DB instance, reset before every run
let db_path = "/tmp/ourdb_governance_proposal_example";
let db = heromodels::db::hero::OurDB::new(db_path, true).expect("Can create DB");
// Create a new proposal with auto-generated ID
let mut proposal = Proposal::new(
None, // id (auto-generated)
@ -16,9 +21,9 @@ fn main() {
Utc::now() + Duration::days(14) // vote_end_date (14 days from now)
);
println!("Created Proposal: '{}' (ID: {})", proposal.title, proposal.base_data.id);
println!("Status: {:?}, Vote Status: {:?}", proposal.status, proposal.vote_status);
println!("Vote Period: {} to {}\n", proposal.vote_start_date, proposal.vote_end_date);
println!("Before saving - Created Proposal: '{}' (ID: {})", proposal.title, proposal.base_data.id);
println!("Before saving - Status: {:?}, Vote Status: {:?}", proposal.status, proposal.vote_status);
println!("Before saving - Vote Period: {} to {}\n", proposal.vote_start_date, proposal.vote_end_date);
// Add vote options
proposal = proposal.add_option(1, "Approve Allocation");
@ -31,6 +36,16 @@ fn main() {
}
println!("");
// Save the proposal to the database
let collection = db.collection::<Proposal>().expect("can open proposal collection");
let (proposal_id, saved_proposal) = collection.set(&proposal).expect("can save proposal");
println!("After saving - Proposal ID: {}", saved_proposal.base_data.id);
println!("After saving - Returned ID: {}", proposal_id);
// Use the saved proposal for further operations
proposal = saved_proposal;
// Simulate casting votes
println!("Simulating Votes...");
// User 1 votes for 'Approve Allocation' with 100 shares (with explicit ballot ID)
@ -83,7 +98,7 @@ fn main() {
// Example of a private proposal (not fully implemented in cast_vote eligibility yet)
let mut private_proposal = Proposal::new(
Some(2), // explicit ID
None, // auto-generated ID
"user_admin_001",
"Internal Team Restructure Vote",
"Vote on proposed internal team changes.",
@ -94,8 +109,16 @@ fn main() {
private_proposal = private_proposal.add_option(1, "Accept Restructure");
private_proposal = private_proposal.add_option(2, "Reject Restructure");
println!("\nCreated Private Proposal: '{}'", private_proposal.title);
println!("Eligible Voters (Group): {:?}", private_proposal.private_group);
println!("\nBefore saving - Created Private Proposal: '{}'", private_proposal.title);
println!("Before saving - Eligible Voters (Group): {:?}", private_proposal.private_group);
// Save the private proposal to the database
let (private_proposal_id, saved_private_proposal) = collection.set(&private_proposal).expect("can save private proposal");
private_proposal = saved_private_proposal;
println!("After saving - Private Proposal ID: {}", private_proposal.base_data.id);
println!("After saving - Returned ID: {}", private_proposal_id);
// User 10 (eligible) votes with explicit ballot ID
private_proposal = private_proposal.cast_vote(Some(201), 10, 1, 100);
// User 40 (ineligible) tries to vote with auto-generated ballot ID
@ -106,5 +129,6 @@ fn main() {
println!(" - {}: {} (Votes: {})", option.id, option.text, option.count);
}
println!("\nGovernance Proposal Example Finished.");
println!("\nExample finished. DB stored at {}", db_path);
println!("To clean up, you can manually delete the directory: {}", db_path);
}

View File

@ -16,62 +16,65 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Register the Proposal type with Rhai
// This function is generated by the #[rhai_model_export] attribute
Proposal::register_rhai_bindings_for_proposal(&mut engine, db.clone());
// Register the Ballot type with Rhai
Ballot::register_rhai_bindings_for_ballot(&mut engine, db.clone());
// Register a function to get the database instance
engine.register_fn("get_db", move || db.clone());
// Register builder functions for Proposal and related types
engine.register_fn("create_proposal", |id: i64, creator_id: String, title: String, description: String| {
let start_date = Utc::now();
let end_date = start_date + Duration::days(14);
Proposal::new(id as u32, creator_id, title, description, start_date, end_date)
let id_option = if id <= 0 { None } else { Some(id as u32) };
Proposal::new(id_option, creator_id, title, description, start_date, end_date)
});
engine.register_fn("create_vote_option", |id: i64, text: String| {
VoteOption::new(id as u8, text)
});
engine.register_fn("create_ballot", |id: i64, user_id: i64, vote_option_id: i64, shares_count: i64| {
Ballot::new(id as u32, user_id as u32, vote_option_id as u8, shares_count)
let id_option = if id <= 0 { None } else { Some(id as u32) };
Ballot::new(id_option, user_id as u32, vote_option_id as u8, shares_count)
});
// Register getter and setter methods for Proposal properties
engine.register_fn("get_title", |proposal: Proposal| -> String {
proposal.title.clone()
});
engine.register_fn("get_description", |proposal: Proposal| -> String {
proposal.description.clone()
});
engine.register_fn("get_creator_id", |proposal: Proposal| -> String {
proposal.creator_id.clone()
});
engine.register_fn("get_id", |proposal: Proposal| -> i64 {
proposal.base_data.id as i64
});
engine.register_fn("get_status", |proposal: Proposal| -> String {
format!("{:?}", proposal.status)
});
engine.register_fn("get_vote_status", |proposal: Proposal| -> String {
format!("{:?}", proposal.vote_status)
});
// Register methods for proposal operations
engine.register_fn("add_option_to_proposal", |mut proposal: Proposal, option_id: i64, option_text: String| -> Proposal {
proposal.add_option(option_id as u8, option_text)
});
engine.register_fn("cast_vote_on_proposal", |mut proposal: Proposal, ballot_id: i64, user_id: i64, option_id: i64, shares: i64| -> Proposal {
proposal.cast_vote(ballot_id as u32, user_id as u32, option_id as u8, shares)
let ballot_id_option = if ballot_id <= 0 { None } else { Some(ballot_id as u32) };
proposal.cast_vote(ballot_id_option, user_id as u32, option_id as u8, shares)
});
engine.register_fn("change_proposal_status", |mut proposal: Proposal, status_str: String| -> Proposal {
let new_status = match status_str.as_str() {
"Draft" => ProposalStatus::Draft,
@ -83,7 +86,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
};
proposal.change_proposal_status(new_status)
});
engine.register_fn("change_vote_event_status", |mut proposal: Proposal, status_str: String| -> Proposal {
let new_status = match status_str.as_str() {
"Open" => VoteEventStatus::Open,
@ -93,49 +96,49 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
};
proposal.change_vote_event_status(new_status)
});
// Register functions for database operations
engine.register_fn("save_proposal", |_db: Arc<OurDB>, proposal: Proposal| {
println!("Proposal saved: {}", proposal.title);
});
engine.register_fn("get_proposal_by_id", |_db: Arc<OurDB>, id: i64| -> Proposal {
// In a real implementation, this would retrieve the proposal from the database
let start_date = Utc::now();
let end_date = start_date + Duration::days(14);
Proposal::new(id as u32, "Retrieved Creator", "Retrieved Proposal", "Retrieved Description", start_date, end_date)
Proposal::new(Some(id as u32), "Retrieved Creator", "Retrieved Proposal", "Retrieved Description", start_date, end_date)
});
// Register a function to check if a proposal exists
engine.register_fn("proposal_exists", |_db: Arc<OurDB>, id: i64| -> bool {
// In a real implementation, this would check if the proposal exists in the database
id == 1 || id == 2
});
// Define the function for get_all_proposals
fn get_all_proposals(_db: Arc<OurDB>) -> Vec<Proposal> {
// In a real implementation, this would retrieve all proposals from the database
let start_date = Utc::now();
let end_date = start_date + Duration::days(14);
vec![
Proposal::new(1, "Creator 1", "Proposal 1", "Description 1", start_date, end_date),
Proposal::new(2, "Creator 2", "Proposal 2", "Description 2", start_date, end_date)
Proposal::new(Some(1), "Creator 1", "Proposal 1", "Description 1", start_date, end_date),
Proposal::new(Some(2), "Creator 2", "Proposal 2", "Description 2", start_date, end_date)
]
}
// Register the function with the wrap_vec_return macro
engine.register_fn("get_all_proposals", wrap_vec_return!(get_all_proposals, Arc<OurDB> => Proposal));
engine.register_fn("delete_proposal_by_id", |_db: Arc<OurDB>, _id: i64| {
// In a real implementation, this would delete the proposal from the database
println!("Proposal deleted with ID: {}", _id);
});
// Register helper functions for accessing proposal options and ballots
engine.register_fn("get_option_count", |proposal: Proposal| -> i64 {
proposal.options.len() as i64
});
engine.register_fn("get_option_at", |proposal: Proposal, index: i64| -> VoteOption {
if index >= 0 && index < proposal.options.len() as i64 {
proposal.options[index as usize].clone()
@ -143,35 +146,35 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
VoteOption::new(0, "Invalid Option")
}
});
engine.register_fn("get_option_text", |option: VoteOption| -> String {
option.text.clone()
});
engine.register_fn("get_option_votes", |option: VoteOption| -> i64 {
option.count
});
engine.register_fn("get_ballot_count", |proposal: Proposal| -> i64 {
proposal.ballots.len() as i64
});
engine.register_fn("get_ballot_at", |proposal: Proposal, index: i64| -> Ballot {
if index >= 0 && index < proposal.ballots.len() as i64 {
proposal.ballots[index as usize].clone()
} else {
Ballot::new(0, 0, 0, 0)
Ballot::new(None, 0, 0, 0)
}
});
engine.register_fn("get_ballot_user_id", |ballot: Ballot| -> i64 {
ballot.user_id as i64
});
engine.register_fn("get_ballot_option_id", |ballot: Ballot| -> i64 {
ballot.vote_option_id as i64
});
engine.register_fn("get_ballot_shares", |ballot: Ballot| -> i64 {
ballot.shares_count
});
@ -179,7 +182,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load and evaluate the Rhai script
let script_path = Path::new("examples/governance_rhai/governance.rhai");
let script = fs::read_to_string(script_path)?;
match engine.eval::<()>(&script) {
Ok(_) => println!("Script executed successfully!"),
Err(e) => eprintln!("Script execution failed: {}", e),

View File

@ -1,8 +1,8 @@
// Get the database instance
let db = get_db();
// Create a new proposal
let proposal = create_proposal(1, "user_creator_123", "Community Fund Allocation for Q3",
// Create a new proposal with auto-generated ID (pass 0 for auto-generated ID)
let proposal = create_proposal(0, "user_creator_123", "Community Fund Allocation for Q3",
"Proposal to allocate funds for community projects in the third quarter.");
print("Created Proposal: '" + get_title(proposal) + "' (ID: " + get_id(proposal) + ")");
@ -26,14 +26,14 @@ print("\nProposal saved to database");
// Simulate casting votes
print("\nSimulating Votes...");
// User 1 votes for 'Approve Allocation' with 100 shares
// User 1 votes for 'Approve Allocation' with 100 shares (with explicit ballot ID)
let proposal_with_votes = cast_vote_on_proposal(proposal_with_options, 101, 1, 1, 100);
// User 2 votes for 'Reject Allocation' with 50 shares
// User 2 votes for 'Reject Allocation' with 50 shares (with explicit ballot ID)
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 102, 2, 2, 50);
// User 3 votes for 'Approve Allocation' with 75 shares
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 103, 3, 1, 75);
// User 4 abstains with 20 shares
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 104, 4, 3, 20);
// User 3 votes for 'Approve Allocation' with 75 shares (with auto-generated ballot ID)
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 0, 3, 1, 75);
// User 4 abstains with 20 shares (with auto-generated ballot ID)
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 0, 4, 3, 20);
print("\nVote Counts After Simulation:");
option_count = get_option_count(proposal_with_votes);
@ -46,7 +46,7 @@ print("\nBallots Cast:");
let ballot_count = get_ballot_count(proposal_with_votes);
for i in range(0, ballot_count) {
let ballot = get_ballot_at(proposal_with_votes, i);
print("- Ballot ID: " + i + ", User ID: " + get_ballot_user_id(ballot) +
print("- Ballot ID: " + i + ", User ID: " + get_ballot_user_id(ballot) +
", Option ID: " + get_ballot_option_id(ballot) + ", Shares: " + get_ballot_shares(ballot));
}

View File

@ -24,6 +24,7 @@ impl Account {
/// Create a new account with auto-generated ID
///
/// # Arguments
/// * `id` - Optional ID for the account (use None for auto-generated ID)
/// * `name` - Name of the account
/// * `user_id` - ID of the user who owns the account
/// * `description` - Description of the account
@ -31,6 +32,7 @@ impl Account {
/// * `address` - Address of the account on the blockchain
/// * `pubkey` - Public key
pub fn new(
id: Option<u32>,
name: impl ToString,
user_id: u32,
description: impl ToString,
@ -38,8 +40,13 @@ impl Account {
address: impl ToString,
pubkey: impl ToString
) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self {
base_data: BaseModelData::new(),
base_data,
name: name.to_string(),
user_id,
description: description.to_string(),

View File

@ -34,7 +34,17 @@ pub struct Asset {
impl Asset {
/// Create a new asset with auto-generated ID
///
/// # Arguments
/// * `id` - Optional ID for the asset (use None for auto-generated ID)
/// * `name` - Name of the asset
/// * `description` - Description of the asset
/// * `amount` - Amount of the asset
/// * `address` - Address of the asset on the blockchain or bank
/// * `asset_type` - Type of the asset
/// * `decimals` - Number of decimals of the asset
pub fn new(
id: Option<u32>,
name: impl ToString,
description: impl ToString,
amount: f64,
@ -42,8 +52,13 @@ impl Asset {
asset_type: AssetType,
decimals: u8,
) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self {
base_data: BaseModelData::new(),
base_data,
name: name.to_string(),
description: description.to_string(),
amount,

View File

@ -112,7 +112,22 @@ pub struct Listing {
impl Listing {
/// Create a new listing with auto-generated ID
///
/// # Arguments
/// * `id` - Optional ID for the listing (use None for auto-generated ID)
/// * `title` - Title of the listing
/// * `description` - Description of the listing
/// * `asset_id` - ID of the asset being listed
/// * `asset_type` - Type of the asset
/// * `seller_id` - ID of the seller
/// * `price` - Initial price for fixed price, or starting price for auction
/// * `currency` - Currency of the price
/// * `listing_type` - Type of the listing
/// * `expires_at` - Optional expiration date
/// * `tags` - Tags for the listing
/// * `image_url` - Optional image URL
pub fn new(
id: Option<u32>,
title: impl ToString,
description: impl ToString,
asset_id: impl ToString,
@ -125,8 +140,13 @@ impl Listing {
tags: Vec<String>,
image_url: Option<impl ToString>,
) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self {
base_data: BaseModelData::new(),
base_data,
title: title.to_string(),
description: description.to_string(),
asset_id: asset_id.to_string(),

View File

@ -78,12 +78,18 @@ impl Ballot {
/// Create a new ballot with auto-generated ID
///
/// # Arguments
/// * `id` - Optional ID for the ballot (use None for auto-generated ID)
/// * `user_id` - ID of the user who cast this ballot
/// * `vote_option_id` - ID of the vote option chosen
/// * `shares_count` - Number of shares/tokens/voting power
pub fn new(user_id: u32, vote_option_id: u8, shares_count: i64) -> Self {
pub fn new(id: Option<u32>, user_id: u32, vote_option_id: u8, shares_count: i64) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self {
base_data: BaseModelData::new(),
base_data,
user_id,
vote_option_id,
shares_count,
@ -116,14 +122,20 @@ impl Proposal {
/// Create a new proposal with auto-generated ID
///
/// # Arguments
/// * `id` - Optional ID for the proposal (use None for auto-generated ID)
/// * `creator_id` - ID of the user who created the proposal
/// * `title` - Title of the proposal
/// * `description` - Description of the proposal
/// * `vote_start_date` - Date when voting starts
/// * `vote_end_date` - Date when voting ends
pub fn new(creator_id: impl ToString, title: impl ToString, description: impl ToString, vote_start_date: DateTime<Utc>, vote_end_date: DateTime<Utc>) -> Self {
pub fn new(id: Option<u32>, creator_id: impl ToString, title: impl ToString, description: impl ToString, vote_start_date: DateTime<Utc>, vote_end_date: DateTime<Utc>) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self {
base_data: BaseModelData::new(),
base_data,
creator_id: creator_id.to_string(),
title: title.to_string(),
description: description.to_string(),
@ -143,7 +155,7 @@ impl Proposal {
self
}
pub fn cast_vote(mut self, user_id: u32, chosen_option_id: u8, shares: i64) -> Self {
pub fn cast_vote(mut self, ballot_id: Option<u32>, user_id: u32, chosen_option_id: u8, shares: i64) -> Self {
if self.vote_status != VoteEventStatus::Open {
eprintln!("Voting is not open for proposal '{}'", self.title);
return self;
@ -159,7 +171,7 @@ impl Proposal {
}
}
let new_ballot = Ballot::new(user_id, chosen_option_id, shares);
let new_ballot = Ballot::new(ballot_id, user_id, chosen_option_id, shares);
self.ballots.push(new_ballot);
if let Some(option) = self.options.iter_mut().find(|opt| opt.id == chosen_option_id) {

View File

@ -0,0 +1 @@
1

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
2

Binary file not shown.

View File

@ -0,0 +1 @@
1

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
2

Binary file not shown.