Skip to content

feat/Implement booking contract for managing reservations#58

Merged
respp merged 2 commits intoStellar-Rent:mainfrom
ussyalfaks:bookingManageReservation
Jun 3, 2025
Merged

feat/Implement booking contract for managing reservations#58
respp merged 2 commits intoStellar-Rent:mainfrom
ussyalfaks:bookingManageReservation

Conversation

@ussyalfaks
Copy link
Contributor

@ussyalfaks ussyalfaks commented May 30, 2025

StellarRent Logo

Pull Request | StellarRent

📋 Summary

This PR introduces the Application Binary Interface (ABI) for the BookingContract, a critical component of the StellarRent decentralized property rental platform. The ABI provides a standardized interface for frontend applications and other smart contracts to interact with the booking functionality on the Stellar blockchain using Soroban.

Close #45

🎯 Motivation

The booking contract needed a properly structured ABI to:

  • Enable seamless integration between the smart contract and frontend applications
  • Provide type safety for contract interactions
  • Document the contract interface for developers
  • Facilitate automated SDK generation for various programming languages

🔧 Changes Made

New Files

  • apps/stellar-contracts/booking_abi.json - Complete ABI specification for the BookingContract

ABI Structure

The ABI includes comprehensive definitions for:

📌 Functions (8 total)

Function Purpose Key Parameters
initialize Set up the contract None
check_availability Verify property availability property_id, start_date, end_date
create_booking Create new reservation property_id, user_id, dates, price
cancel_booking Cancel existing booking booking_id, user_id
get_booking Retrieve booking details booking_id
update_status Modify booking status booking_id, new_status, caller
get_property_bookings List property bookings property_id
set_escrow_id Link escrow transaction booking_id, escrow_id

📊 Data Types

BookingStatus Enum:

enum BookingStatus {
  Pending,
  Confirmed,
  Completed,
  Cancelled
}

Booking Struct:

struct Booking {
  id: u64                    // Unique booking identifier
  property_id: String        // Reference to property
  user_id: String           // Guest identifier
  start_date: u64           // Check-in timestamp
  end_date: u64             // Check-out timestamp
  total_price: i128         // Price in USDC
  status: BookingStatus     // Current booking state
  escrow_id: Option<String> // Optional escrow reference
}

⚠️ Error Types

  • InvalidDates - Date validation failures
  • InvalidPrice - Pricing errors
  • BookingOverlap - Double booking prevention
  • Unauthorized - Permission violations
  • InvalidStatus - Invalid status transitions
  • BookingNotFound - Missing booking errors

🌟 Key Features

1. Availability Management

  • Real-time availability checking
  • Overlap detection to prevent double bookings
  • Date validation ensuring logical booking periods

2. Booking Lifecycle

  • Complete state management from creation to completion
  • Status transitions with validation rules
  • Integration points for escrow services

3. Security & Authorization

  • User authentication for booking modifications
  • Owner-only cancellation rights
  • Secure escrow integration points

📚 Usage Example

// Check availability
const isAvailable = await contract.check_availability({
  property_id: "PROP123",
  start_date: 1704067200,
  end_date: 1704153600
});

// Create booking
const bookingId = await contract.create_booking({
  property_id: "PROP123",
  user_id: "USER456",
  start_date: 1704067200,
  end_date: 1704153600,
  total_price: 1000000000 // 100 USDC
});

🧪 Testing Considerations

The ABI supports comprehensive testing scenarios:

  • ✅ Availability conflict detection
  • ✅ Date validation edge cases
  • ✅ Status transition workflows
  • ✅ Authorization verification
  • ✅ Escrow integration points

🔗 Integration Points

This ABI enables integration with:

  • Frontend: Next.js application for user interactions
  • Backend: Node.js/Express API for business logic
  • Escrow: Trustless Work for secure payments
  • Database: Supabase for metadata storage

📖 Documentation

Comprehensive documentation available at:

  • Contract Overview: apps/stellar-contracts/contracts/booking/CONTRACT_OVERVIEW.md
  • Stellar Expert: Contract Explorer

🚀 Deployment Information

  • Network: Stellar Testnet
  • Contract ID: CB3ILSDNHL6TWZYZJAS4L27GLHNAGW4ISW6YXIBHGHL4QYI4JPLP6W3E
  • ABI Path: apps/stellar-contracts/booking_abi.json

