Skip to content

feat: add RBAC, admin timelock, coverage enforcement, load testing and contract build fixes#268

Merged
Luluameh merged 1 commit into
LightForgeHub:mainfrom
Viv-90:main
May 31, 2026
Merged

feat: add RBAC, admin timelock, coverage enforcement, load testing and contract build fixes#268
Luluameh merged 1 commit into
LightForgeHub:mainfrom
Viv-90:main

Conversation

@Viv-90
Copy link
Copy Markdown
Contributor

@Viv-90 Viv-90 commented May 31, 2026

Overview

This PR resolves four platform issues while also addressing pre-existing compilation problems in the smart contract codebase

Contract Compilation Fixes

Before implementing the requested features, several pre-existing issues in contracts/src/lib.rs were resolved.

Changes

  • Removed duplicated start-session event emission logic from subscribe
  • Removed duplicated dispute-resolution logic from set_voucher_signing_key
  • Fixed mismatched delimiters introduced by a previous merge conflict
  • Removed corrupted duplicate code fragments preventing compilation

Multi-Admin Role-Based Access Control

Closes #256

Implemented a role hierarchy to separate administrative responsibilities and reduce operational risk.

Roles

SuperAdmin

Full administrative authority.

Capabilities include:

  • Grant roles
  • Revoke roles
  • Execute all administrative actions
  • Manage protocol configuration

FeeManager

Responsible for fee-related operations.

DisputeAdmin

Responsible for dispute management workflows.

Changes

Added:

  • roles.rs
  • Role storage management
  • Permission validation helpers
  • Role grant/revoke functionality
  • Role-related events

Events

  • RoleGranted
  • RoleRevoked

Administrative Timelock System

Closes #257

Implemented a two-day timelock for critical administrative operations.

Timelock Configuration

Delay:

172800 seconds (48 hours)

Protected Actions

Administrative operations now require:

  1. Proposal
  2. Waiting period
  3. Execution

Changes

Added:

  • timelock.rs
  • AdminAction enum
  • PendingAction storage model
  • Action proposal workflow
  • Delayed execution workflow

New Error

  • TimelockActive

Security Benefits

  • Prevents instant governance actions
  • Provides community visibility into pending changes
  • Reduces risk of compromised admin keys
  • Creates a review window for sensitive operations

CI Code Coverage Enforcement

Closes #255

Added automated code coverage reporting and CI enforcement.

CI Enhancements

Added coverage generation using:

cargo tarpaulin

Enforcement

CI now fails when line coverage drops below:

80%

Reporting

Generated artifacts include:

  • cobertura.xml

Documentation

Updated README with:

  • Coverage badge
  • Coverage workflow information

Load Testing Harness

Closes #254

Implemented a load-testing framework for validating contract behavior under realistic usage conditions.

Load Test Script

Added:

  • load_test.ts

Simulated Operations

The harness performs concurrent execution of:

  • start_session
  • settle_session
  • end_session

Scale

The test executes:

500+ sessions

Metrics Collected

  • Average gas/resource fees
  • Average latency
  • p95 latency
  • Error rate

CI Integration

Added:

  • load_test.yml

The workflow:

  1. Starts a local Soroban sandbox
  2. Deploys the contract environment
  3. Executes the load-testing harness
  4. Reports execution metrics

Security Model Updates

This PR introduces a layered administrative security model:

RBAC Layer

Controls who can perform administrative actions.

Timelock Layer

Controls when administrative actions can execute.

Together they provide:

  • Permission separation
  • Delayed execution safeguards
  • Improved governance transparency
  • Stronger protocol security

Summary by CodeRabbit

Release Notes

  • New Features

    • Added role-based access control system for administrators (SuperAdmin, FeeManager, DisputeAdmin).
    • Introduced timelock mechanism for critical administrative actions with 48-hour execution delay.
    • Experts can now initiate session cancellation and receive partial refunds.
  • Improvements

    • Streamlined and consolidated error handling for clearer feedback.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 31, 2026

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR introduces a multi-role access control system with timelock-gated admin actions, migrates all persistent storage from typed DataKey enum to compact symbol_short() keys, consolidates error variants, adds expert-initiated session cancellation, and refactors fee/protocol management through internal helpers with extended test coverage.

Changes

Role-Based Access Control & Admin Governance Infrastructure

Layer / File(s) Summary
Role and Timelock System Modules
contracts/src/roles.rs, contracts/src/timelock.rs
Introduces Role enum (SuperAdmin, FeeManager, DisputeAdmin) with role-check and role-management functions in roles.rs. Timelock system in timelock.rs defines AdminAction (fee/tier/pause updates), wraps actions in PendingAction with timestamp, enforces 172,800-second execution delay, and dispatches to internal handlers.
Contract Module Exports and Governance Initialization
contracts/src/lib.rs
Exports new roles and timelock modules, removes local Error enum, grants initial SuperAdmin role during initialization via persistent storage, and adds public wrappers (grant_role, revoke_role, has_role, propose_admin_action, execute_admin_action, is_paused) delegating to the governance subsystems.

Storage Refactoring and Contract Semantics Updates

Layer / File(s) Summary
Error Enum Consolidation
contracts/src/errors.rs
Consolidates error variants: renames BurnBpsExceedsFee = 34 to InsufficientBalance = 34, removes staking/subscription/voucher-specific errors, retains InvalidVoucher = 56, and adds TimelockActive = 57 for timelock enforcement.
Admin Helper Persistence Migration
contracts/src/admin.rs
Migrates rate-limit configuration and cooldown to symbol_short! keys ("lim_ledg", ("lst_act", caller)), approved-token whitelist to symbol_short!("app_toks"), stops publicly re-exporting Error, and updates error returns to Error::Unauthorized for cooldown/whitelist violations.
Crypto and Voucher Storage Migration
contracts/src/crypto.rs
Migrates voucher pubkey and nonce-consumption tracking to symbol_short!-based tuple keys ("exp_v_pk", "v_nonce"), updates voucher_message to append cloned expert address, removes DataKey imports.
Disputes: Cooldown Storage and Expert Cancellation
contracts/src/disputes.rs
Migrates expert cooldown from DataKey::* to symbol_short!-based keys ("cd_ledg", ("cd_until", expert)), adds cancel_session_by_expert enabling experts to cancel Active|Paused sessions with partial refund (computes claimable vs remaining, persists reason CID, applies MIN_SESSION_ESCROW thresholds, publishes event).
Governance and Session Counter Storage Migration
contracts/src/governance.rs, contracts/src/migrations.rs
Governance adds DEFAULT_REFERRAL_SESSION_LIMIT constant, migrates referral-limit to instance key symbol_short!("ref_lim"). Migrations updates V1→V2 counter lookup to symbol_short!("next_sid"), explicitly initializes new V2 fields (encrypted_notes_hash, paused_at, agency/rate/locking defaults), updates migration test.
Core Contract Storage Key Migration
contracts/src/lib.rs
Migrates distributed storage keys: heartbeat (symbol_short!("last_hb"), expert), platform stats (symbol_short!("tot_sess|tot_vol")), DEX router symbol_short!("dex_addr"), spending limits (symbol_short!("sk_sp_lim"), seeker), cancellation fee symbol_short!("canc_fee"), next session ID symbol_short!("next_sid"), cancellation reason (symbol_short!("canc_rsn"), session_id). Updates reader/writer functions, health checks, and expert profile writes to use cloned addresses.
Fee and Protocol Management Refactoring
contracts/src/lib.rs
Introduces pub(crate) internal helpers (set_fee_internal, set_fee_tiers_internal, pause_protocol_internal, resume_protocol_internal, resolve_dispute_internal), rewires public entry points to call internals, adds resolve_dispute_by_dispute_admin with role gating, updates error mappings in fee/treasury and fixed-price flows.
Event and Webhook Payload Updates
contracts/src/events.rs
Updates publish_event to convert webhook payload via IntoVal<Env, Val> trait before emission, changing serialization representation for off-chain relay.
Test Coverage and Validation
contracts/src/lib.rs
Extended test suite covers role-based access control (multi-admin assignment, unauthorized access), timelock enforcement (proposal/execution with delay), rate-limiting/token whitelist (try_*() patterns), voucher replay, webhook relay topic parsing, DEX integration, expert cancellation (partial refund validation).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • LightForgeHub/SkillSphere-Dapp#244: Modifies admin helper logic and expert-cancellation flow in contracts/src/admin.rs and contracts/src/disputes.rs with overlapping rate-limit cooldown and token whitelist semantics.
  • LightForgeHub/SkillSphere-Dapp#267: Updates referral-session-limit persistence and default behavior in contracts/src/governance.rs directly intersecting with this PR's governance storage migration.
  • LightForgeHub/SkillSphere-Dapp#245: Overlaps with disputes cooldown storage refactoring, crypto voucher tracking, and webhook publish_event envelope handling.

Poem

🐰 With roles and locks, the admin gate stands tall,
Symbol-short keys replace the typed Data-Call,
Two days to ponder ere dispatch takes flight,
Experts claim back their sessions in the night,
Fee management flows through paths true and bright!

🚥 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 accurately summarizes the main features added: RBAC, admin timelock, coverage enforcement, load testing, and contract build fixes align with the changeset.
Linked Issues check ✅ Passed The PR addresses all four linked issues: #256 (RBAC with roles.rs, role enums, grant/revoke), #257 (timelock.rs with 48-hour delay), #255 (coverage CI integration), and #254 (load testing harness).
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objectives: role system, timelock, storage key migrations, error updates, and new public entry points align with feature requirements.
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.

@Luluameh Luluameh merged commit 4b42cd8 into LightForgeHub:main May 31, 2026
1 check was pending
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.

Admin Action Timelock (2-Day Delay) Multi-Admin Role System Automated Test Coverage Reporting & Coverage Gate Contract Load Testing Harness

2 participants