Skip to content

Conversation

@AnoukRImola
Copy link

@AnoukRImola AnoukRImola commented Jan 29, 2026


Feat(vault-contract): Add view functions, events, and ROI preview for v2 improvements

Close: #17

Description

This PR implements the Vault Contract v2 improvements as defined in the PRD,
transforming it from a minimalistic ROI-distribution contract into a fully
observable, dashboard-friendly, and indexer-compatible module.

Summary

  • Added getter/view functions for all vault state
  • Implemented ROI preview before claiming
  • Added VaultOverview for complete vault snapshots
  • Implemented ClaimEvent and AvailabilityChangedEvent for indexer integration
  • Refactored storage to use typed keys
  • Renamed price to roi_percentage for clarity
  • Added comprehensive test coverage (23 tests)

Changes

New Files
File: storage_types.rs
Description: Typed DataKey enum replacing raw string storage keys
────────────────────────────────────────
File: events.rs
Description: ClaimEvent and AvailabilityChangedEvent structs with emission
helpers
New View Functions

fn get_admin(env: Env) -> Address
fn is_enabled(env: Env) -> bool
fn get_roi_percentage(env: Env) -> i128
fn get_token_address(env: Env) -> Address
fn get_usdc_address(env: Env) -> Address
fn get_vault_usdc_balance(env: Env) -> i128
fn get_total_tokens_redeemed(env: Env) -> i128

Preview Function

fn preview_claim(env: Env, beneficiary: Address) -> ClaimPreview
Returns: token_balance, usdc_amount, roi_amount, vault_has_sufficient_balance,
claim_enabled

Vault Overview

fn get_vault_overview(env: Env) -> VaultOverview
Returns a complete snapshot of the vault state in a single call.

Events

  • ClaimEvent: Emitted on successful claim with beneficiary, tokens_redeemed,
    usdc_received, roi_percentage
  • AvailabilityChangedEvent: Emitted when admin toggles vault availability

Test Plan

  • All original tests pass (claim behavior unchanged)
  • Getter functions return correct values
  • preview_claim calculates ROI correctly
  • get_vault_overview returns complete snapshot
  • Events are emitted on claim and availability change
  • Edge cases covered (zero tokens, insufficient balance, disabled vault, high
    ROI)

Test Results

23 tests passing ✅
Captura desde 2026-01-29 13-40-07

Summary by CodeRabbit

Release Notes

  • New Features

    • Added event emissions for claims and availability changes to support external monitoring and indexing.
    • Introduced vault overview queries to retrieve complete configuration snapshots.
    • Added claim preview functionality to forecast potential claim outcomes without state changes.
    • Implemented ROI percentage-based claim calculations for improved financial accuracy.
    • Added admin-controlled vault availability toggling with authentication.
    • Introduced new getter functions to query vault configuration and state.
  • Tests

    • Expanded test coverage with comprehensive scenarios and snapshot validation.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link
Contributor

vercel bot commented Jan 29, 2026

@AnoukRImola is attempting to deploy a commit to the Trustless Work Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Jan 29, 2026

📝 Walkthrough

Walkthrough

Adds getter and view functions, event emission system, typed storage keys, and ROI preview capabilities to the Vault contract. Renames storage key "price" to "roi_percentage" and replaces string-based keys with a typed enum. Introduces ClaimEvent and AvailabilityChangedEvent for external tracking.

Changes

Cohort / File(s) Summary
Events & Storage Infrastructure
events.rs, storage_types.rs, lib.rs
Introduces ClaimEvent and AvailabilityChangedEvent types with emission helpers. Adds typed DataKey enum replacing string-based storage keys (Admin, Enabled, RoiPercentage, TokenAddress, UsdcAddress, TotalTokensRedeemed). Reorganizes public module exports to expose events and storage types.
Core Vault Contract Logic
vault.rs
Adds two new public data structures (VaultOverview, ClaimPreview) for state snapshots and preview functionality. Renames constructor parameter "price" to "roi_percentage" and updates storage initialization. Adds admin-controlled availability_for_exchange function with event emission. Reworks claim flow to use typed storage keys, compute USDC using ROI percentage, validate vault balance, track total redeemed tokens, and emit ClaimEvent. Introduces 7 new getter/view functions (get_admin, is_enabled, get_roi_percentage, get_token_address, get_usdc_address, get_vault_usdc_balance, get_total_tokens_redeemed), preview_claim, and get_vault_overview.
Test Suite
test.rs
Updates create_vault helper to use roi_percentage instead of price parameter. Extends coverage with 428 new lines including getter tests, preview tests, event emission tests, availability toggle tests, multiple claims tests, and edge-case scenarios. Adjusts test expectations to align with ROI percentage semantics.
Test Snapshots
test_snapshots/test/*.json
Adds 19 comprehensive snapshot fixtures covering: availability change events, claim events with varying ROI rates (6%, 100%), insufficient vault balance, disabled vault claims, multiple beneficiary claims, preview scenarios (basic, disabled, insufficient balance, zero tokens), getter function calls, vault overview queries, and vault deployment states. All snapshots use typed DataKey symbol-based storage keys instead of string keys.

Sequence Diagram

sequenceDiagram
    actor Client
    participant Vault as VaultContract
    participant Storage as Storage Keys<br/>(DataKey Enum)
    participant Events as Event Emitter

    rect rgba(100, 150, 200, 0.5)
    Note over Client,Events: Claim Flow with ROI & Event Emission
    Client->>Vault: claim(beneficiary)
    activate Vault
    Vault->>Storage: read(Enabled)
    Storage-->>Vault: enabled_flag
    alt Vault Disabled
        Vault-->>Client: Error
    else Vault Enabled
        Vault->>Storage: read(TotalTokensRedeemed)
        Storage-->>Vault: previous_total
        Vault->>Storage: read(RoiPercentage)
        Storage-->>Vault: roi_pct
        Note over Vault: Compute USDC = tokens × roi_pct
        Vault->>Storage: read(UsdcAddress)
        Storage-->>Vault: usdc_addr
        Note over Vault: Validate vault balance ≥ usdc_amount
        alt Insufficient Balance
            Vault-->>Client: Error
        else Sufficient Balance
            Vault->>Storage: write(TotalTokensRedeemed, new_total)
            Vault->>Events: emit_claim(ClaimEvent)
            Events-->>Vault: ✓
            Vault-->>Client: Success
        end
    end
    deactivate Vault
    end

    rect rgba(150, 100, 200, 0.5)
    Note over Client,Events: Availability Toggle with Event
    Client->>Vault: availability_for_exchange(admin, enabled)
    activate Vault
    Vault->>Storage: validate(admin)
    alt Not Admin
        Vault-->>Client: Error
    else Is Admin
        Vault->>Storage: write(Enabled, enabled)
        Vault->>Events: emit_availability_changed(AvailabilityChangedEvent)
        Events-->>Vault: ✓
        Vault-->>Client: Success
    end
    deactivate Vault
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • Feature/tokenize escrow #11: Introduces changes to Vault contract constructor and storage parameters (renaming price to roi_percentage), which directly impacts vault deployment APIs and wasm interactions affected by this PR.
  • Main #21: Modifies the same vault-contract crate components (lib.rs, vault.rs, test.rs), introducing or adjusting contract errors, storage keys, events, and public module exports with overlapping scope.

Poem

🐰 A vault so clear, with types so fair,
Events hop through the indexed air,
ROI whispers what tokens shall yield,
With storage keys properly sealed,
Getters galore for those who peek—
A contract robust, no longer meek! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(vault-contract): add view functions, events, and ROI' clearly and concisely summarizes the main changes: addition of view/getter functions, event emission support, and ROI-related improvements to the vault contract.
Linked Issues check ✅ Passed The PR implements all primary coding objectives from issue #17: getter functions (get_admin, is_enabled, get_roi_percentage, get_token_address, get_usdc_address, get_vault_usdc_balance, get_total_tokens_redeemed), preview_claim with ROI calculation, get_vault_overview snapshot, event emissions (ClaimEvent, AvailabilityChangedEvent), typed storage keys, ROI field renaming, and comprehensive test coverage.
Out of Scope Changes check ✅ Passed All code changes are directly aligned with issue #17 objectives. The PR introduces storage_types.rs (typed keys), events.rs (event definitions), new view functions, event emissions, renamed storage fields, and comprehensive tests—all within scope. No unrelated or extraneous changes 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 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

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

Copy link

@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: 1

🤖 Fix all issues with AI agents
In `@apps/smart-contracts/contracts/vault-contract/src/test.rs`:
- Around line 524-549: The test currently asserts any event was emitted, causing
false positives from token transfer events; update
test_availability_change_emits_event to filter env.events().all() by the vault
contract address (vault.address) and the first topic symbol matching "avail"
using Symbol::try_from_val/TryFromVal on topics.get(0), then assert that the
filtered list is non-empty; follow the same pattern used for claim events
(filtering by vault.address and topic "claim") to locate the specific vault
event.
🧹 Nitpick comments (2)
apps/smart-contracts/contracts/vault-contract/src/vault.rs (2)

60-80: Consider validating roi_percentage range in the constructor.

The roi_percentage parameter accepts any i128 value, including negative values (which would penalize claimants) or extremely large values (which could cause overflow in the calculation token_balance * (100 + roi_percentage)).

Consider adding validation to ensure sensible bounds:

💡 Suggested validation
     pub fn __constructor(
         env: Env,
         admin: Address,
         enabled: bool,
         roi_percentage: i128,
         token: Address,
         usdc: Address,
     ) {
+        // Validate ROI percentage is within reasonable bounds
+        if roi_percentage < 0 || roi_percentage > 1000 {
+            panic!("ROI percentage must be between 0 and 1000");
+        }
+
         env.storage().instance().set(&DataKey::Admin, &admin);

171-171: Consider extracting ROI calculation to a helper function (optional).

The USDC amount calculation (token_balance * (100 + roi_percentage)) / 100 is duplicated in claim() (line 171) and preview_claim() (line 303). Extracting this to a private helper would improve maintainability:

♻️ Optional: Extract helper function
impl VaultContract {
    /// Calculates the USDC amount for a given token balance and ROI percentage.
    fn calculate_usdc_payout(token_balance: i128, roi_percentage: i128) -> i128 {
        (token_balance * (100 + roi_percentage)) / 100
    }
    
    // Then use in claim():
    // let usdc_amount = Self::calculate_usdc_payout(token_balance, roi_percentage);
    
    // And in preview_claim():
    // let usdc_amount = if token_balance > 0 {
    //     Self::calculate_usdc_payout(token_balance, roi_percentage)
    // } else { 0 };
}

Also applies to: 302-303

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.

Vault Contract v2 Improvements

1 participant