Skip to content

feat: implement session top-up functionality to extend booking duration#57

Merged
Bosun-Josh121 merged 1 commit intoLightForgeHub:mainfrom
ikemHood:feature/graceful-session-extensions-33
Mar 28, 2026
Merged

feat: implement session top-up functionality to extend booking duration#57
Bosun-Josh121 merged 1 commit intoLightForgeHub:mainfrom
ikemHood:feature/graceful-session-extensions-33

Conversation

@ikemHood
Copy link
Copy Markdown
Contributor

@ikemHood ikemHood commented Mar 27, 2026

Graceful Session Extensions (Top-Ups)

Overview

This PR implements the requested "Graceful Session Extensions" feature for the payment-vault-contract. This functionality allows users to increase the maximum duration of a pending (or live) session by depositing additional funds without needing to disconnect or create a new booking ID.

Changes

  • contract.rs: Implemented top_up_session to handle authorization, state updates, and token transfers.
  • lib.rs: Exposed the top_up_session endpoint in the smart contract interface.
  • events.rs: Added the session_topped_up event to facilitate real-time tracking of session extensions.
  • test.rs: Included unit tests for successful top-ups and authorization failure cases.

Verification

  • Ran the full test suite for payment-vault-contract.
  • Status: 43 tests passed, 0 failed.
  • Specifically verified that 30-minute bookings can be successfully extended correctly calculating and pulling the additional 15-minute extra_cost.

Closes #33

Summary by CodeRabbit

  • New Features

    • Users can now extend pending bookings by adding additional session time with automatic cost calculation based on the booking rate.
    • Includes authorization checks and token transfer handling for session extensions.
  • Tests

    • Added test coverage for session top-up functionality, including authorization validation and state updates.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 27, 2026

📝 Walkthrough

Walkthrough

The PR implements a new top_up_session feature that enables users to extend their active booking duration mid-session by depositing additional funds. The implementation spans contract logic with validation, token transfer, booking state updates, event emission, and test coverage across four files.

Changes

Cohort / File(s) Summary
Core Implementation
contracts/payment-vault-contract/src/contract.rs
Added top_up_session entrypoint with authorization, contract pause, booking existence/status validation, overflow-safe cost calculation, token transfer, booking field updates (total_deposit, max_duration), and event emission.
Event Handling & Public Interface
contracts/payment-vault-contract/src/events.rs, contracts/payment-vault-contract/src/lib.rs
Added session_topped_up event function and exposed top_up_session public method that delegates to core contract logic.
Test Coverage
contracts/payment-vault-contract/src/test.rs
Added two test cases: successful top-up with balance and duration verification, and unauthorized user rejection.

Sequence Diagram

sequenceDiagram
    participant User
    participant Contract
    participant Storage
    participant TokenSystem
    participant EventLog

    User->>Contract: top_up_session(user, booking_id, additional_duration)
    Contract->>Contract: Validate contract not paused
    Contract->>Contract: Verify user authorization
    Contract->>Storage: Fetch booking by booking_id
    Contract->>Contract: Check booking exists & is Pending
    Contract->>Contract: Calculate extra_cost = rate_per_second × additional_duration
    Contract->>TokenSystem: Transfer extra_cost tokens from user to vault
    Contract->>Storage: Update booking.total_deposit += extra_cost
    Contract->>Storage: Update booking.max_duration += additional_duration
    Contract->>Storage: Persist updated booking
    Contract->>EventLog: Emit session_topped_up event
    EventLog-->>User: Event published
    Contract-->>User: Return Ok(())
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Hops with glee at extended sessions!
Time flows long when users call,
Top-ups extend the booking hall—
No disconnect, just more duration,
Tokens flow in celebration! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately summarizes the main change: implementing session top-up functionality to extend booking duration, which is the primary feature added.
Description check ✅ Passed The PR description covers the main changes (contract.rs, lib.rs, events.rs, test.rs) and includes verification results (43 tests passed), but lacks evidence as required by the template (screenshots, logs, or transaction hashes).
Linked Issues check ✅ Passed All requirements from issue #33 are implemented: top_up_session function handles authorization and state updates [contract.rs], endpoint exposed in contract interface [lib.rs], session_topped_up event added [events.rs], and tests cover successful top-ups and authorization failures [test.rs].
Out of Scope Changes check ✅ Passed All changes directly address issue #33 requirements: implementing session top-up functionality, state management, event emission, and corresponding test coverage. No unrelated modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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.

🧹 Nitpick comments (2)
contracts/payment-vault-contract/src/test.rs (2)

