Skip to content

fix: get_portfolio panics on non-existent portfolio ID instead of returning typed error #62

Description

@grantfox-oss

Problem

In contracts/src/lib.rs, get_portfolio calls .unwrap() directly on the storage lookup. If called with a non-existent portfolio ID, the contract aborts with a panic instead of returning a meaningful error.

Worse, check_rebalance_needed and execute_rebalance also call get_portfolio with user-supplied portfolio_id and unwrap the result — so any call with an invalid ID panics the entire transaction with no recoverable error. This is inconsistent with the rest of the contract, which uses typed Error enum variants for all other failure modes.

Proposed Fix

1. Add PortfolioNotFound error variant

In contracts/src/types.rs, add a new variant to the Error enum:

pub enum Error {
    // ... existing variants
    PortfolioNotFound = 11,
}

2. Replace .unwrap() with proper error handling

In contracts/src/lib.rs, update get_portfolio:

fn get_portfolio(env: &Env, portfolio_id: u64) -> Result<Portfolio, Error> {
    env.storage()
        .persistent()
        .get(&DataKey::Portfolio(portfolio_id))
        .ok_or(Error::PortfolioNotFound)
}

3. Update callers

check_rebalance_needed and execute_rebalance must handle the PortfolioNotFound result instead of unwrapping.

Files to modify

  • contracts/src/types.rs — add PortfolioNotFound variant
  • contracts/src/lib.rs — update get_portfolio, check_rebalance_needed, execute_rebalance
  • contracts/src/test.rs — add tests

Acceptance Criteria

  • Add PortfolioNotFound = 11 to Error enum in types.rs
  • get_portfolio returns Result<Portfolio, Error> using .ok_or(Error::PortfolioNotFound)?
  • check_rebalance_needed and execute_rebalance handle the PortfolioNotFound result
  • Test test_get_portfolio_not_found — calls get_portfolio with a non-existent ID, asserts correct error
  • Test test_execute_rebalance_portfolio_not_found — verifies error propagates cleanly from execute_rebalance

Affected Area

Smart Contract

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendBackend relatedbugSomething isn't workinghelp wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions