Skip to content

Commit fb298d3

Browse files
authored
Merge pull request #1498 from priscaenoch/feature/1374-earnings-notinitialized-error
fix(earnings): replace admin() unwrap with typed NotInitialized error
2 parents b50f6e7 + 430fb61 commit fb298d3

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

contract/contracts/earnings/src/lib.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,14 @@ enum DataKey {
2020
/// | Code | Variant |
2121
/// |------|---------|
2222
/// | 1 | `AlreadyInitialized` |
23+
/// | 2 | `NotInitialized` |
2324
#[contracterror]
2425
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2526
pub enum Error {
2627
/// Code 1 – contract was already initialized.
2728
AlreadyInitialized = 1,
29+
/// Code 2 – admin key not present; contract was never initialized.
30+
NotInitialized = 2,
2831
}
2932

3033
#[contract]
@@ -42,7 +45,10 @@ impl Earnings {
4245
}
4346

4447
pub fn admin(env: Env) -> Address {
45-
env.storage().instance().get(&DataKey::Admin).unwrap()
48+
env.storage()
49+
.instance()
50+
.get(&DataKey::Admin)
51+
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized))
4652
}
4753

4854
pub fn record(env: Env, creator: Address, amount: i128) {

contract/contracts/earnings/src/test.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,23 @@ fn test_init_requires_admin_auth_without_persisting_state() {
7878
assert_eq!(client.admin(), admin);
7979
}
8080

81+
/// Calling admin() before init() returns a typed NotInitialized error instead
82+
/// of panicking on an unwrap of empty storage.
83+
#[test]
84+
fn test_admin_returns_not_initialized_before_init() {
85+
let env = Env::default();
86+
let contract_id = env.register_contract(None, Earnings);
87+
let client = EarningsClient::new(&env, &contract_id);
88+
89+
let result = client.try_admin();
90+
assert_eq!(
91+
result,
92+
Err(Ok(SorobanError::from_contract_error(
93+
Error::NotInitialized as u32,
94+
)))
95+
);
96+
}
97+
8198
// ── #319 – non-admin record reverts ──────────────────────────────────────────
8299

83100
/// Non-admin caller (no admin auth) must not be able to record earnings.

0 commit comments

Comments
 (0)