From c2ee73984b4dcf47d9cb2fb29aabe0a5f82d0d58 Mon Sep 17 00:00:00 2001 From: Henry Ebubechukwu Date: Thu, 23 Apr 2026 14:47:32 +0100 Subject: [PATCH] Update the lib.rs file with the latest contract implementation --- contracts/reputation/src/lib.rs | 333 ++++++++++++++++++++++++++------ 1 file changed, 278 insertions(+), 55 deletions(-) diff --git a/contracts/reputation/src/lib.rs b/contracts/reputation/src/lib.rs index 38a5899c..c643607c 100644 --- a/contracts/reputation/src/lib.rs +++ b/contracts/reputation/src/lib.rs @@ -41,7 +41,7 @@ pub enum Role { pub struct ReputationScore { pub address: Address, pub role: Role, - /// Score in basis points (0–10000 = 0–100%) + /// Score in basis points (0\u201310000 = 0\u2013100%) pub score: i32, pub total_jobs: u32, /// Sum of raw rating points (1-5) to compute aggregates off-chain @@ -50,6 +50,14 @@ pub struct ReputationScore { pub reviews: u32, } +#[contracttype] +#[derive(Clone, Debug, PartialEq)] +pub struct ReputationView { + pub address: Address, + pub client: ReputationScore, + pub freelancer: ReputationScore, +} + #[contracttype] pub enum DataKey { Admin, @@ -62,6 +70,11 @@ pub enum DataKey { pub enum ReputationError { NotInitialized = 1, Unauthorized = 2, + InvalidInput = 3, + JobNotCompleted = 4, + NotJobParticipant = 5, + AlreadyReviewed = 6, + ContractStateError = 7, } #[contracttype] @@ -72,6 +85,32 @@ pub struct ContractUpgradedEvent { pub upgraded_at: u64, } +#[contracttype] +#[derive(Clone)] +pub struct ReputationUpdatedEvent { + pub job_id: u64, + pub caller: Address, + pub target: Address, + pub role: Role, + pub rating: u32, + pub new_score: i32, + pub total_jobs: u32, + pub total_points: i32, + pub reviews: u32, + pub updated_at: u64, +} + +#[contracttype] +#[derive(Clone)] +pub struct ScoreAdjustedEvent { + pub address: Address, + pub role: Role, + pub delta: i32, + pub new_score: i32, + pub total_jobs: u32, + pub adjusted_at: u64, +} + #[contract] pub struct ReputationContract; @@ -88,6 +127,31 @@ impl ReputationContract { .extend_ttl(Self::INSTANCE_TTL_THRESHOLD, Self::INSTANCE_TTL_EXTEND_TO); } + fn score_from_rating(score: u32) -> i32 { + (score as i32).saturating_mul(2_000) + } + + fn score_from_profile(address: &Address, role: Role, profile: &profile::Profile) -> ReputationScore { + match role { + Role::Client => ReputationScore { + address: address.clone(), + role: Role::Client, + score: profile.client_score, + total_jobs: profile.client_jobs, + total_points: profile.client_points, + reviews: profile.client_jobs, + }, + Role::Freelancer => ReputationScore { + address: address.clone(), + role: Role::Freelancer, + score: profile.freelancer_score, + total_jobs: profile.freelancer_jobs, + total_points: profile.freelancer_points, + reviews: profile.freelancer_jobs, + }, + } + } + /// Upgrades the current contract WASM. Only callable by admin. pub fn upgrade( env: Env, @@ -149,20 +213,17 @@ impl ReputationContract { /// Submit a rating for a target address tied to a Job ID. Caller must be the client or freelancer /// on the job, and the job must be Completed. pub fn submit_rating(env: Env, caller: Address, job_id: u64, target: Address, score: u32) { - // caller must authorize caller.require_auth(); + if !(1u32..=5u32).contains(&score) { + soroban_sdk::panic_with_error!(&env, ReputationError::InvalidInput); + } - // validate score in 1..=5 - assert!((1u32..=5u32).contains(&score), "score out of range"); - - // ensure job registry is configured let registry_addr: Address = env .storage() .instance() .get(&DataKey::JobRegistry) .expect("job registry not set"); - // call JobRegistry.get_job(job_id) and decode into local JobRecord let get_sym = Symbol::new(&env, "get_job"); let args = soroban_sdk::vec![&env, job_id.into_val(&env)]; let job: JobRecord = env @@ -173,37 +234,53 @@ impl ReputationContract { ) .unwrap(); - // verify job is completed (ratings only allowed after completion) - assert!(job.status == JobStatus::Completed, "job not completed"); + if job.status != JobStatus::Completed { + soroban_sdk::panic_with_error!(&env, ReputationError::JobNotCompleted); + } - // verify caller is participant let caller_addr = caller.clone(); let is_client = caller_addr == job.client; let is_freelancer = match job.freelancer.clone() { Some(f) => caller_addr == f, None => false, }; - assert!(is_client || is_freelancer, "unauthorized to rate"); + if !(is_client || is_freelancer) { + soroban_sdk::panic_with_error!(&env, ReputationError::Unauthorized); + } - // prevent double review let reviewed_key = DataKey::Reviewed(job_id, caller.clone()); - assert!( - !env.storage().persistent().has(&reviewed_key), - "already reviewed" - ); + if env.storage().persistent().has(&reviewed_key) { + soroban_sdk::panic_with_error!(&env, ReputationError::AlreadyReviewed); + } - // update reputation aggregates for target let mut profile = storage::read_profile_or_default(&env, &target); - - // We assume target is a freelancer for now in submit_rating - // In a more complex system, we might need to know which role was rated. - profile.freelancer_points = profile.freelancer_points.saturating_add(score as i32); - profile.freelancer_jobs = profile.freelancer_jobs.saturating_add(1); - - // compute new averaged score in basis points: avg = total_points / jobs, scaled - let avg = profile.freelancer_points / (profile.freelancer_jobs as i32); - let bps = avg.saturating_mul(2000); // 1->2000 ... 5->10000 - profile.freelancer_score = Self::clamp_score(bps); + let (role, total_points, total_jobs, new_score) = if target == job.client { + profile.client_points = profile.client_points.saturating_add(score as i32); + profile.client_jobs = profile.client_jobs.saturating_add(1); + let avg = profile.client_points / (profile.client_jobs as i32); + let bps = Self::score_from_rating(avg as u32); + profile.client_score = Self::clamp_score(bps); + ( + Role::Client, + profile.client_points, + profile.client_jobs, + profile.client_score, + ) + } else if job.freelancer.as_ref() == Some(&target) { + profile.freelancer_points = profile.freelancer_points.saturating_add(score as i32); + profile.freelancer_jobs = profile.freelancer_jobs.saturating_add(1); + let avg = profile.freelancer_points / (profile.freelancer_jobs as i32); + let bps = Self::score_from_rating(avg as u32); + profile.freelancer_score = Self::clamp_score(bps); + ( + Role::Freelancer, + profile.freelancer_points, + profile.freelancer_jobs, + profile.freelancer_score, + ) + } else { + soroban_sdk::panic_with_error!(&env, ReputationError::NotJobParticipant); + }; storage::write_profile(&env, &target, &profile); env.storage().persistent().set(&reviewed_key, &true); @@ -212,6 +289,21 @@ impl ReputationContract { Self::PERSISTENT_TTL_THRESHOLD, Self::PERSISTENT_TTL_EXTEND_TO, ); + env.events().publish( + ("reputation", "ReputationUpdated"), + ReputationUpdatedEvent { + job_id, + caller, + target, + role, + rating: score, + new_score, + total_jobs, + total_points, + reviews: total_jobs, + updated_at: env.ledger().timestamp(), + }, + ); Self::bump_instance_ttl(&env); } @@ -226,20 +318,32 @@ impl ReputationContract { admin.require_auth(); let mut profile = storage::read_profile_or_default(&env, &address); - match role { + let (new_score, total_jobs) = match role { Role::Client => { - profile.client_score = - Self::clamp_score(profile.client_score.saturating_add(delta)); + profile.client_score = Self::clamp_score(profile.client_score.saturating_add(delta)); profile.client_jobs = profile.client_jobs.saturating_add(1); + (profile.client_score, profile.client_jobs) } Role::Freelancer => { profile.freelancer_score = Self::clamp_score(profile.freelancer_score.saturating_add(delta)); profile.freelancer_jobs = profile.freelancer_jobs.saturating_add(1); + (profile.freelancer_score, profile.freelancer_jobs) } - } + }; storage::write_profile(&env, &address, &profile); + env.events().publish( + ("reputation", "ScoreAdjusted"), + ScoreAdjustedEvent { + address, + role, + delta, + new_score, + total_jobs, + adjusted_at: env.ledger().timestamp(), + }, + ); Self::bump_instance_ttl(&env); } @@ -253,41 +357,37 @@ impl ReputationContract { admin.require_auth(); let mut profile = storage::read_profile_or_default(&env, &address); - match role { + let (new_score, total_jobs) = match role { Role::Client => { profile.client_score = Self::clamp_score(profile.client_score.saturating_sub(2000)); + (profile.client_score, profile.client_jobs) } Role::Freelancer => { profile.freelancer_score = Self::clamp_score(profile.freelancer_score.saturating_sub(2000)); + (profile.freelancer_score, profile.freelancer_jobs) } - } + }; storage::write_profile(&env, &address, &profile); + env.events().publish( + ("reputation", "ScoreAdjusted"), + ScoreAdjustedEvent { + address, + role, + delta: -2_000, + new_score, + total_jobs, + adjusted_at: env.ledger().timestamp(), + }, + ); Self::bump_instance_ttl(&env); } pub fn get_score(env: Env, address: Address, role: Role) -> ReputationScore { Self::bump_instance_ttl(&env); let profile = storage::read_profile_or_default(&env, &address); - match role { - Role::Client => ReputationScore { - address, - role: Role::Client, - score: profile.client_score, - total_jobs: profile.client_jobs, - total_points: profile.client_points, - reviews: profile.client_jobs, // reviews and total_jobs are unified - }, - Role::Freelancer => ReputationScore { - address, - role: Role::Freelancer, - score: profile.freelancer_score, - total_jobs: profile.freelancer_jobs, - total_points: profile.freelancer_points, - reviews: profile.freelancer_jobs, - }, - } + Self::score_from_profile(&address, role, &profile) } /// Update profile metadata hash (IPFS CID) @@ -308,11 +408,12 @@ impl ReputationContract { /// Frontend-friendly aggregate metrics for public profile pages. /// Returns: [score_bps, total_jobs, total_points, reviews] pub fn get_public_metrics(env: Env, address: Address, role_name: Symbol) -> Vec { - Self::bump_instance_ttl(&env); let role = if role_name == Symbol::new(&env, "client") { Role::Client - } else { + } else if role_name == Symbol::new(&env, "freelancer") { Role::Freelancer + } else { + soroban_sdk::panic_with_error!(&env, ReputationError::InvalidInput); }; let rep = Self::get_score(env.clone(), address, role); @@ -323,6 +424,19 @@ impl ReputationContract { metrics.push_back(rep.reviews as i128); metrics } + + /// Read both role snapshots for a single address in one call. + pub fn query_reputation(env: Env, address: Address) -> ReputationView { + Self::bump_instance_ttl(&env); + let profile = storage::read_profile_or_default(&env, &address); + let client = Self::score_from_profile(&address, Role::Client, &profile); + let freelancer = Self::score_from_profile(&address, Role::Freelancer, &profile); + ReputationView { + address, + client, + freelancer, + } + } } impl ReputationContract { @@ -337,6 +451,31 @@ mod test { use soroban_sdk::testutils::Address as _; use soroban_sdk::{Address, BytesN, Env}; + #[contract] + pub struct MockJobRegistry; + + #[contracttype] + enum MockKey { + Job(u64), + } + + #[contractimpl] + impl MockJobRegistry { + pub fn set_job(env: Env, job_id: u64, job: JobRecord) { + env.storage() + .persistent() + .set(&MockKey::Job(job_id), &job); + } + + pub fn get_job(env: Env, _job_id: u64) -> Result { + Ok(env + .storage() + .persistent() + .get(&MockKey::Job(_job_id)) + .expect("mock job missing")) + } + } + #[test] fn test_initial_score() { let env = Env::default(); @@ -429,7 +568,91 @@ mod test { } #[test] - #[should_panic(expected = "Error(Contract, #2)")] + fn test_query_reputation_returns_both_roles() { + let env = Env::default(); + env.mock_all_auths(); + + let admin = Address::generate(&env); + let address = Address::generate(&env); + let contract_id = env.register_contract(None, ReputationContract); + let client = ReputationContractClient::new(&env, &contract_id); + + client.initialize(&admin); + client.update_score(&address, &Role::Freelancer, &1000); + client.update_score(&address, &Role::Client, &500); + + let view = client.query_reputation(&address); + assert_eq!(view.address, address); + assert_eq!(view.client.score, 5500); + assert_eq!(view.client.total_jobs, 1); + assert_eq!(view.client.total_points, 500); + assert_eq!(view.freelancer.score, 6000); + assert_eq!(view.freelancer.total_jobs, 1); + assert_eq!(view.freelancer.total_points, 1000); + } + + #[test] + #[should_panic(expected = "Error(Contract, #3)")] + fn test_get_public_metrics_rejects_unknown_role() { + let env = Env::default(); + let address = Address::generate(&env); + let contract_id = env.register_contract(None, ReputationContract); + let client = ReputationContractClient::new(&env, &contract_id); + + client.get_public_metrics(&address, &soroban_sdk::Symbol::new(&env, "bogus")); + } + + #[test] + fn test_submit_rating_updates_client_and_freelancer_paths() { + let env = Env::default(); + env.mock_all_auths(); + + let admin = Address::generate(&env); + let caller = Address::generate(&env); + let target = Address::generate(&env); + let freelancer = Address::generate(&env); + let caller2 = Address::generate(&env); + let contract_id = env.register_contract(None, ReputationContract); + let client = ReputationContractClient::new(&env, &contract_id); + client.initialize(&admin); + + let mock_id = env.register_contract(None, MockJobRegistry); + client.set_job_registry(&admin, &mock_id); + + let job = JobRecord { + client: caller.clone(), + freelancer: Some(freelancer.clone()), + metadata_hash: Bytes::from_slice(&env, b"QmJob"), + budget_stroops: 10, + status: JobStatus::Completed, + }; + let mock_client = MockJobRegistryClient::new(&env, &mock_id); + mock_client.set_job(&7u64, &job); + let other_job = JobRecord { + client: caller2.clone(), + freelancer: Some(target.clone()), + metadata_hash: Bytes::from_slice(&env, b"QmJob2"), + budget_stroops: 10, + status: JobStatus::Completed, + }; + mock_client.set_job(&8u64, &other_job); + + client.submit_rating(&caller, &7u64, &freelancer, &5u32); + let client_score = client.get_score(&freelancer, &Role::Freelancer); + assert_eq!(client_score.score, 10_000); + assert_eq!(client_score.total_jobs, 1); + assert_eq!(client_score.total_points, 5); + + client.submit_rating(&caller2, &8u64, &target, &4u32); + let freelancer_score = client.get_score(&target, &Role::Freelancer); + assert_eq!(freelancer_score.score, 8_000); + assert_eq!(freelancer_score.total_jobs, 1); + assert_eq!(freelancer_score.total_points, 4); + assert_eq!(freelancer_score.reviews, 1); + } + + #[test] + #[should_panic(expected = "Error(Contract, #2)")] fn test_upgrade_requires_admin() { let env = Env::default(); env.mock_all_auths(); @@ -443,4 +666,4 @@ mod test { let wasm_hash = BytesN::from_array(&env, &[0; 32]); client.upgrade(&attacker, &wasm_hash); } -} +} \ No newline at end of file