From eac08e1274a2c8e669c311bfd85a54225406232b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?bmidun=20=E2=9C=8C=F0=9F=8F=BD?= Date: Thu, 19 Nov 2026 19:58:42 +0000 Subject: [PATCH] Add permissionless escrow state queries Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- contracts/contracts/escrow/src/lib.rs | 171 +++++++++++++++++++++++++ contracts/contracts/escrow/src/test.rs | 111 ++++++++++++++++ docs/soroban-contract-events.md | 78 +++++++++++ 3 files changed, 360 insertions(+) diff --git a/contracts/contracts/escrow/src/lib.rs b/contracts/contracts/escrow/src/lib.rs index d82054e..3527254 100644 --- a/contracts/contracts/escrow/src/lib.rs +++ b/contracts/contracts/escrow/src/lib.rs @@ -20,6 +20,20 @@ pub enum MilestoneStatus { Extended = 11, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[contracttype] +pub enum EscrowStatus { + Created = 0, + Funded = 1, + InProgress = 2, + Submitted = 3, + Approved = 4, + Disputed = 5, + PartiallySettled = 6, + Completed = 7, + Expired = 8, +} + #[derive(Clone, Debug, PartialEq, Eq)] #[contracttype] pub struct Milestone { @@ -32,6 +46,37 @@ pub struct Milestone { pub freelancer_approved: bool, } +#[derive(Clone, Debug, PartialEq, Eq)] +#[contracttype] +pub struct MilestoneState { + pub id: u32, + pub deadline: u64, + pub allocated_amount: i128, + pub released_amount: i128, + pub refunded_amount: i128, + pub remaining_amount: i128, + pub status: MilestoneStatus, + pub completed: bool, + pub client_approved: bool, + pub freelancer_approved: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[contracttype] +pub struct EscrowState { + pub client: Address, + pub freelancer: Address, + pub arbiter: Address, + pub token: Address, + pub allocated_amount: i128, + pub released_amount: i128, + pub refunded_amount: i128, + pub remaining_balance: i128, + pub funded: bool, + pub status: EscrowStatus, + pub milestones: Vec, +} + #[derive(Clone, Debug, PartialEq, Eq)] #[contracttype] pub enum DataKey { @@ -47,6 +92,7 @@ pub enum DataKey { EscrowBalance, PendingDeadline(u32), ExpiredFrom(u32), + ResolvedToFreelancer(u32), } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -291,6 +337,41 @@ fn mark_milestone_expired( #[contract] pub struct EscrowContract; +fn build_milestone_state(env: &Env, milestone: &Milestone) -> MilestoneState { + let (released_amount, refunded_amount) = match milestone.status { + MilestoneStatus::Released => (milestone.amount, 0), + MilestoneStatus::Refunded => (0, milestone.amount), + MilestoneStatus::Resolved => { + let to_freelancer: bool = env + .storage() + .instance() + .get(&DataKey::ResolvedToFreelancer(milestone.id)) + .unwrap_or(false); + if to_freelancer { + (milestone.amount, 0) + } else { + (0, milestone.amount) + } + } + _ => (0, 0), + }; + MilestoneState { + id: milestone.id, + deadline: milestone.deadline, + allocated_amount: milestone.amount, + released_amount, + refunded_amount, + remaining_amount: milestone.amount - released_amount - refunded_amount, + status: milestone.status, + completed: matches!( + milestone.status, + MilestoneStatus::Released | MilestoneStatus::Refunded | MilestoneStatus::Resolved + ), + client_approved: milestone.client_approved, + freelancer_approved: milestone.freelancer_approved, + } +} + #[contractimpl] impl EscrowContract { pub fn initialize( @@ -737,6 +818,9 @@ impl EscrowContract { } balance -= transfer_amount; env.storage().instance().set(&DataKey::EscrowBalance, &balance); + env.storage() + .instance() + .set(&DataKey::ResolvedToFreelancer(milestone_id), &release_to_freelancer); milestone.status = MilestoneStatus::Resolved; env.storage().instance().set(&DataKey::Milestone(milestone_id), &milestone); env.storage() @@ -914,6 +998,93 @@ impl EscrowContract { // --- State Getters --- + pub fn get_escrow_state(env: Env) -> Result { + let client: Address = env.storage().instance().get(&DataKey::Client).ok_or(Error::NotInitialized)?; + let freelancer: Address = env.storage().instance().get(&DataKey::Freelancer).ok_or(Error::NotInitialized)?; + let arbiter: Address = env.storage().instance().get(&DataKey::Arbiter).ok_or(Error::NotInitialized)?; + let token: Address = env.storage().instance().get(&DataKey::Token).ok_or(Error::NotInitialized)?; + let funded: bool = env.storage().instance().get(&DataKey::IsFunded).unwrap_or(false); + let remaining_balance: i128 = env.storage().instance().get(&DataKey::EscrowBalance).unwrap_or(0); + let ids: Vec = env.storage().instance().get(&DataKey::MilestoneIds).ok_or(Error::NotInitialized)?; + + let mut allocated_amount = 0i128; + let mut released_amount = 0i128; + let mut refunded_amount = 0i128; + let mut milestones = Vec::new(&env); + let mut has_disputed = false; + let mut has_approved = false; + let mut has_submitted = false; + let mut has_in_progress = false; + let mut has_expired = false; + let mut has_settled = false; + let mut all_settled = true; + + for i in 0..ids.len() { + let id = ids.get(i).unwrap(); + let milestone: Milestone = env.storage().instance().get(&DataKey::Milestone(id)).ok_or(Error::MilestoneNotFound)?; + let state = build_milestone_state(&env, &milestone); + allocated_amount += milestone.amount; + released_amount += state.released_amount; + refunded_amount += state.refunded_amount; + has_disputed |= milestone.status == MilestoneStatus::Disputed; + has_approved |= milestone.status == MilestoneStatus::Approved; + has_submitted |= milestone.status == MilestoneStatus::Submitted; + has_in_progress |= matches!( + milestone.status, + MilestoneStatus::InProgress | MilestoneStatus::Extended + ); + has_expired |= matches!( + milestone.status, + MilestoneStatus::Expired | MilestoneStatus::AutoExpired + ); + has_settled |= state.completed; + all_settled &= state.completed; + milestones.push_back(state); + } + + let status = if !funded { + EscrowStatus::Created + } else if has_disputed { + EscrowStatus::Disputed + } else if all_settled { + EscrowStatus::Completed + } else if has_settled { + EscrowStatus::PartiallySettled + } else if has_approved { + EscrowStatus::Approved + } else if has_submitted { + EscrowStatus::Submitted + } else if has_in_progress { + EscrowStatus::InProgress + } else if has_expired { + EscrowStatus::Expired + } else { + EscrowStatus::Funded + }; + + Ok(EscrowState { + client, + freelancer, + arbiter, + token, + allocated_amount, + released_amount, + refunded_amount, + remaining_balance, + funded, + status, + milestones, + }) + } + + pub fn get_milestone_state(env: Env, milestone_id: u32) -> Result { + if !env.storage().instance().has(&DataKey::Client) { + return Err(Error::NotInitialized); + } + let milestone: Milestone = env.storage().instance().get(&DataKey::Milestone(milestone_id)).ok_or(Error::MilestoneNotFound)?; + Ok(build_milestone_state(&env, &milestone)) + } + pub fn get_milestones(env: Env) -> Result, Error> { let ids: Vec = env.storage().instance().get(&DataKey::MilestoneIds).ok_or(Error::NotInitialized)?; let mut milestones = Vec::new(&env); diff --git a/contracts/contracts/escrow/src/test.rs b/contracts/contracts/escrow/src/test.rs index 70edc9d..b1af7ed 100644 --- a/contracts/contracts/escrow/src/test.rs +++ b/contracts/contracts/escrow/src/test.rs @@ -197,6 +197,115 @@ fn test_voluntary_refund() { assert_eq!(token_client.balance(&escrow.address), 0); } +#[test] +fn test_permissionless_state_queries_track_funding_release_and_refund() { + let setup = setup_test(); + let env = setup.env.clone(); + let milestones = vec![ + &env, + milestone(&env, 1, 100), + milestone(&env, 2, 200), + ]; + setup.escrow_client.initialize( + &setup.admin, + &setup.client, + &setup.freelancer, + &setup.arbiter, + &setup.token_address, + &milestones, + ); + + let created = setup.escrow_client.get_escrow_state(); + assert_eq!(created.client, setup.client); + assert_eq!(created.freelancer, setup.freelancer); + assert_eq!(created.arbiter, setup.arbiter); + assert_eq!(created.token, setup.token_address); + assert_eq!(created.allocated_amount, 300); + assert_eq!(created.released_amount, 0); + assert_eq!(created.refunded_amount, 0); + assert_eq!(created.remaining_balance, 0); + assert_eq!(created.status, EscrowStatus::Created); + + let event_count = env.events().all().filter_by_contract(&setup.contract_id).events().len(); + assert_eq!(setup.escrow_client.get_escrow_state(), created); + assert_eq!( + setup.escrow_client.get_milestone_state(&1).remaining_amount, + 100 + ); + assert_eq!(env.events().all().filter_by_contract(&setup.contract_id).events().len(), event_count); + + setup.escrow_client.fund(); + let funded = setup.escrow_client.get_escrow_state(); + assert_eq!(funded.status, EscrowStatus::Funded); + assert_eq!(funded.remaining_balance, 300); + + setup.escrow_client.start_milestone(&1); + setup.escrow_client.submit_milestone(&1); + setup.escrow_client.approve(&1); + assert_eq!( + setup.escrow_client.get_escrow_state().status, + EscrowStatus::Approved + ); + setup.escrow_client.release(&1, &setup.client); + + let partially_settled = setup.escrow_client.get_escrow_state(); + assert_eq!(partially_settled.status, EscrowStatus::PartiallySettled); + assert_eq!(partially_settled.released_amount, 100); + assert_eq!(partially_settled.refunded_amount, 0); + assert_eq!(partially_settled.remaining_balance, 200); + assert_eq!( + setup.escrow_client.get_milestone_state(&1).released_amount, + 100 + ); + + setup.escrow_client.refund(&2, &setup.freelancer); + let completed = setup.escrow_client.get_escrow_state(); + assert_eq!(completed.status, EscrowStatus::Completed); + assert_eq!(completed.released_amount, 100); + assert_eq!(completed.refunded_amount, 200); + assert_eq!(completed.remaining_balance, 0); + assert_eq!( + setup.escrow_client.get_milestone_state(&2).refunded_amount, + 200 + ); +} + +#[test] +fn test_state_query_reports_dispute_resolution_recipient_and_invalid_ids() { + let setup = setup_test(); + initialize_single_milestone(&setup, 150); + setup.escrow_client.fund(); + setup.escrow_client.start_milestone(&1); + setup.escrow_client.submit_milestone(&1); + setup.escrow_client.dispute(&1, &setup.client); + assert_eq!( + setup.escrow_client.get_escrow_state().status, + EscrowStatus::Disputed + ); + + setup.escrow_client.resolve_dispute(&1, &false); + let state = setup.escrow_client.get_escrow_state(); + assert_eq!(state.status, EscrowStatus::Completed); + assert_eq!(state.released_amount, 0); + assert_eq!(state.refunded_amount, 150); + assert_eq!(state.remaining_balance, 0); +} + +#[test] +#[should_panic(expected = "HostError: Error(Contract, #5)")] +fn test_state_query_rejects_nonexistent_milestone() { + let setup = setup_test(); + initialize_single_milestone(&setup, 150); + setup.escrow_client.get_milestone_state(&99); +} + +#[test] +#[should_panic(expected = "HostError: Error(Contract, #2)")] +fn test_state_query_rejects_uninitialized_escrow() { + let setup = setup_test(); + setup.escrow_client.get_escrow_state(); +} + #[test] fn test_dispute_and_resolve_to_freelancer() { let setup = setup_test(); @@ -232,6 +341,8 @@ fn test_dispute_and_resolve_to_freelancer() { assert_eq!(token_client.balance(&setup.freelancer), 400); assert_eq!(token_client.balance(&setup.client), 600); assert_eq!(escrow.get_milestones().get(0).unwrap().status, MilestoneStatus::Resolved); + assert_eq!(escrow.get_escrow_state().released_amount, 400); + assert_eq!(escrow.get_escrow_state().refunded_amount, 0); } #[test] diff --git a/docs/soroban-contract-events.md b/docs/soroban-contract-events.md index 364cce1..edbd829 100644 --- a/docs/soroban-contract-events.md +++ b/docs/soroban-contract-events.md @@ -38,6 +38,84 @@ Contract methods that can fail return `Result<_, Error>`. Soroban exposes the en Numeric values are append-only ABI values. If a new failure is added, append a new variant and never renumber an existing one. +## Permissionless state queries + +The escrow contract exposes `get_escrow_state()` and `get_milestone_state(milestone_id)` as read-only calls. They require no authorization and do not write storage or emit events. Call them against the escrow contract address on the same Stellar network as the contract; for example, use the Soroban RPC `simulateTransaction` method with a contract invocation and do not submit the simulated transaction. + +With a generated Soroban contract client, the invocations are: + +```rust +let escrow_state = escrow_client.get_escrow_state(); +let milestone_state = escrow_client.get_milestone_state(&1); +``` + +`get_escrow_state()` returns participants (`client`, `freelancer`, `arbiter`), the supported token contract address (`token`), the funding flag, aggregate amounts, current status, and a `milestones` array. `get_milestone_state()` returns the same milestone representation for one ID. Amounts are signed integers in the token's smallest units; convert for display using the token's decimals. `allocated_amount` is the sum of milestone allocations. `released_amount` is value transferred to the freelancer by `release` or dispute resolution; `refunded_amount` is value returned to the client by `refund` or dispute resolution. `remaining_amount` is the milestone allocation not yet settled. At escrow level, `remaining_balance` comes from the contract's `EscrowBalance` accounting and is zero before funding. The JSON below is a decoded representation (enum values are shown by their names). + +### Escrow status mapping + +The aggregate `status` uses this precedence, so mixed milestone states map deterministically: + +| Status | Meaning | +| --- | --- | +| `Created` | Escrow has not been funded. | +| `Disputed` | At least one milestone is disputed. | +| `Completed` | Every milestone is released, refunded, or resolved. | +| `PartiallySettled` | At least one milestone is settled and at least one is not. | +| `Approved` | No higher-priority state applies and at least one milestone is approved. | +| `Submitted` | No higher-priority state applies and at least one milestone is submitted. | +| `InProgress` | No higher-priority state applies and at least one milestone is in progress or extended. | +| `Expired` | No higher-priority state applies and at least one milestone is expired or auto-expired. | +| `Funded` | Funded; all milestones remain in an earlier state. | + +Milestone `status` remains the canonical detailed lifecycle value (`Created`, `Funded`, `InProgress`, `Submitted`, `Approved`, `Released`, `Refunded`, `Disputed`, `Resolved`, `AutoExpired`, `Expired`, `Extended`). `completed` is true only for `Released`, `Refunded`, and `Resolved`. + +### Example response + +```json +{ + "client": "G...", + "freelancer": "G...", + "arbiter": "G...", + "token": "C...", + "allocated_amount": 300, + "released_amount": 100, + "refunded_amount": 0, + "remaining_balance": 200, + "funded": true, + "status": "PartiallySettled", + "milestones": [ + { + "id": 1, + "deadline": 2000000000, + "allocated_amount": 100, + "released_amount": 100, + "refunded_amount": 0, + "remaining_amount": 0, + "status": "Released", + "completed": true, + "client_approved": true, + "freelancer_approved": false + }, + { + "id": 2, + "deadline": 2000000000, + "allocated_amount": 200, + "released_amount": 0, + "refunded_amount": 0, + "remaining_amount": 200, + "status": "Funded", + "completed": false, + "client_approved": false, + "freelancer_approved": false + } + ] +} +``` + +Generated Soroban clients expose typed `get_escrow_state` and `get_milestone_state` calls. For other clients, decode the returned Soroban `ScVal` using the contract's generated XDR schema; preserve integer amounts without converting to floating point. Treat `NotInitialized` (error 2) as an uninitialized/nonexistent escrow contract and `MilestoneNotFound` (error 5) as an invalid milestone ID. A malformed address, unknown contract, or RPC/network failure occurs before contract execution and is reported by the RPC layer, not as an escrow contract error. + +Frontend and backend consumers should treat these on-chain responses as authoritative for escrow and milestone state. Database/indexer data can be used for search and presentation, but should be reconciled with these contract views (or a verified ledger snapshot) before presenting balances as authoritative. All clients should use the same contract ABI, network, and ledger context when comparing results. + ## Events All standardized events use the PascalCase type names below in contract source and the equivalent snake_case event name in RPC/indexer storage. Every event includes `contract_id` as an indexed topic. `actor`, when present, is the wallet that initiated the action.