✅ Checklist

  • ABI follows Soroban standards
  • All contract functions documented
  • Error types clearly defined
  • Data structures properly typed
  • Integration examples provided
  • Contract ID and network specified

Building the future of decentralized property rentals on Stellar! 🏠✨

Summary by CodeRabbit

  • New Features

    • Introduced a blockchain-based booking system for property reservations, enabling users to check availability, create, cancel, and manage bookings, as well as integrate escrow payments.
    • Added support for tracking booking status (Pending, Confirmed, Completed, Cancelled) and detailed booking information.
  • Documentation

    • Added comprehensive user and developer documentation outlining contract functionality, workflows, security considerations, and integration guidance.
  • Tests

    • Implemented extensive automated tests covering booking creation, availability checks, overlap prevention, cancellations, status updates, and error handling.
    • Included test snapshots to validate contract behavior and ledger state across key scenarios.
  • Chores

    • Added configuration files and build scripts to streamline development, testing, and deployment workflows.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 30, 2025

Walkthrough

This change introduces a new BookingContract smart contract for the Stellar blockchain (Soroban) to manage property reservations. It includes contract logic, ABI, documentation, configuration, a Makefile, comprehensive unit tests, and a suite of test ledger snapshots. The contract supports booking creation, availability checks, overlap prevention, status management, escrow integration, and cancellation.

Changes

File(s) Change Summary
apps/stellar-contracts/booking_abi.json Added ABI JSON for BookingContract with functions, types, and errors.
apps/stellar-contracts/contracts/booking/CONTRACT_OVERVIEW.md Added detailed contract overview and documentation.
apps/stellar-contracts/contracts/booking/Cargo.toml Added Rust package configuration for the booking contract.
apps/stellar-contracts/contracts/booking/Makefile Added Makefile for building, testing, formatting, and cleaning the contract.
apps/stellar-contracts/contracts/booking/src/lib.rs Implemented BookingContract logic, data structures, and public methods.
apps/stellar-contracts/contracts/booking/src/test.rs Added comprehensive unit tests for BookingContract functionality and error handling.
apps/stellar-contracts/contracts/booking/test_snapshots/test/*.json Added test ledger state snapshots for various booking scenarios (creation, overlap, cancellation, etc.).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant BookingContract
    participant EscrowContract

    User->>BookingContract: check_availability(property_id, start_date, end_date)
    BookingContract-->>User: availability (bool)

    User->>BookingContract: create_booking(property_id, user_id, start_date, end_date, total_price)
    BookingContract->>BookingContract: validate dates, check overlap
    BookingContract->>EscrowContract: initiate escrow (escrow_id)
    BookingContract-->>User: booking_id

    User->>BookingContract: cancel_booking(booking_id, user_id)
    BookingContract->>EscrowContract: trigger refund (if applicable)
    BookingContract-->>User: cancellation status

    User->>BookingContract: get_booking(booking_id)
    BookingContract-->>User: Booking details

    User->>BookingContract: update_status(booking_id, new_status, caller)
    BookingContract-->>User: updated Booking
Loading

Assessment against linked issues

Objective (Issue #) Addressed Explanation
Contract overview documentation present (#45)
BookingContract implements: check_availability, create_booking, cancel_booking, unique ID, overlap prevention (#45)
Booking struct and storage mappings, proper data structures (#45)
Escrow integration included in booking creation and cancellation logic (#45)
Comprehensive tests: creation, overlap, cancellation, edge cases, escrow (mocked) (#45)

Poem

In the blockchain burrow, a contract was spun,
For bookings and stays, and double-booking—none!
With tests that all pass and docs clear as day,
Escrow and dates keep trouble at bay.
A rabbit’s delight—reservations done right!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7a7825 and f6f76ac.

📒 Files selected for processing (2)
  • apps/stellar-contracts/contracts/booking/src/lib.rs (1 hunks)
  • apps/stellar-contracts/contracts/booking/src/test.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/stellar-contracts/contracts/booking/src/test.rs
  • apps/stellar-contracts/contracts/booking/src/lib.rs
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

♻️ Duplicate comments (2)
apps/stellar-contracts/contracts/booking/test_snapshots/test/test_invalid_price.1.json (1)

21-105: Storage keys match initial state
Snapshot only populates BOOKCOUNT, contract instance, and code—no bookings exist prior to InvalidPrice validation.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_booking_overlap_prevention.1.json (1)

6-11: Auth array length consistency
Matches the non-overlapping snapshot—ensure this count corresponds to the number of distinct contract calls recorded before snapshotting.

🧹 Nitpick comments (8)
apps/stellar-contracts/contracts/booking/Cargo.toml (2)

1-6: Consider enriching crate metadata
The package section currently contains minimal fields. Adding description, license, and authors (even if unpublished) will improve clarity and future maintainability.


27-29: Custom profile for logging
The release-with-logs profile enables debug assertions. Consider whether additional logging features from the SDK should be toggled here, or if this profile needs further customization.

apps/stellar-contracts/contracts/booking/CONTRACT_OVERVIEW.md (1)

1-305: Comprehensive and well-structured documentation!

The documentation provides excellent coverage of the contract's functionality, integration patterns, and usage examples. The CLI examples are particularly helpful for understanding contract interactions.

Consider addressing these minor improvements:

  • Fix the markdown formatting issues flagged by static analysis (loose punctuation marks)
  • Ensure error types mentioned in documentation match those defined in the ABI (e.g., "PropertyNotFound" vs actual ABI errors)
  • Consider using the bare URL formatting for the contract link on line 11 as suggested by markdownlint
🧰 Tools
🪛 LanguageTool

[uncategorized] ~73-~73: Loose punctuation mark.
Context: ... \ --end_date 1704153600 ``` - PROP1: Property ID to check. - `1704067200`: S...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~74-~74: Loose punctuation mark.
Context: ...1: Property ID to check. - 1704067200`: Start date (Unix timestamp - Jan 1, 202...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~75-~75: Loose punctuation mark.
Context: ...timestamp - Jan 1, 2024). - 1704153600: End date (Unix timestamp - Jan 2, 2024)...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~99-~99: Loose punctuation mark.
Context: ... --total_price 1000000000 ``` - PROP1: Property being booked. - `USER123`: Use...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~100-~100: Loose punctuation mark.
Context: ...OP1: Property being booked. - USER123: User making the booking. - 1704067200`...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~101-~101: Loose punctuation mark.
Context: ... User making the booking. - 1704067200: Check-in date. - 1704153600: Check-ou...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~102-~102: Loose punctuation mark.
Context: ...04067200: Check-in date. - 1704153600: Check-out date. - 1000000000`: Total p...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~103-~103: Loose punctuation mark.
Context: ...4153600: Check-out date. - 1000000000`: Total price in USDC (100 USDC with 7 de...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~124-~124: Loose punctuation mark.
Context: ...23 \ --user_id USER123 ``` - BOOK123: Booking ID to cancel. - `USER123`: User...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~125-~125: Loose punctuation mark.
Context: ...K123: Booking ID to cancel. - USER123`: User requesting cancellation (must matc...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~166-~166: To form a complete sentence, be sure to include a subject.
Context: ...ler <HOST_ADDRESS> ``` - --new_status can be `Pending`, `Confirmed`, `Completed`,...

(MISSING_IT_THERE)


[uncategorized] ~246-~246: Loose punctuation mark.
Context: ...h existing reservation. - InvalidDates: Start date is after end date or dates a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~247-~247: Loose punctuation mark.
Context: ...es are in the past. - PropertyNotFound: Referenced property doesn't exist. - `U...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~248-~248: Loose punctuation mark.
Context: ...ty doesn't exist. - UnauthorizedAction: User attempting action they don't have ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~249-~249: Loose punctuation mark.
Context: ...'t have permission for. - InvalidPrice: Negative or zero price provided. - `Boo...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~250-~250: Loose punctuation mark.
Context: ...zero price provided. - BookingNotFound: Referenced booking ID doesn't exist. - ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~251-~251: Loose punctuation mark.
Context: ...king ID doesn't exist. - InvalidStatus: Attempted invalid status transition. -...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~261-~261: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...selects check-in/check-out dates. 2. Guest creates booking: - Backend verifie...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

🪛 markdownlint-cli2 (0.17.2)

11-11: Bare URL used
null

(MD034, no-bare-urls)

apps/stellar-contracts/contracts/booking/src/lib.rs (5)

18-29: Consider using Address type for user identification.

While the Booking struct is well-designed, consider using Address instead of String for user_id to leverage Soroban's built-in authentication and ensure type safety.

pub struct Booking {
    pub id: u64,
    pub property_id: String,
-   pub user_id: String,
+   pub user_id: Address,
    pub start_date: u64,
    pub end_date: u64,
    pub total_price: i128,
    pub status: BookingStatus,
    pub escrow_id: Option<String>,
}

53-71: Optimize availability check with early validation.

The availability logic is correct, but consider validating the current timestamp to prevent checking availability for past dates.

pub fn check_availability(
    env: Env,
    property_id: String,
    start_date: u64,
    end_date: u64,
) -> bool {
    // Validate dates
    if start_date >= end_date {
        return false;
    }
+   
+   // Check if start date is in the past
+   let current_time = env.ledger().timestamp();
+   if start_date < current_time {
+       return false;
+   }

    // Get all bookings for this property
    let bookings = Self::get_property_bookings_internal(&env, property_id.clone());
    
    // Check for overlaps
    for booking in bookings.iter() {
        if booking.status != BookingStatus::Cancelled {
            // Check if dates overlap
            if !(end_date <= booking.start_date || start_date >= booking.end_date) {
                return false;
            }
        }
    }
    
    true
}

242-243: Implement proper authorization for update_status.

The TODO comment indicates incomplete authorization. This function should verify that only authorized entities (property owners, system administrators) can update booking status.

The current authorization is incomplete. Would you like me to help implement proper role-based authorization for status updates?

pub fn update_status(
    env: Env,
    booking_id: u64,
    new_status: BookingStatus,
    caller: Address,
) -> Booking {
-   // TODO: Add proper authorization check for host/system
    caller.require_auth();
+   
+   // Verify caller is authorized (property owner, system admin, etc.)
+   // This requires additional contract design for role management

143-145: Document escrow integration requirements.

The TODO comments indicate incomplete escrow integration. Consider documenting the expected escrow contract interface and integration points.

Would you like me to help design the escrow integration interface or create documentation for the required escrow contract interactions?


258-268: Consider adding state transition validation for business rules.

While the basic state transitions are correct, consider adding business rule validation (e.g., time-based restrictions for cancellations).

match (booking.status, new_status) {
    (BookingStatus::Pending, BookingStatus::Confirmed) |
    (BookingStatus::Confirmed, BookingStatus::Completed) |
    (BookingStatus::Pending, BookingStatus::Cancelled) |
    (BookingStatus::Confirmed, BookingStatus::Cancelled) => {
+       // Add time-based validation for cancellations
+       if new_status == BookingStatus::Cancelled {
+           let current_time = env.ledger().timestamp();
+           // Example: prevent cancellation within 24 hours of start
+           if booking.start_date.saturating_sub(current_time) < 86400 {
+               panic!("Cannot cancel booking within 24 hours of start date");
+           }
+       }
        booking.status = new_status;
        bookings_map.set(i, (id.clone(), booking.clone()));
        updated_booking = Some(booking.clone());
        booking_found = true;
    }
    _ => panic!("Invalid status transition"),
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 877e6d9 and f7a7825.

⛔ Files ignored due to path filters (1)
  • apps/stellar-contracts/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (20)
  • apps/stellar-contracts/booking_abi.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/CONTRACT_OVERVIEW.md (1 hunks)
  • apps/stellar-contracts/contracts/booking/Cargo.toml (1 hunks)
  • apps/stellar-contracts/contracts/booking/Makefile (1 hunks)
  • apps/stellar-contracts/contracts/booking/src/lib.rs (1 hunks)
  • apps/stellar-contracts/contracts/booking/src/test.rs (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_booking_not_found.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_booking_overlap_prevention.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_cancel_booking_success.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_cancel_booking_unauthorized.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_check_availability_empty.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_create_booking_success.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_get_property_bookings.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_initialize.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_invalid_dates.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_invalid_price.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_invalid_status_transition.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_non_overlapping_bookings.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_set_escrow_id.1.json (1 hunks)
  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_update_status.1.json (1 hunks)
🧰 Additional context used
🪛 LanguageTool
apps/stellar-contracts/contracts/booking/CONTRACT_OVERVIEW.md

[uncategorized] ~73-~73: Loose punctuation mark.
Context: ... \ --end_date 1704153600 ``` - PROP1: Property ID to check. - `1704067200`: S...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~74-~74: Loose punctuation mark.
Context: ...1: Property ID to check. - 1704067200`: Start date (Unix timestamp - Jan 1, 202...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~75-~75: Loose punctuation mark.
Context: ...timestamp - Jan 1, 2024). - 1704153600: End date (Unix timestamp - Jan 2, 2024)...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~99-~99: Loose punctuation mark.
Context: ... --total_price 1000000000 ``` - PROP1: Property being booked. - `USER123`: Use...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~100-~100: Loose punctuation mark.
Context: ...OP1: Property being booked. - USER123: User making the booking. - 1704067200`...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~101-~101: Loose punctuation mark.
Context: ... User making the booking. - 1704067200: Check-in date. - 1704153600: Check-ou...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~102-~102: Loose punctuation mark.
Context: ...04067200: Check-in date. - 1704153600: Check-out date. - 1000000000`: Total p...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~103-~103: Loose punctuation mark.
Context: ...4153600: Check-out date. - 1000000000`: Total price in USDC (100 USDC with 7 de...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~124-~124: Loose punctuation mark.
Context: ...23 \ --user_id USER123 ``` - BOOK123: Booking ID to cancel. - `USER123`: User...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~125-~125: Loose punctuation mark.
Context: ...K123: Booking ID to cancel. - USER123`: User requesting cancellation (must matc...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~166-~166: To form a complete sentence, be sure to include a subject.
Context: ...ler <HOST_ADDRESS> ``` - --new_status can be `Pending`, `Confirmed`, `Completed`,...

(MISSING_IT_THERE)


[uncategorized] ~246-~246: Loose punctuation mark.
Context: ...h existing reservation. - InvalidDates: Start date is after end date or dates a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~247-~247: Loose punctuation mark.
Context: ...es are in the past. - PropertyNotFound: Referenced property doesn't exist. - `U...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~248-~248: Loose punctuation mark.
Context: ...ty doesn't exist. - UnauthorizedAction: User attempting action they don't have ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~249-~249: Loose punctuation mark.
Context: ...'t have permission for. - InvalidPrice: Negative or zero price provided. - `Boo...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~250-~250: Loose punctuation mark.
Context: ...zero price provided. - BookingNotFound: Referenced booking ID doesn't exist. - ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~251-~251: Loose punctuation mark.
Context: ...king ID doesn't exist. - InvalidStatus: Attempted invalid status transition. -...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~261-~261: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...selects check-in/check-out dates. 2. Guest creates booking: - Backend verifie...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

🪛 markdownlint-cli2 (0.17.2)
apps/stellar-contracts/contracts/booking/CONTRACT_OVERVIEW.md

11-11: Bare URL used
null

(MD034, no-bare-urls)

🔇 Additional comments (61)
apps/stellar-contracts/contracts/booking/Cargo.toml (4)

7-10: Library configuration looks correct
Building as a cdylib and disabling doctests aligns with a WASM target for Soroban contracts.


14-16: Dev-dependencies are aligned
Including testutils for the Soroban SDK in dev-dependencies is appropriate for writing unit tests.


17-26: Release profile optimization
The release profile is configured for size (opt-level = "z"), overflow checks, and LTO, which is ideal for WASM performance and security.


11-13:

Details

✅ Verification successful

Pinning Soroban SDK dependency
Dependency on soroban-sdk = "22.0.0" is good; ensure consistency across all contract crates.

Run this script to confirm the SDK version is uniform:


🏁 Script executed:

#!/bin/bash
rg -n 'soroban-sdk = "[0-9]+\.[0-9]+\.[0-9]+"' -H apps/stellar-contracts/contracts

Length of output: 249


Soroban SDK version consistency verified
Both apps/stellar-contracts/contracts/booking/Cargo.toml and apps/stellar-contracts/contracts/property-listing/Cargo.toml pin soroban-sdk = "22.0.0". No further action needed.

apps/stellar-contracts/contracts/booking/Makefile (4)

5-7: Test target is well defined
Running cargo test after build is the correct approach for contract tests.


8-11: Build target lists resulting WASM
Invoking stellar contract build and then listing the .wasm artifacts provides immediate feedback on the output.


12-14: Formatting workflow
Using cargo fmt --all ensures code style consistency across the workspace.


15-16: Clean target is straightforward
cargo clean is sufficient to remove artifacts; consider whether removing test snapshots or logs is necessary here.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_booking_not_found.1.json (1)

1-108: Approve snapshot for "booking not found" test
The JSON ledger state is well-formed, uses protocol_version: 22, and initializes the booking count to zero. No unexpected entries are present.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_invalid_status_transition.1.json (1)

1-326: Approve snapshot for invalid status transition
This snapshot accurately captures a booking in Pending status and includes the necessary ledger entries to test invalid transitions.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_invalid_dates.1.json (1)

1-108: Approve snapshot for invalid dates test
The ledger configuration and BOOKCOUNT initialization are correct, aligning with the InvalidDates error scenario.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_check_availability_empty.1.json (5)

1-5: Correct generators configuration
The generators section properly initializes the contract address and nonce for the snapshot.


6-10: Auth entries reflect no prior invocations
An empty auth array indicates no signers were required before invoking check_availability. This aligns with an availability-only check.


11-20: Ledger metadata is consistent
Protocol version, TTLs, and network parameters match the contract’s requirements for test snapshots.


106-108: Empty events array is correct
No events are emitted for an availability check, so an empty list is expected.


21-105:

Details

❌ Incorrect review comment

Verify required storage keys are present
This snapshot includes only BOOKCOUNT, contract instance, and code entries. The contract implementation and other tests also reference a persistent BOOKINGS key, even when empty. Please confirm that omitting an empty BOOKINGS entry here won’t cause a missing-key error in check_availability.


🏁 Script executed:

#!/bin/bash
# Verify usage of the BOOKINGS key in the contract
rg -n '"BOOKINGS"' apps/stellar-contracts/contracts/booking/src/lib.rs

Length of output: 127


🏁 Script executed:

#!/bin/bash
# Retrieve the implementation of check_availability to inspect BOOKINGS usage
rg -n 'fn check_availability' -A 30 apps/stellar-contracts/contracts/booking/src/lib.rs

Length of output: 1036


🏁 Script executed:

#!/bin/bash
# Retrieve implementation of get_property_bookings_internal to inspect handling of missing storage entries
rg -n 'fn get_property_bookings_internal' -A 60 apps/stellar-contracts/contracts/booking/src/lib.rs

Length of output: 1327


Incorrect concern: check_availability doesn’t use the BOOKINGS symbol
check_availability calls get_property_bookings_internal(&env, property_id), which loads from storage().persistent().get(&property_id) and provides an empty-vector default—not from the BOOKINGS key. Omitting a BOOKINGS entry in the empty snapshot is expected and won’t trigger a missing-key error here.

Likely an incorrect or invalid review comment.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_invalid_price.1.json (4)

1-5: Correct generators configuration
Generators are set up identically to the availability snapshot, initializing address and nonce.


6-10: Auth entries consistent
No authorizations are listed, which is appropriate since no storage writes occur before the invalid price error is thrown.


11-20: Ledger metadata looks good
All ledger parameters (protocol version, timestamp, TTLs) are properly configured.


106-108: No events on error
An error snapshot should contain no events, consistent with the contract failing before emitting any.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_non_overlapping_bookings.1.json (8)

1-5: Generators are correctly initialized
Address and nonce setup matches other snapshots, ensuring a clean environment.


12-20: Ledger metadata is consistent
Timestamp, base reserve, and TTL settings are correctly applied for this test scenario.


21-199: Property-specific booking entries are accurate
The PROP1 key holds exactly two non-overlapping bookings with correct start/end dates, statuses, and pricing.


200-230: BOOKCOUNT is updated correctly
The booking counter increments to 2, reflecting the two persisted bookings.


231-276: Global BOOKINGS list is populated
The snapshot captures a top-level BOOKINGS vector mirroring the two bookings with correct IDs and maps.


277-323: Contract instance and code entries present
WASM hash and instance data are included, ensuring the contract context is complete.


324-329: No events emitted
An empty events array matches the expected behavior after state-changing calls but without event logging.


6-11:

Details

❓ Verification inconclusive

Auth array length differs from other snapshots
This snapshot lists 4 auth entries versus 3 in others; verify this aligns with the number of contract calls recorded prior to taking the snapshot in the test.


🏁 Script executed:

#!/bin/bash
# Count contract invocations to match auth entries
grep -R "invoke" -n apps/stellar-contracts/contracts/booking/src/test.rs | wc -l

Length of output: 82


🏁 Script executed:

#!/bin/bash
# Locate the non-overlapping bookings test to inspect contract call count
rg -n "test_non_overlapping_bookings" apps/stellar-contracts/contracts/booking

Length of output: 172


Verify auth entry count in test_non_overlapping_bookings snapshot
I wasn’t able to locate any invoke calls in the test harness—please double-check that you’re matching the actual contract invocation pattern (e.g. invoke_contract or host calls). Ensure the number of contract invocations in test_non_overlapping_bookings() (line 110 in apps/stellar-contracts/contracts/booking/src/test.rs) matches the length of the "auth" array in

  • apps/stellar-contracts/contracts/booking/test_snapshots/test/test_non_overlapping_bookings.1.json

If they don’t align, update either the test code or the snapshot to keep them in sync.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_initialize.1.json (8)

1-5: Generators section is correct
Initial address and nonce values follow the standard setup for snapshots.


6-10: Auth entries align with initialization
Three empty auth arrays correspond to the calls made during contract initialization in the test.


11-20: Ledger metadata valid
Protocol version, sequence number, timestamp, and TTLs are properly defined for the init test.


21-118: Initial booking entry matches initialize call
The PROP1 booking vector contains exactly one entry with correct ID, user, dates, price, and default Pending status.


126-155: BOOKCOUNT incremented to 1
The counter correctly reflects the single booking created during initialization.


157-267: BOOKINGS global list is populated
Top-level BOOKINGS vector mirrors the property booking entry, ensuring read APIs can retrieve all bookings.


268-323: Contract instance and code included
Instance and code entries are present to execute the initialized contract.


324-325: Empty events as expected
No events should fire during pure initialization.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_booking_overlap_prevention.1.json (7)

1-5: Generators setup is correct
Address and nonce values initialize a fresh test environment.


12-20: Ledger metadata validated
Timestamp, base reserve, and RPC parameters are correctly configured.


21-120: Existing booking entry for overlap test
The snapshot contains one booking with a date range that will conflict, correctly setting up the overlap-prevention scenario.


121-150: BOOKCOUNT reflects the single booking
Value 1 aligns with the one persisted booking for the overlap test.


157-266: Global BOOKINGS list entry is correct
One tuple in BOOKINGS vector ensures the overlap logic can detect conflicts.


269-323: Instance and code sections included
Completes the contract's snapshot context for the test.


324-326: No events emitted
Empty events array matches a failing overlap check that returns an error rather than emitting events.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_get_property_bookings.1.json (3)

23-119: Property booking list contains two entries
The "PROP1" contract_data vector correctly includes two booking objects (IDs 0 and 1) with matching start_date, end_date, status Pending, total_price, and escrow_id set to void. This aligns with the ABI’s expectation for get_property_bookings.


201-229: BOOKCOUNT reflects two bookings
The "BOOKCOUNT" persistent entry has u64: 2, accurately representing the number of bookings stored.


232-423: Global BOOKINGS mapping mirrors property entries
The separate "BOOKINGS" mapping lists the same two entries as [id, map] tuples, preserving consistency between the property‐scoped and global booking data structures.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_set_escrow_id.1.json (2)

136-155: BOOKCOUNT remains at 1 after escrow assignment
The "BOOKCOUNT" entry is u64: 1, confirming that setting an escrow ID does not affect the total booking count. TTL and ledger metadata are unchanged.


188-262: Escrow ID correctly updated in BOOKINGS mapping
In the "BOOKINGS" vector under key "BOOKINGS", the booking with id: 0 now uses the Option::Some union format—{"string":"ESCROW123"}—while the initial None variant is still represented as the bare string "void". This matches XDR’s JSON union conventions.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_create_booking_success.1.json (2)

24-49: Booking creation snapshot reflects correct initial booking
The "PROP1" entry holds one booking map with id: 0, the expected start_date/end_date, status Pending, total_price in i128, user_id "USER1", and escrow_id "void".


128-150: BOOKCOUNT updated to 1
The "BOOKCOUNT" persistent entry shows u64: 1, matching the single booking created.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_cancel_booking_unauthorized.1.json (3)

24-32: Property state unchanged on unauthorized cancellation
The "PROP1" entry still contains the original booking in Pending status with escrow_id "void", as no modifications should occur on failed authorization.


137-157: BOOKCOUNT remains at 1
The "BOOKCOUNT" entry correctly remains u64: 1, confirming no decrement on unauthorized cancellation.


168-192: BOOKINGS mapping unchanged for unauthorized attempt
The global "BOOKINGS" vector still lists the single booking in Pending state with escrow_id "void".

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_cancel_booking_success.1.json (3)

48-82: Property‐level bookings reflect cancellation
The "PROP1" entry now contains two booking objects: the first with status "Cancelled" and the second still "Pending", preserving other fields.


130-150: BOOKCOUNT remains accurate at 2
The "BOOKCOUNT" entry remains u64: 2, as cancellation should not remove the booking record count.


248-292: Global BOOKINGS mapping shows updated status
Within the global "BOOKINGS" vector, entry id: 0 is now "Cancelled" while id: 1 remains "Pending", mirroring the property‐scoped data.

apps/stellar-contracts/contracts/booking/test_snapshots/test/test_update_status.1.json (1)

1-449: LGTM! Test snapshot accurately captures booking status transitions.

The JSON test snapshot correctly captures the ledger state for testing the update_status function, showing a realistic booking lifecycle progression from "Confirmed" to "Completed". The data structure is consistent with the expected booking schema and properly represents the contract state changes.

apps/stellar-contracts/contracts/booking/src/test.rs (1)

1-405: Excellent comprehensive test coverage!

The test suite is well-structured and covers all critical functionalities including:

  • Contract initialization and basic operations
  • Booking creation and retrieval
  • Overlap prevention and availability checking
  • Authorization and cancellation logic
  • Status transition validation
  • Edge cases and error conditions

The tests properly use Soroban SDK testing utilities and follow good testing practices with clear setup, execution, and verification patterns.

apps/stellar-contracts/booking_abi.json (1)

1-242: Well-structured ABI with comprehensive interface definition.

The ABI properly defines all contract functions, custom types, and error conditions. The interface is complete and consistent with the documented functionality. The inclusion of deployment information (contract ID and network) is helpful for integration.

apps/stellar-contracts/contracts/booking/src/lib.rs (2)

1-6: LGTM! Clean imports and contract setup.

The #![no_std] attribute and Soroban SDK imports are correctly configured for blockchain deployment.


8-15: Well-designed booking status enum.

The enum provides clear state transitions for the booking lifecycle with appropriate derive attributes for Soroban contracts.

@respp
Copy link
Contributor

respp commented Jun 2, 2025

Hi, could you please you to show me your current output and tests?. Thanks.

@ussyalfaks
Copy link
Contributor Author

Hi, could you please you to show me your current output and tests?. Thanks.

Screenshot 2025-06-02 at 04 42 55 Screenshot 2025-06-02 at 04 41 06

Copy link
Contributor

@respp respp left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Excellent work! The contract implementation is very complete and functional. The effort and solid understanding of Soroban and the overall system design are evident. 🙌

📝 Only Minor Issues Detected:

⚠️ Warnings about register_contract being deprecated in the tests (does not affect current functionality).

⚠️ Warnings related to profiles in the workspace (does not impact performance or compilation).

⚠️ Minor error in the Makefile with the ls path (the build still works correctly).

🔍 These are cosmetic issues that do not affect the contract's functionality, so the PR is approved ✅. Congratulations on this great contribution to StellarRent! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement BookingContract for Managing Reservations

2 participants