1452-1481: Consider adding balance assertions for robustness.

The test correctly validates that a non-owner cannot top up, but doesn't verify that no tokens were transferred. Adding balance assertions would strengthen the test.

💡 Optional enhancement
     let result = client.try_top_up_session(&other_user, &booking_id, &900);
     assert!(result.is_err());
+
+    // Verify no tokens were transferred
+    let initial_deposit = rate_per_second * (initial_duration as i128);
+    assert_eq!(token.balance(&client.address), initial_deposit);
+    assert_eq!(token.balance(&other_user), 40_000);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@contracts/payment-vault-contract/src/test.rs` around lines 1452 - 1481, Add
assertions in test_top_up_wrong_user_fails to verify no token transfer occurred:
capture balances (via token.balance_of or equivalent) for the payer
(other_user), the intended payee or vault, and optionally the original user
before calling client.try_top_up_session, then assert those balances are
unchanged after the failed try_top_up_session call and that result.is_err()
remains true; reference token.mint, token.balance_of, client.try_top_up_session
and booking_id to locate where to insert the pre- and post-call balance checks.

1406-1481: Consider adding tests for edge cases and started sessions.

The test suite covers the happy path and wrong-user rejection but omits several scenarios:

  1. Top-up after mark_session_started — This would confirm the intended "live session" behavior since started_at can be set while status is still Pending.
  2. Top-up on finalized/cancelled booking — Validates BookingNotPending error.
  3. Top-up with additional_duration = 0 — Validates InvalidAmount error.
  4. Top-up when contract is paused — Validates ContractPaused error.

Would you like me to generate these additional test cases?

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@contracts/payment-vault-contract/src/test.rs` around lines 1406 - 1481, Add
four tests around try_top_up_session: (1) test_top_up_after_mark_started —
create a booking, call mark_session_started on the booking (so started_at is set
while status remains Pending) then call try_top_up_session and assert it returns
Err (the live-session behavior you expect); (2)
test_top_up_on_finalized_or_cancelled — create a booking, call cancel_booking or
whatever transitions it to a non-Pending state, then call try_top_up_session and
assert it returns BookingNotPending; (3) test_top_up_zero_duration — create a
booking and call try_top_up_session with additional_duration = 0 and assert it
returns InvalidAmount; (4) test_top_up_when_paused — init client, create a
booking, pause the contract (use the contract pause method) then call
try_top_up_session and assert it returns ContractPaused; reuse existing helpers
(create_client, book_session, token.mint) and assert specific error variants
from try_top_up_session.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@contracts/payment-vault-contract/src/test.rs`:
- Around line 1452-1481: Add assertions in test_top_up_wrong_user_fails to
verify no token transfer occurred: capture balances (via token.balance_of or
equivalent) for the payer (other_user), the intended payee or vault, and
optionally the original user before calling client.try_top_up_session, then
assert those balances are unchanged after the failed try_top_up_session call and
that result.is_err() remains true; reference token.mint, token.balance_of,
client.try_top_up_session and booking_id to locate where to insert the pre- and
post-call balance checks.
- Around line 1406-1481: Add four tests around try_top_up_session: (1)
test_top_up_after_mark_started — create a booking, call mark_session_started on
the booking (so started_at is set while status remains Pending) then call
try_top_up_session and assert it returns Err (the live-session behavior you
expect); (2) test_top_up_on_finalized_or_cancelled — create a booking, call
cancel_booking or whatever transitions it to a non-Pending state, then call
try_top_up_session and assert it returns BookingNotPending; (3)
test_top_up_zero_duration — create a booking and call try_top_up_session with
additional_duration = 0 and assert it returns InvalidAmount; (4)
test_top_up_when_paused — init client, create a booking, pause the contract (use
the contract pause method) then call try_top_up_session and assert it returns
ContractPaused; reuse existing helpers (create_client, book_session, token.mint)
and assert specific error variants from try_top_up_session.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 018a0883-7ad3-4dfc-b974-dbfb6d962570

📥 Commits

Reviewing files that changed from the base of the PR and between 1a4ddef and 1e90aeb.

📒 Files selected for processing (4)
  • contracts/payment-vault-contract/src/contract.rs
  • contracts/payment-vault-contract/src/events.rs
  • contracts/payment-vault-contract/src/lib.rs
  • contracts/payment-vault-contract/src/test.rs

@Bosun-Josh121 Bosun-Josh121 merged commit a0795c8 into LightForgeHub:main Mar 28, 2026
2 checks passed
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.

Graceful Session Extensions (Top-Ups)

2 participants