Skip to content

Conversation

@saiintbrisson
Copy link
Collaborator

@saiintbrisson saiintbrisson commented Apr 6, 2025

Torus Network v0.5 Changelog

This release introduces major architectural changes to enable decentralized economic relationships, improved governance flexibility, and preparation for off-chain service integration. The changes span several months of development focused on creating a more sophisticated and scalable network.

Major Features

Permission System (permission0 pallet)

A comprehensive permission framework that revolutionizes how agents interact economically within the network:

  • Agents can now share their token emissions with contributors through recursive permission trees. Supports percentage-based streams or fixed amounts, with flexible distribution controls (manual, automatic threshold, scheduled).
  • Permissions can be managed by arbiters (multi-sig groups) for enhanced security and decentralized control.
  • Governance powers are now granular with specific permissions for application review, whitelist management, and penalty control. Replaces the old curator system with a more flexible approach.
  • Built-in protections against double-spending and infinite recursion ensure tokenomics.

Namespace System

A hierarchical naming system that functions as decentralized DNS/capability listing for agent services:

  • Agents can create dot-separated paths like agent.alice.api.v2 to organize their off-chain services.
  • Owning a namespace gives control over all sub-paths, enabling structured delegation of services.
  • Base fees go to treasury while refundable deposits incentivize efficient storage use.
  • Namespaces can be delegated through the permission system, enabling complex service architectures.

Agent Management Improvements

  • Agent names are automatically converted to namespace-compliant format (lowercase, no spaces) during the upgrade.
  • Curators can now freeze/unfreeze agents, adding a new governance tool for spam control.
  • Agent metadata updates now have cooldowns to prevent spam and ensure stability.
  • Burn parameters adjusted for better economic balance during high registration activity.

Economic Enhancements

  • All transaction fees now flow to the treasury instead of being burned, providing sustainable funding for network development.
  • Only whitelisted agents receive emissions, ensuring quality participants chosen by the DAO are rewarded.
  • Permission holders can dynamically adjust how they distribute received emissions.
  • Distribution remainders are now properly accumulated, preventing token loss.

Developer Experience

  • Proof-of-work based faucet for obtaining testnet tokens, preventing abuse while maintaining accessibility.
  • Comprehensive docs for all pallets now auto-published to GitHub Pages.
  • New torus0_namespacePathCreationCost RPC for calculating namespace fees upfront.
  • Integrated coverage reporting with cargo xtask coverage for maintaining code quality.

Bug Fixes & Safety Improvements

  • Critical fix ensuring stakes are properly refunded before clearing storage during de-registration.
  • Banned arithmetic side effects throughout the runtime, using saturating operations to prevent overflows.
  • All agents now automatically delegate weights to allocators, simplifying the onboarding process.

Governance Changes

  • Instead of all-or-nothing curator status, specific permissions can be granted.
  • Improved with better event emissions and clearer execution flows.
  • Now integrated with the permission system for more flexible control.

Infrastructure

  • Enhanced GitHub Actions for automated testing, documentation, and Docker builds.
  • Added development container configuration for consistent environments.
  • Migrated CI infrastructure for better performance.

This release represents a fundamental evolution of the Torus Network, creating the foundation for a truly decentralized economy where agents can form complex relationships, share resources, and organize their services in meaningful ways.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive permission system enabling emission, curator, and namespace permissions with fine-grained control, revocation, and enforcement.
    • Added namespace management: users can create and delete hierarchical namespaces with associated economic and permission models.
    • Added a testnet-only faucet feature allowing users to obtain test tokens via proof-of-work.
    • Expanded governance with freezing controls for agent/namespace registration and more granular role/permission management.
    • Added new RPC endpoints for permission and namespace queries.
    • Enhanced agent management with update cooldowns and namespace integration.
  • Improvements

    • Unified numeric types for emission calculations, improving precision and consistency.
    • Refined governance proposal lifecycle, voting, and reward distribution with improved type safety and fixed-point math.
    • Strengthened access controls and permission checks across emission, governance, and agent operations.
    • Improved documentation, developer guides, and user manuals for new features and workflows.
    • Expanded benchmarking and test coverage for new and existing modules.
  • Bug Fixes

    • Fixed edge cases in emission and permission logic, including overflow handling and delegation validation.
    • Addressed governance and agent update race conditions with improved cooldown and permission enforcement.
  • Chores

    • Updated dependencies, development environment, CI workflows, and added new workspace members for modularity.
    • Upgraded Nix flake and build tooling for improved developer experience.
  • Documentation

    • Added detailed docs covering permission system, namespaces, emission mechanics, governance structure, deployment, and developer tooling.
  • Style/Refactor

    • Refactored imports, code organization, and type usage for clarity and maintainability.
    • Removed deprecated benchmarking and test files, replacing them with updated implementations.

steinerkelvin and others added 19 commits February 6, 2025 18:26
Adds docstrings to most storage values and core functions. Closes
CHAIN-45.

---------

Co-authored-by: Luiz Carvalho <[email protected]>
Removes unused storage values from Commune times.

Storage values removed:
* `MinAllowedWeights`,
* `MaxAllowedWeights`,
* `MinStakePerWeight`,
* `RegistrationBlock` (in favor of `registration_block` within the Agent
value).
 
Fields removed from `GlobalParamsData`:
* `max_allowed_weights`,
* `min_stake_per_weight`.
Updates weight control code to better handle the current state. This
means all agents will automatically delegate weights to the allocator.
Closes CHAIN-69.
This is a large one. We've been facing issues with the precision
provided by `substrate-fixed` types for a while now.

This commit drops this dependency in favor of the SDK's provided `Fixed`
types, which handle 18 decimals of precision correctly for most cases.
The change required various tweaks to how we test things. I also
expanded coverage for the emission code.
Improves coverage for some governance files.
Updates the README and creates a new CONTRIBUTING.md.
This PR adds the `Docker build and push xtask cli tool` action.  
  
When code that changes anything related to the xtask is pushed to the
branch `dev` or `main` this action builds a docker image and publishes
it on github packages.
  
The image tag is `ghcr.io/renlabs-dev/torus-xtask:{commit small sha}`
with the addition of `ghcr.io/renlabs-dev/torus-xtask:latest` if it's
pushed to `main`.

Closes CHAIN-71
Closes CHAIN-66

---------

Co-authored-by: Luiz Carvalho <[email protected]>
This is the first version for the permission0 pallet. Effectively
implements emission recursion.

---------

Co-authored-by: devwckd <[email protected]>
devwckd and others added 10 commits April 9, 2025 09:20
…n` branch (#93)

Adds a CI task that generates the pallet docs and uploads them to
[github
pages](http://renlabs-dev.github.io/torus-substrate/pallet_torus0)
Closes CHAIN-75
This PR adds the faucet pallet.

Closes CHAIN-85
Creates a new curator scope for the permission0 system. This change
supersedes the `Curators` storage value in the governance pallet.

A new extrinsic was added to `permission0`: 
```rust
pub fn grant_curator_permission(
	origin: OriginFor<T>,
	grantee: T::AccountId,
	flags: u32,
	cooldown: Option<BlockNumberFor<T>>,
	duration: PermissionDuration<T>,
	revocation: RevocationTerms<T>,
) ;
```

For now, only the sudo (root) key is allowed to grant new permissions,
which we will do through a multisig dispatch. Future versions will allow
curators to re-delegate permissions. The new extrinsic allows setting
different sub-permissions for curator actions:

```rust
        /// Permission to review and process agent applications
        const APPLICATION_REVIEW = 0b0000_0010;
        /// Permission to manage the whitelist (add/remove accounts)
        const WHITELIST_MANAGE   = 0b0000_0100;
        /// Permission to apply penalty factors to agents
        const PENALTY_CONTROL    = 0b0000_1000;
```

The value for `0b1` is reserved for future use and internally assigned
as `ROOT`.

The `flags` field is a bitmask, so OR the different flags together to
get your very own personalized permission.

Finally, I removed the old extrinsics for curators in the governance
pallet.
# Pull Request Checklist

Before submitting this PR, please make sure:

- [ ] You have run `cargo clippy` and addressed any warnings
- [ ] You have added appropriate tests (if applicable)
- [ ] You have updated the documentation (if applicable)
- [ ] You have reviewed your own code
- [ ] You have updated changelog (if applicable)

## Description

Please provide a brief description of the changes in this PR.

## Related Issues

Please link any related issues here
- Add CLAUDE.md with repository guidance for Claude Code assistant
- Standardize shell code blocks to use 'sh' instead of 'bash'
- Add spell checker words to VS Code settings
- Simplify README project description for clarity
- Add temporary files pattern to .gitignore

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
saiintbrisson and others added 5 commits June 20, 2025 14:19
After discussing how the emissions will be initially used, it was clear
to us that there are no cases where it makes sense to delegate emissions
permission to another agent. In this case, the best way to delegate is
to itself, which allows the agent to control how the emissions will flow
and edit the targets at will.
Adds a doc containing the steps needed to deploy the runtime.
This change updates the burn parameters as well as namespace fees.

Closes CHAIN-101.
devwckd and others added 5 commits June 24, 2025 15:34
This patch prevents a registered agent from de-registering the agent
entry (`agent.<name>`) through the `delete_namespace` extrinsic.
We are getting ready for the mainnet release on July 7th. This change
finishes the name porting logic converting agent names to complying
namespace names, by lowering and removing whitespace from the names.
@saiintbrisson saiintbrisson marked this pull request as ready for review July 7, 2025 13:52
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: 36

🔭 Outside diff range comments (3)
pallets/permission0/src/migrations.rs (1)

1-2: Blank migration module — add a stub or drop the file

An entirely empty file triggers missing_docs/dead_code lints and increases noise. Either delete it until the first migration is needed, or add a doc comment and a stub such as:

//! Storage migrations for `permission0`.  
//! TODO: implement when upgrading storage version.

#[cfg(feature = "try-runtime")]
pub fn pre_migrate() -> Result<(), &'static str> { Ok(()) }

pub fn migrate<T: frame_system::Config>() -> frame_support::weights::Weight {
    // no-op
    0
}
pallets/governance/tests/voting.rs (1)

115-116: Test name is misleading.

The test is named global_proposal_is_refused_correctly but it actually tests vote removal functionality. The proposal remains in Open status after votes are removed.

-fn global_proposal_is_refused_correctly() {
+fn votes_can_be_removed_from_open_proposal() {
pallets/governance/src/application.rs (1)

159-165: Handle the refund transfer result

The transfer result is being ignored with let _. If the refund fails (e.g., due to account issues), it should be handled appropriately or at least logged.

Consider handling the transfer result:

-    // Give the application fee back to the payer key.
-    let _ = <T as crate::Config>::Currency::transfer(
+    // Give the application fee back to the payer key.
+    <T as crate::Config>::Currency::transfer(
         &crate::DaoTreasuryAddress::<T>::get(),
         &application.payer_key,
         application.cost,
         ExistenceRequirement::AllowDeath,
-    );
+    ).map_err(|_| crate::Error::<T>::RefundFailed)?;

Alternatively, if refund failures should not block application acceptance, emit an event to notify about the failed refund.

♻️ Duplicate comments (1)
pallets/emission0/api/Cargo.toml (1)

9-10: Same unstable [lints] table issue as noted above

The concern about requiring nightly Cargo applies here as well.

🧹 Nitpick comments (55)
.github/CODEOWNERS (1)

1-1: Catch-all rule appears first — confirm no precedence issue

GitHub picks the last matching pattern, so placing the * rule at the top is usually fine, but double-check that any more-specific rules that follow are not unintentionally shadowed later in the file.

node/src/main.rs (1)

1-1: Global result_large_err suppression may hide real problems

Disabling this lint for the entire file masks legitimate oversized Result error types. Prefer narrowing the #[allow] to the specific function (or refactor the error enum) instead of a crate-level blanket allow.

pallets/torus0/Cargo.toml (1)

28-28: Empty testnet feature added.

The empty testnet feature is added but not populated. Consider documenting what this feature is intended for.

.github/workflows/build-docs.yml (1)

7-7: Fix trailing spaces.

Static analysis detected trailing spaces that should be removed for cleaner YAML formatting.

-    branches:
-      - main
-    
+    branches:
+      - main
+
-        uses: Swatinem/rust-cache@v2
-      
+        uses: Swatinem/rust-cache@v2
+

Also applies to: 20-20

pallets/torus0/api/src/api.rs (1)

1-1: Consider addressing the clippy allow directive.

The #![allow(clippy::multiple_bound_locations)] directive suppresses warnings about generic bounds in multiple locations. Consider restructuring to avoid this if possible.

docs/deploy.md (1)

22-22: Fix grammatical error: missing comma after introductory phrase.

-> As of april 9th 2025 the try-runtime cli is broken, install the fork by running `cargo install --git https://github.com/renlabs-dev/try-runtime-cli --locked`.
+> As of april 9th 2025, the try-runtime cli is broken, install the fork by running `cargo install --git https://github.com/renlabs-dev/try-runtime-cli --locked`.
pallets/governance/src/voting.rs (1)

5-5: Consider expanding the documentation for public voting APIs.

While the added documentation is accurate, these public functions would benefit from more comprehensive docs including parameter descriptions, error conditions, and possibly usage examples.

For example:

-/// Casts a vote on behalf of a voter.
+/// Casts a vote on behalf of a voter.
+///
+/// # Arguments
+/// * `voter` - The account casting the vote
+/// * `proposal_id` - The ID of the proposal being voted on
+/// * `agree` - Whether the vote is in favor (true) or against (false)
+///
+/// # Errors
+/// * `ProposalNotFound` - If the proposal doesn't exist
+/// * `ProposalClosed` - If the proposal is no longer open for voting
+/// * `AlreadyVoted` - If the voter has already voted on this proposal
+/// * `InsufficientStake` - If the voter has no stake
+/// * `VoterIsDelegatingVotingPower` - If the voter is delegating and has no delegated stake

Also applies to: 56-56, 82-82, 91-91

pallets/permission0/tests/fixed.rs (1)

1-218: Well-structured test suite for fixed emission permissions!

The tests provide good coverage of the permission lifecycle including:

  • Balance requirements
  • Permission creation and reservation
  • Manual and automatic execution
  • Single execution enforcement

Consider adding a constant for the weight distribution value:

+const FULL_WEIGHT: u16 = u16::MAX;
+const HALF_WEIGHT: u16 = u16::MAX / 2;

 vec![(agent_0, u16::MAX)],
+vec![(agent_0, FULL_WEIGHT)],

 vec![(agent_1, u16::MAX / 2), (agent_2, u16::MAX / 2)],
+vec![(agent_1, HALF_WEIGHT), (agent_2, HALF_WEIGHT)],
pallets/governance/api/src/lib.rs (1)

14-24: API extensions align well with governance enhancements!

The new methods provide clean interfaces for:

  • Allocator enumeration via iterator
  • Permission checks for namespace/agent operations
  • Benchmarking support with proper feature gating

The can_create_namespace and can_register_agent methods follow similar patterns (checking frozen state + whitelist). If more such permission checks are added in the future, consider introducing a generic permission check pattern to reduce duplication in the implementation.

.github/workflows/check.yml (1)

54-59: Consider re-enabling basic tests alongside coverage.

The original cargo test step is commented out in favor of coverage testing. Consider running both basic tests (for faster feedback) and coverage tests (for detailed reporting) in parallel or sequence.

-      # - name: Run tests
-      #   env:
-      #     RUST_BACKTRACE: 1
-      #     SKIP_WASM_BUILD: 1
-      #   run: cargo test
+      - name: Run tests
+        if: ${{ !steps.findPr.outputs.number }}
+        env:
+          RUST_BACKTRACE: 1
+          SKIP_WASM_BUILD: 1
+        run: cargo test
pallets/emission0/tests/weights.rs (2)

26-30: Address commented-out assertions.

Several assertions for regain_weight_control are commented out with TODO notes. This suggests incomplete feature implementation or testing.

Consider creating a tracking issue for re-enabling weight control features or provide a timeline for when these tests should be uncommented.

Also applies to: 53-61


65-65: Remove unreachable code warning suppression.

The #[allow(unreachable_code)] attribute suggests there might be unreachable code in the test. Consider reviewing the test logic to eliminate unreachable paths instead of suppressing the warning.

pallets/permission0/tests/lifetime.rs (1)

174-188: Consider extracting the helper function.

The grant_invalid closure is useful for testing invalid configurations. Consider extracting it to a test utility function for reuse across other test files.

pallets/emission0/src/weight_control.rs (1)

103-106: Consider improving error clarity.

While the allocator check is appropriate, returning WeightControlNotEnabled might be confusing since the feature is enabled but the user lacks permissions. Consider a more specific error like NotAnAllocator.

-    if <T::Governance>::ensure_allocator(&acc_id).is_err() {
-        return Err(crate::Error::<T>::WeightControlNotEnabled.into());
-    }
+    <T::Governance>::ensure_allocator(&acc_id)?;
pallets/governance/tests/roles.rs (1)

1-2: Consider removing the blanket allow directives.

While these may be convenient for tests, it's better to be explicit about what's allowed. Consider removing the blanket #![allow(unused)] and addressing specific warnings individually.

-#![allow(unused, clippy::arithmetic_side_effects)]
+#![allow(dead_code)] // for test helper functions
+#![allow(clippy::arithmetic_side_effects)] // test calculations don't need overflow checks
README.md (3)

3-3: Add alt text to the Discord badge.

The static analysis correctly identifies that the image should have alternate text for accessibility.

-[![](https://dcbadge.limes.pink/api/server/https://discord.gg/torus)](https://discord.gg/torus)
+[![Discord](https://dcbadge.limes.pink/api/server/https://discord.gg/torus)](https://discord.gg/torus)

69-70: Fix punctuation formatting.

The loose punctuation marks should be formatted as part of the list items.

-The Torus node operates on two primary ports:
-
-- `9944`: a WebSocket RPC for interacting with the node's API. It's recommended to always have SSL enabled and the node behind a reverse proxy.
-- `30333`: Used for node-to-node communication in the network.
+The Torus node operates on two primary ports:
+
+- **9944**: a WebSocket RPC for interacting with the node's API. It's recommended to always have SSL enabled and the node behind a reverse proxy.
+- **30333**: Used for node-to-node communication in the network.

157-157: Consider simplifying the wording.

The phrase "in support of" could be more concise.

-| Stake                   | Tokens locked in support of an agent. Higher stakes affect the weights set by the validator and their influence in the network. Stake determines validator status (only top staked agents can be validators) and affects emission distribution rewards. See: Validator, Emission. [Source: [stake.rs](pallets/torus0/src/stake.rs)]                                                                                                          |
+| Stake                   | Tokens locked to support an agent. Higher stakes affect the weights set by the validator and their influence in the network. Stake determines validator status (only top staked agents can be validators) and affects emission distribution rewards. See: Validator, Emission. [Source: [stake.rs](pallets/torus0/src/stake.rs)]                                                                                                          |
pallets/torus0/rpc/src/lib.rs (1)

53-67: Use distinct error codes for different error types.

Both error cases use error code 1, making it difficult for clients to distinguish between runtime API errors and execution failures. Consider using different error codes for better error discrimination.

         runtime
             .namespace_path_creation_cost(at, account_id, path)
             .map(|res| {
                 res.map_err(|err| {
                     ErrorObject::owned(
-                        1,
+                        1001,
                         "namespace cost calculation failed",
                         Some(format!("{err:?}")),
                     )
                 })
             })
             .map_err(|err| {
-                ErrorObject::owned(1, "Runtime execution failed", Some(err.to_string()))
+                ErrorObject::owned(1002, "Runtime API execution failed", Some(err.to_string()))
             })?
pallets/permission0/src/ext/namespace_impl.rs (1)

74-75: Track the ROOT curator TODO.

The comment indicates pending functionality that will change once a ROOT curator is implemented. Consider tracking this in an issue to ensure it's not forgotten.

Would you like me to create an issue to track the ROOT curator implementation?

docs/xtask-manual.md (1)

139-139: Add missing comma for better readability.

-The nodes will automatically connect to each other and start producing blocks since they're both configured as validators.
+The nodes will automatically connect to each other and start producing blocks, since they're both configured as validators.
pallets/permission0/src/weights.rs (1)

4-8: Consider re-running benchmarks on reference hardware.

The benchmarks were generated on 2025-06-18 (over a month ago) on a MacBook Pro. For production deployments, consider:

  1. Re-running benchmarks with the latest code changes
  2. Using reference hardware for consistent and reliable weight measurements

Would you like me to create a reminder to update the benchmarks before the next release?

CONTRIBUTING.md (1)

56-56: Add missing comma.

-We follow standard Rust coding conventions with some additional requirements specific to blockchain development.
+We follow standard Rust coding conventions, with some additional requirements specific to blockchain development.
pallets/governance/src/roles.rs (2)

12-12: Fix typo in documentation comment

Replace "wether" with "whether".

-/// Adds a new allocator to the network, checking wether it's already registered.
+/// Adds a new allocator to the network, checking whether it's already registered.

23-23: Fix typo in documentation comment

Replace "wether" with "whether".

-/// Removes an existing allocator to the network, checking wether it's registered.
+/// Removes an existing allocator to the network, checking whether it's registered.
pallets/permission0/src/permission/curator.rs (1)

72-80: Consider future cleanup requirements

The cleanup method is currently a no-op. Consider documenting what cleanup operations might be needed in the future or add a TODO comment if cleanup logic is planned.

    pub(crate) fn cleanup(
        &self,
        _permission_id: polkadot_sdk::sp_core::H256,
        _last_execution: &Option<crate::BlockNumberFor<T>>,
        _grantor: &T::AccountId,
    ) {
-        // No special cleanup needed for curator permissions
+        // No special cleanup needed for curator permissions
+        // TODO: Consider cleanup operations if curator permissions affect external state in the future
    }
docs/linear-emission.md (4)

3-3: Grammar improvement suggestion

Consider rephrasing for better clarity.

-The emission distribution code present on Torus V0 is written from scratch while keeping the same behavior as older projects.
+The emission distribution code in Torus V0 is written from scratch while maintaining the same behavior as older projects.

15-15: Add missing article

-subject to change via proposals, but default value is `100 blocks`.
+subject to change via proposals, but the default value is `100 blocks`.

17-17: Consider rephrasing for clarity

-We use `pallet-balances`' `Currency` API to issue tokens and deposit them afterwards. This is very important.
+We use `pallet-balances`' `Currency` API to issue tokens and deposit them afterward. This is crucial.

35-35: Add missing comma for clarity

-If the total stake is larger than the `MinValidatorStake` value and it has weights set, the weights are filtered
+If the total stake is larger than the `MinValidatorStake` value, and it has weights set, the weights are filtered
pallets/governance/tests/voting.rs (2)

1-1: Consider removing the broad #![allow(unused)] directive.

Using #![allow(unused)] at the module level can hide genuinely unused code that should be removed. Consider using more specific allows only where needed or removing truly unused code.

-#![allow(unused, clippy::arithmetic_side_effects)]
+#![allow(clippy::arithmetic_side_effects)]

250-251: Consider a more descriptive test name.

The current name is quite long. Consider shortening while maintaining clarity.

-fn creates_emission_proposal_with_invalid_params_and_it_fails() {
+fn voting_on_nonexistent_proposal_fails() {
pallets/governance/src/benchmarking.rs (1)

27-43: Consider using realistic curator permissions for benchmarking.

The curator helper grants all permissions (CuratorPermissions::all()), which may not reflect real-world usage patterns. Consider benchmarking with typical permission sets to get more accurate weights.

pallets/faucet/src/lib.rs (1)

185-187: Consider using benchmarked weights.

The weight values appear to be estimates. Consider adding proper benchmarks to measure actual execution costs.

Add a benchmarking module similar to other pallets to measure actual weights:

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pallets/permission0/tests/enforcement.rs (1)

293-299: Consider using a more specific error type

The test expects NotAuthorizedToToggle error when an unauthorized account tries to execute enforcement. Consider using a more specific error like NotAuthorizedToExecute for better clarity.

docs/pallet-structure.md (1)

21-21: Add language specifier to fenced code block

The fenced code block should specify a language for better syntax highlighting.

-```
+```text
pallets/faucet/tests/faucet.rs (1)

359-359: Remove dangling comment

This appears to be a remnant from removed code.

-// }
pallets/permission0/src/ext/curator_impl.rs (1)

116-120: Track the transition away from centralized chain management.

The code contains two related TODOs about ROOT curator implementation:

  1. Line 116-120: Comments about not checking ROOT curator permission due to SUDO key usage
  2. Line 143-144: Parent field will change once ROOT curator is implemented

These comments indicate a planned architectural shift from SUDO to a ROOT curator system.

Would you like me to create an issue to track the implementation of ROOT curator functionality and the removal of SUDO dependency?

Also applies to: 143-144

pallets/faucet/src/faucet.rs (1)

50-50: Consider making the faucet amount configurable.

The faucet amount is hardcoded to 50 tokens. Consider adding this as a configurable parameter in the pallet's Config trait to allow runtime configuration without code changes.

pallets/emission0/src/distribute.rs (1)

336-347: Clarify the "impossible case" comment.

The comment states this is an "impossible case", but the code handles it properly by accumulating emissions and staking. Consider clarifying why this case is considered impossible or updating the comment to reflect that this is a fallback mechanism.

-            // This is an impossible case, but if something changes in the future,
-            // the code is here.
+            // This handles the edge case where the delegatee is not in the current
+            // consensus members list. While unlikely, we handle it gracefully.
pallets/permission0/src/permission.rs (1)

316-323: Consider making the auto-execution interval configurable.

The 10-block interval for auto-execution is hardcoded. Consider making this a configurable parameter to allow runtime tuning based on network conditions.

docs/namespace.md (4)

68-68: Add missing comma for clarity.

-    Agents think carefully about namespace creation since deposits are locked. The base fee
+    Agents think carefully about namespace creation, since deposits are locked. The base fee

121-121: Add missing comma.

-    The agent can delegate read access to `agent.memory.twitter` to analytics agents while keeping other sources private.
+    The agent can delegate read access to `agent.memory.twitter` to analytics agents, while keeping other sources private.

123-123: Add missing comma.

-    The hierarchical structure naturally represents the hardware taxonomy while permissions control access.
+    The hierarchical structure naturally represents the hardware taxonomy, while permissions control access.

135-135: Add comma before "and" in compound sentence.

-    This may be refined in future versions as usage patterns emerge and economic requirements become clearer.
+    This may be refined in future versions as usage patterns emerge, and economic requirements become clearer.
pallets/governance/tests/proposal.rs (2)

255-256: Use consistent stake value representation

The test uses raw values instead of the as_tors helper function used elsewhere.

-                stake_for: 5_000_000_000_000_000_000,
-                stake_against: 10_000_000_000_000_000_000,
+                stake_for: as_tors(5),
+                stake_against: as_tors(10),

509-520: Eliminate code duplication between stake and register functions

The stake function duplicates staking logic from the register function (lines 48-57). Consider refactoring register to use this helper function.

Update the register function to use the stake helper:

-    let min_stake: u128 = pallet_torus0::MinAllowedStake::<Test>::get();
-    if stake >= min_stake {
-        if get_balance(account) - stake < 1 {
-            add_balance(account, 1);
-        }
-        assert_ok!(pallet_torus0::stake::add_stake::<Test>(
-            account, module, stake
-        ));
-    }
+    let min_stake: u128 = pallet_torus0::MinAllowedStake::<Test>::get();
+    if stake >= min_stake {
+        stake(account, module, stake);
+    }
pallets/permission0/src/lib.rs (1)

99-165: Consider storage access patterns and optimization

The pallet maintains multiple storage indices (PermissionsByParticipants, PermissionsByGrantor, PermissionsByGrantee) which improve query performance but increase storage writes. For high-frequency operations, this could impact performance.

Consider:

  1. Documenting the expected read/write patterns
  2. Adding benchmarks to measure the impact
  3. Potentially implementing lazy index updates for non-critical queries
pallets/permission0/src/permission/emission.rs (1)

73-125: Consider performance impact of nested iterations

The function iterates over all permissions for each emission accumulation. For accounts with many permissions, this could become a performance bottleneck.

Consider:

  1. Adding an index for active emission permissions by stream
  2. Implementing batch processing for multiple emissions
  3. Adding metrics to monitor accumulation performance
pallets/permission0/src/ext/emission_impl.rs (1)

431-435: Handle potential overflow in percentage addition.

The checked_add correctly handles overflow, but the error could be more specific about exceeding 100% total allocation vs arithmetic overflow.

 let new_total_allocated = match total_allocated.checked_add(percentage) {
     Some(new_total_allocated) => new_total_allocated,
-    None => return Err(Error::<T>::TotalAllocationExceeded.into()),
+    None => return Err(Error::<T>::PercentageOverflow.into()),
 };
pallets/permission0/api/src/lib.rs (1)

107-116: Consider using a builder pattern for grant_emission_permission.

With 8 parameters, this function could benefit from a builder pattern or parameter struct to improve usability and reduce the chance of parameter confusion.

Consider creating a struct to group related parameters:

pub struct EmissionPermissionParams<AccountId, Balance, BlockNumber> {
    pub allocation: EmissionAllocation<Balance>,
    pub targets: Vec<(AccountId, u16)>,
    pub distribution: DistributionControl<Balance, BlockNumber>,
    pub duration: PermissionDuration<BlockNumber>,
    pub revocation: RevocationTerms<AccountId, BlockNumber>,
    pub enforcement: EnforcementAuthority<AccountId>,
}
docs/permission0.md (2)

93-93: Add missing comma for clarity

-> `ROOT = 0b0001` exists but is reserved for future use. For now, only the SUDO key is able to grant curator permissions.
+> `ROOT = 0b0001` exists, but is reserved for future use. For now, only the SUDO key is able to grant curator permissions.

510-510: Fix missing preposition

-By using the `Currency` trait, we are able to use reserves for fixed amount emissions, and negative imbalances to avoid emitting duplicate tokens.
+By using the `Currency` trait, we are able to use reserves for fixed amount of emissions, and negative imbalances to avoid emitting duplicate tokens.
pallets/emission0/src/lib.rs (1)

101-108: Consider simplifying the Permission0 trait bounds.

The Permission0 associated type has complex trait bounds that might make the Config trait harder to implement and understand. Consider if all these type parameters are necessary or if they could be simplified.

If possible, consider grouping related functionality or using a single trait with associated types to reduce complexity.

pallets/emission0/src/distribute/math.rs (1)

134-155: Consider documenting the fixed-point to integer conversion.

The conversion from FixedU128 to u16 involves multiple steps that might not be immediately clear.

 vec.iter()
     .map(|e| {
+        // Scale by ratio, round, truncate, then convert from fixed-point to integer
         e.saturating_mul(ratio)
             .round()
             .trunc()
             .into_inner()
             .checked_div(FixedU128::DIV)
             .unwrap_or_default() as u16
     })
     .collect()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 954a248 and 498642d.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • flake.lock is excluded by !**/*.lock
📒 Files selected for processing (107)
  • .devcontainer/devcontainer.json (1 hunks)
  • .github/CODEOWNERS (1 hunks)
  • .github/workflows/build-docker-node.yml (2 hunks)
  • .github/workflows/build-docker-xtask.yml (1 hunks)
  • .github/workflows/build-docs.yml (1 hunks)
  • .github/workflows/build-runtime.yml (2 hunks)
  • .github/workflows/check.yml (2 hunks)
  • .gitignore (1 hunks)
  • .vscode/extensions.json (1 hunks)
  • .vscode/settings.json (1 hunks)
  • CLAUDE.md (1 hunks)
  • CONTRIBUTING.md (1 hunks)
  • Cargo.toml (2 hunks)
  • README.md (1 hunks)
  • docker-compose.yml (1 hunks)
  • docker/xtask.dockerfile (1 hunks)
  • docs/deploy.md (1 hunks)
  • docs/linear-emission.md (1 hunks)
  • docs/namespace.md (1 hunks)
  • docs/pallet-structure.md (1 hunks)
  • docs/permission0.md (1 hunks)
  • docs/xtask-manual.md (1 hunks)
  • flake.nix (3 hunks)
  • justfile (2 hunks)
  • node/Cargo.toml (2 hunks)
  • node/src/chain_spec.rs (0 hunks)
  • node/src/cli/eth.rs (3 hunks)
  • node/src/command.rs (1 hunks)
  • node/src/command/benchmarking.rs (3 hunks)
  • node/src/main.rs (1 hunks)
  • node/src/rpc.rs (2 hunks)
  • node/src/rpc/eth.rs (3 hunks)
  • node/src/service.rs (3 hunks)
  • pallets/emission0/Cargo.toml (2 hunks)
  • pallets/emission0/api/Cargo.toml (1 hunks)
  • pallets/emission0/api/src/lib.rs (2 hunks)
  • pallets/emission0/src/benchmarking.rs (1 hunks)
  • pallets/emission0/src/benchmarks.rs (0 hunks)
  • pallets/emission0/src/distribute.rs (17 hunks)
  • pallets/emission0/src/distribute/math.rs (6 hunks)
  • pallets/emission0/src/ext.rs (1 hunks)
  • pallets/emission0/src/lib.rs (6 hunks)
  • pallets/emission0/src/migrations.rs (1 hunks)
  • pallets/emission0/src/weight_control.rs (3 hunks)
  • pallets/emission0/src/weights.rs (3 hunks)
  • pallets/emission0/tests/distribution.rs (18 hunks)
  • pallets/emission0/tests/weights.rs (4 hunks)
  • pallets/faucet/Cargo.toml (1 hunks)
  • pallets/faucet/src/ext.rs (1 hunks)
  • pallets/faucet/src/faucet.rs (1 hunks)
  • pallets/faucet/src/lib.rs (1 hunks)
  • pallets/faucet/tests/faucet.rs (1 hunks)
  • pallets/governance/Cargo.toml (1 hunks)
  • pallets/governance/api/Cargo.toml (1 hunks)
  • pallets/governance/api/src/lib.rs (1 hunks)
  • pallets/governance/src/application.rs (10 hunks)
  • pallets/governance/src/benchmarking.rs (1 hunks)
  • pallets/governance/src/benchmarks.rs (0 hunks)
  • pallets/governance/src/config.rs (1 hunks)
  • pallets/governance/src/ext.rs (0 hunks)
  • pallets/governance/src/lib.rs (18 hunks)
  • pallets/governance/src/migrations.rs (1 hunks)
  • pallets/governance/src/proposal.rs (23 hunks)
  • pallets/governance/src/roles.rs (2 hunks)
  • pallets/governance/src/voting.rs (4 hunks)
  • pallets/governance/src/weights.rs (12 hunks)
  • pallets/governance/src/whitelist.rs (2 hunks)
  • pallets/governance/tests/application.rs (14 hunks)
  • pallets/governance/tests/config.rs (1 hunks)
  • pallets/governance/tests/curator.rs (0 hunks)
  • pallets/governance/tests/delegation.rs (1 hunks)
  • pallets/governance/tests/proposal.rs (1 hunks)
  • pallets/governance/tests/roles.rs (1 hunks)
  • pallets/governance/tests/voting.rs (7 hunks)
  • pallets/permission0/Cargo.toml (1 hunks)
  • pallets/permission0/api/Cargo.toml (1 hunks)
  • pallets/permission0/api/src/lib.rs (1 hunks)
  • pallets/permission0/rpc/Cargo.toml (1 hunks)
  • pallets/permission0/rpc/src/lib.rs (1 hunks)
  • pallets/permission0/src/benchmarking.rs (1 hunks)
  • pallets/permission0/src/ext.rs (1 hunks)
  • pallets/permission0/src/ext/curator_impl.rs (1 hunks)
  • pallets/permission0/src/ext/emission_impl.rs (1 hunks)
  • pallets/permission0/src/ext/namespace_impl.rs (1 hunks)
  • pallets/permission0/src/lib.rs (1 hunks)
  • pallets/permission0/src/migrations.rs (1 hunks)
  • pallets/permission0/src/permission.rs (1 hunks)
  • pallets/permission0/src/permission/curator.rs (1 hunks)
  • pallets/permission0/src/permission/emission.rs (1 hunks)
  • pallets/permission0/src/weights.rs (1 hunks)
  • pallets/permission0/tests/curator.rs (1 hunks)
  • pallets/permission0/tests/enforcement.rs (1 hunks)
  • pallets/permission0/tests/fixed.rs (1 hunks)
  • pallets/permission0/tests/lifetime.rs (1 hunks)
  • pallets/permission0/tests/stream.rs (1 hunks)
  • pallets/torus0/Cargo.toml (1 hunks)
  • pallets/torus0/api/Cargo.toml (1 hunks)
  • pallets/torus0/api/src/api.rs (1 hunks)
  • pallets/torus0/api/src/lib.rs (3 hunks)
  • pallets/torus0/rpc/Cargo.toml (1 hunks)
  • pallets/torus0/rpc/src/lib.rs (1 hunks)
  • pallets/torus0/src/agent.rs (9 hunks)
  • pallets/torus0/src/benchmarking.rs (1 hunks)
  • pallets/torus0/src/burn.rs (3 hunks)
  • pallets/torus0/src/fee.rs (1 hunks)
  • pallets/torus0/src/lib.rs (14 hunks)
  • pallets/torus0/src/migrations.rs (1 hunks)
⛔ Files not processed due to max files limit (4)
  • pallets/torus0/src/namespace.rs
  • pallets/torus0/src/stake.rs
  • pallets/torus0/src/weights.rs
  • pallets/torus0/tests/agent.rs
💤 Files with no reviewable changes (5)
  • node/src/chain_spec.rs
  • pallets/governance/tests/curator.rs
  • pallets/governance/src/ext.rs
  • pallets/emission0/src/benchmarks.rs
  • pallets/governance/src/benchmarks.rs
🧰 Additional context used
🧬 Code Graph Analysis (19)
pallets/emission0/api/src/lib.rs (3)
pallets/emission0/src/lib.rs (3)
  • consensus_stats (209-218)
  • delegate_weight_control (175-181)
  • delegate_weight_control (220-225)
pallets/emission0/src/weight_control.rs (1)
  • delegate_weight_control (68-98)
pallets/emission0/tests/weights.rs (2)
  • delegate_weight_control (41-41)
  • delegate_weight_control (106-106)
node/src/rpc.rs (3)
node/src/command/benchmarking.rs (2)
  • new (29-31)
  • new (68-74)
pallets/torus0/rpc/src/lib.rs (1)
  • new (34-36)
pallets/permission0/rpc/src/lib.rs (1)
  • new (29-31)
pallets/torus0/api/src/api.rs (1)
pallets/torus0/rpc/src/lib.rs (2)
  • namespace_path_creation_cost (22-26)
  • namespace_path_creation_cost (45-67)
pallets/permission0/tests/fixed.rs (7)
test-utils/src/lib.rs (9)
  • new_test_ext (362-364)
  • zero_min_burn (494-496)
  • register_empty_agent (407-422)
  • grant_emission_permission (429-456)
  • as_tors (332-334)
  • add_balance (340-344)
  • get_origin (376-378)
  • get_balance (403-405)
  • step_block (380-397)
pallets/faucet/tests/faucet.rs (2)
  • new_test_ext (328-330)
  • as_tors (324-326)
pallets/permission0/src/ext/emission_impl.rs (1)
  • grant_emission_permission (36-84)
pallets/permission0/api/src/lib.rs (2)
  • grant_emission_permission (107-116)
  • execute_permission (101-101)
pallets/permission0/src/lib.rs (2)
  • grant_emission_permission (323-348)
  • execute_permission (363-368)
runtime/src/configs.rs (1)
  • as_tors (303-305)
pallets/permission0/src/ext.rs (1)
  • execute_permission (31-33)
pallets/permission0/tests/lifetime.rs (5)
test-utils/src/lib.rs (6)
  • register_empty_agent (407-422)
  • add_balance (340-344)
  • as_tors (332-334)
  • grant_emission_permission (429-456)
  • step_block (380-397)
  • get_origin (376-378)
runtime/src/configs.rs (1)
  • as_tors (303-305)
pallets/permission0/api/src/lib.rs (3)
  • grant_emission_permission (107-116)
  • execute_permission (101-101)
  • revoke_permission (98-98)
pallets/permission0/src/lib.rs (3)
  • grant_emission_permission (323-348)
  • execute_permission (363-368)
  • revoke_permission (353-358)
pallets/permission0/src/ext.rs (2)
  • execute_permission (31-33)
  • revoke_permission (27-29)
pallets/permission0/tests/curator.rs (3)
pallets/permission0/src/ext/curator_impl.rs (3)
  • ensure_curator_permission (40-82)
  • grant_curator_permission (25-38)
  • get_curator_permission (84-96)
test-utils/src/lib.rs (4)
  • new_test_ext (362-364)
  • grant_curator_permission (458-477)
  • get (79-81)
  • step_block (380-397)
pallets/permission0/src/ext.rs (1)
  • execute_permission (31-33)
pallets/governance/api/src/lib.rs (1)
pallets/governance/src/lib.rs (5)
  • get_allocators (581-583)
  • set_allocator (585-587)
  • can_create_namespace (589-591)
  • can_register_agent (593-595)
  • force_set_whitelisted (598-600)
pallets/governance/src/migrations.rs (5)
pallets/governance/src/benchmarking.rs (10)
  • proposal (202-202)
  • proposal (222-222)
  • curator (27-43)
  • curator (72-72)
  • curator (81-81)
  • curator (110-110)
  • curator (119-119)
  • curator (135-135)
  • curator (273-273)
  • curator (279-279)
pallets/governance/src/proposal.rs (2)
  • pallet_torus0 (579-579)
  • pallet_torus0 (582-582)
pallets/permission0/api/src/lib.rs (1)
  • grant_curator_permission (147-154)
pallets/permission0/src/lib.rs (1)
  • grant_curator_permission (421-439)
pallets/permission0/src/ext/curator_impl.rs (1)
  • grant_curator_permission (25-38)
pallets/governance/src/benchmarking.rs (7)
test-utils/src/lib.rs (1)
  • grant_curator_permission (458-477)
pallets/governance/src/lib.rs (24)
  • submit_application (265-273)
  • add_allocator (188-191)
  • remove_allocator (197-200)
  • add_to_whitelist (206-212)
  • remove_from_whitelist (218-224)
  • accept_application (230-236)
  • deny_application (242-248)
  • penalize_agent (254-260)
  • add_global_params_proposal (278-285)
  • proposal (176-176)
  • proposal (177-177)
  • proposal (284-284)
  • proposal (295-295)
  • proposal (309-309)
  • proposal (364-364)
  • add_global_custom_proposal (290-296)
  • add_dao_treasury_transfer_proposal (302-315)
  • vote_proposal (320-327)
  • remove_vote_proposal (332-335)
  • enable_vote_delegation (340-343)
  • disable_vote_delegation (348-351)
  • add_emission_proposal (356-371)
  • toggle_agent_freezing (393-408)
  • toggle_namespace_freezing (412-427)
pallets/permission0/api/src/lib.rs (1)
  • grant_curator_permission (147-154)
pallets/governance/src/roles.rs (3)
  • add_allocator (13-20)
  • remove_allocator (24-31)
  • penalize_agent (34-66)
pallets/torus0/src/lib.rs (1)
  • force_register_agent (598-625)
pallets/governance/src/proposal.rs (4)
  • add_global_params_proposal (322-331)
  • add_global_custom_proposal (334-339)
  • add_dao_treasury_transfer_proposal (342-354)
  • add_emission_proposal (358-379)
pallets/governance/src/voting.rs (2)
  • disable_delegation (92-99)
  • add_vote (6-54)
pallets/permission0/src/ext.rs (4)
pallets/permission0/src/ext/emission_impl.rs (5)
  • permission (91-91)
  • permission (95-95)
  • permission (246-246)
  • permission (368-368)
  • execute_permission_impl (222-256)
pallets/permission0/src/lib.rs (3)
  • permission (314-314)
  • revoke_permission (353-358)
  • execute_permission (363-368)
pallets/permission0/api/src/lib.rs (3)
  • permission_exists (95-95)
  • revoke_permission (98-98)
  • execute_permission (101-101)
pallets/permission0/src/ext/curator_impl.rs (1)
  • execute_permission_impl (160-169)
pallets/faucet/src/lib.rs (2)
pallets/torus0/api/src/lib.rs (1)
  • sum_staking_to (33-33)
pallets/faucet/src/faucet.rs (1)
  • execute (52-102)
pallets/emission0/tests/weights.rs (4)
test-utils/src/lib.rs (5)
  • add_stake (346-360)
  • get_origin (376-378)
  • pallet_torus0 (359-359)
  • register_empty_agent (407-422)
  • get (79-81)
pallets/torus0/src/stake.rs (2)
  • add_stake (15-46)
  • add_stake (113-113)
pallets/emission0/src/weight_control.rs (2)
  • delegate_weight_control (68-98)
  • regain_weight_control (100-111)
pallets/emission0/src/lib.rs (3)
  • delegate_weight_control (175-181)
  • delegate_weight_control (220-225)
  • regain_weight_control (185-187)
pallets/permission0/src/permission.rs (6)
pallets/permission0/src/ext/namespace_impl.rs (1)
  • generate_permission_id (63-63)
pallets/permission0/src/ext/emission_impl.rs (1)
  • generate_permission_id (178-178)
pallets/permission0/src/ext/curator_impl.rs (1)
  • generate_permission_id (132-132)
pallets/permission0/src/permission/emission.rs (1)
  • cleanup (30-47)
pallets/permission0/src/permission/curator.rs (1)
  • cleanup (72-79)
pallets/permission0/src/lib.rs (1)
  • remove_permission_from_indices (540-556)
pallets/emission0/src/distribute.rs (6)
pallets/torus0/api/src/lib.rs (4)
  • agent_ids (38-38)
  • min_validator_stake (26-26)
  • is_agent_registered (39-39)
  • stake_to (36-36)
pallets/governance/src/lib.rs (1)
  • is_whitelisted (573-575)
pallets/governance/src/whitelist.rs (3)
  • is_whitelisted (7-7)
  • is_whitelisted (23-23)
  • is_whitelisted (37-39)
pallets/emission0/src/distribute/math.rs (6)
  • row_hadamard_sparse (94-110)
  • col_normalize_sparse (65-92)
  • matmul_transpose_sparse (112-132)
  • normalize (11-16)
  • vec_max_upscale_to_u16 (136-155)
  • normalize_with_sum (19-29)
pallets/permission0/api/src/lib.rs (2)
  • accumulate_emissions (119-119)
  • generate_root_stream_id (24-28)
pallets/torus0/src/stake.rs (2)
  • add_stake (15-46)
  • add_stake (113-113)
pallets/governance/src/application.rs (1)
pallets/governance/src/lib.rs (3)
  • whitelist (211-211)
  • whitelist (223-223)
  • whitelist (574-574)
pallets/permission0/api/src/lib.rs (7)
pallets/permission0/src/ext.rs (3)
  • permission_exists (23-25)
  • revoke_permission (27-29)
  • execute_permission (31-33)
pallets/permission0/src/lib.rs (4)
  • revoke_permission (353-358)
  • execute_permission (363-368)
  • grant_emission_permission (323-348)
  • grant_curator_permission (421-439)
test-utils/src/lib.rs (2)
  • grant_emission_permission (429-456)
  • grant_curator_permission (458-477)
pallets/permission0/src/ext/emission_impl.rs (4)
  • grant_emission_permission (36-84)
  • accumulate_emissions (86-92)
  • process_auto_distributions (94-96)
  • get_accumulated_amount (98-108)
pallets/permission0/src/ext/curator_impl.rs (3)
  • grant_curator_permission (25-38)
  • ensure_curator_permission (40-82)
  • get_curator_permission (84-96)
pallets/permission0/src/ext/namespace_impl.rs (1)
  • is_delegating_namespace (17-33)
pallets/permission0/rpc/src/lib.rs (2)
  • root_stream_id_for_account (21-21)
  • root_stream_id_for_account (40-47)
pallets/governance/src/lib.rs (6)
pallets/governance/src/whitelist.rs (8)
  • application (11-11)
  • application (27-27)
  • pallet_torus0 (32-32)
  • add_to_whitelist (6-18)
  • remove_from_whitelist (22-35)
  • is_whitelisted (7-7)
  • is_whitelisted (23-23)
  • is_whitelisted (37-39)
pallets/governance/src/voting.rs (5)
  • pallet_torus0 (29-29)
  • pallet_torus0 (30-30)
  • remove_vote (57-80)
  • enable_delegation (83-89)
  • disable_delegation (92-99)
pallets/governance/src/application.rs (3)
  • resolve_expired_applications (195-213)
  • accept_application (130-170)
  • deny_application (173-190)
pallets/governance/src/roles.rs (3)
  • add_allocator (13-20)
  • remove_allocator (24-31)
  • penalize_agent (34-66)
pallets/permission0/src/ext/curator_impl.rs (1)
  • ensure_curator_permission (40-82)
pallets/governance/api/src/lib.rs (6)
  • get_allocators (14-14)
  • set_allocator (16-16)
  • can_create_namespace (18-18)
  • is_whitelisted (10-10)
  • can_register_agent (20-20)
  • force_set_whitelisted (24-24)
pallets/governance/src/proposal.rs (4)
pallets/governance/tests/voting.rs (3)
  • pallet_torus0 (53-53)
  • pallet_torus0 (220-220)
  • stake (64-74)
pallets/governance/tests/proposal.rs (2)
  • pallet_torus0 (68-68)
  • stake (509-519)
pallets/governance/src/voting.rs (2)
  • pallet_torus0 (29-29)
  • pallet_torus0 (30-30)
pallets/torus0/src/lib.rs (9)
  • namespace (380-380)
  • namespace (397-397)
  • stake (290-290)
  • stake (302-302)
  • stake (315-315)
  • stake (565-565)
  • stake (574-574)
  • stake (582-582)
  • stake (633-633)
pallets/torus0/api/src/lib.rs (2)
pallets/torus0/src/lib.rs (10)
  • sum_staking_to (564-566)
  • staked_by (568-575)
  • stake_to (577-583)
  • agent_ids (585-587)
  • is_agent_registered (589-591)
  • agent (329-329)
  • agent (337-337)
  • agent (351-351)
  • namespace_exists (593-595)
  • force_set_stake (628-634)
pallets/torus0/src/stake.rs (1)
  • sum_staking_to (131-133)
🪛 actionlint (1.7.7)
.github/workflows/build-docs.yml

14-14: label "ubicloud-standard-2" is unknown. available labels are "windows-latest", "windows-latest-8-cores", "windows-2025", "windows-2022", "windows-2019", "ubuntu-latest", "ubuntu-latest-4-cores", "ubuntu-latest-8-cores", "ubuntu-latest-16-cores", "ubuntu-24.04", "ubuntu-24.04-arm", "ubuntu-22.04", "ubuntu-22.04-arm", "ubuntu-20.04", "macos-latest", "macos-latest-xl", "macos-latest-xlarge", "macos-latest-large", "macos-15-xlarge", "macos-15-large", "macos-15", "macos-14-xl", "macos-14-xlarge", "macos-14-large", "macos-14", "macos-13-xl", "macos-13-xlarge", "macos-13-large", "macos-13", "self-hosted", "x64", "arm", "arm64", "linux", "macos", "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file

(runner-label)

.github/workflows/build-docker-node.yml

20-20: label "ubicloud-standard-16" is unknown. available labels are "windows-latest", "windows-latest-8-cores", "windows-2025", "windows-2022", "windows-2019", "ubuntu-latest", "ubuntu-latest-4-cores", "ubuntu-latest-8-cores", "ubuntu-latest-16-cores", "ubuntu-24.04", "ubuntu-24.04-arm", "ubuntu-22.04", "ubuntu-22.04-arm", "ubuntu-20.04", "macos-latest", "macos-latest-xl", "macos-latest-xlarge", "macos-latest-large", "macos-15-xlarge", "macos-15-large", "macos-15", "macos-14-xl", "macos-14-xlarge", "macos-14-large", "macos-14", "macos-13-xl", "macos-13-xlarge", "macos-13-large", "macos-13", "self-hosted", "x64", "arm", "arm64", "linux", "macos", "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file

(runner-label)

.github/workflows/build-docker-xtask.yml

19-19: label "ubicloud-standard-2" is unknown. available labels are "windows-latest", "windows-latest-8-cores", "windows-2025", "windows-2022", "windows-2019", "ubuntu-latest", "ubuntu-latest-4-cores", "ubuntu-latest-8-cores", "ubuntu-latest-16-cores", "ubuntu-24.04", "ubuntu-24.04-arm", "ubuntu-22.04", "ubuntu-22.04-arm", "ubuntu-20.04", "macos-latest", "macos-latest-xl", "macos-latest-xlarge", "macos-latest-large", "macos-15-xlarge", "macos-15-large", "macos-15", "macos-14-xl", "macos-14-xlarge", "macos-14-large", "macos-14", "macos-13-xl", "macos-13-xlarge", "macos-13-large", "macos-13", "self-hosted", "x64", "arm", "arm64", "linux", "macos", "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file

(runner-label)

.github/workflows/build-runtime.yml

19-19: label "ubicloud-standard-16" is unknown. available labels are "windows-latest", "windows-latest-8-cores", "windows-2025", "windows-2022", "windows-2019", "ubuntu-latest", "ubuntu-latest-4-cores", "ubuntu-latest-8-cores", "ubuntu-latest-16-cores", "ubuntu-24.04", "ubuntu-24.04-arm", "ubuntu-22.04", "ubuntu-22.04-arm", "ubuntu-20.04", "macos-latest", "macos-latest-xl", "macos-latest-xlarge", "macos-latest-large", "macos-15-xlarge", "macos-15-large", "macos-15", "macos-14-xl", "macos-14-xlarge", "macos-14-large", "macos-14", "macos-13-xl", "macos-13-xlarge", "macos-13-large", "macos-13", "self-hosted", "x64", "arm", "arm64", "linux", "macos", "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file

(runner-label)

.github/workflows/check.yml

21-21: label "ubicloud-standard-8" is unknown. available labels are "windows-latest", "windows-latest-8-cores", "windows-2025", "windows-2022", "windows-2019", "ubuntu-latest", "ubuntu-latest-4-cores", "ubuntu-latest-8-cores", "ubuntu-latest-16-cores", "ubuntu-24.04", "ubuntu-24.04-arm", "ubuntu-22.04", "ubuntu-22.04-arm", "ubuntu-20.04", "macos-latest", "macos-latest-xl", "macos-latest-xlarge", "macos-latest-large", "macos-15-xlarge", "macos-15-large", "macos-15", "macos-14-xl", "macos-14-xlarge", "macos-14-large", "macos-14", "macos-13-xl", "macos-13-xlarge", "macos-13-large", "macos-13", "self-hosted", "x64", "arm", "arm64", "linux", "macos", "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file

(runner-label)

🪛 YAMLlint (1.37.1)
.github/workflows/build-docs.yml

[error] 7-7: trailing spaces

(trailing-spaces)


[error] 20-20: trailing spaces

(trailing-spaces)

🪛 LanguageTool
CLAUDE.md

[uncategorized] ~14-~14: Loose punctuation mark.
Context: ...g guide ## Core Pallets - torus0: Agent registration, staking, burn mecha...

(UNLIKELY_OPENING_PUNCTUATION)

README.md

[uncategorized] ~69-~69: Loose punctuation mark.
Context: ...operates on two primary ports: - 9944: a WebSocket RPC for interacting with th...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~70-~70: Loose punctuation mark.
Context: ...e node behind a reverse proxy. - 30333: Used for node-to-node communication in ...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~157-~157: ‘in support of’ might be wordy. Consider a shorter alternative.
Context: ...Stake | Tokens locked in support of an agent. Higher stakes affect the weig...

(EN_WORDINESS_PREMIUM_IN_SUPPORT_OF)

docs/pallet-structure.md

[uncategorized] ~134-~134: Possible missing comma found.
Context: ...ins require careful handling of storage changes since data persists across runtime upgr...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~170-~170: Possible missing comma found.
Context: ...data. Agents can be registered by anyone but must meet certain criteria, such as pas...

(AI_HYDRA_LEO_MISSING_COMMA)


[style] ~222-~222: This phrase is redundant. Consider writing “evolve”.
Context: ...maintainable blockchain system that can evolve over time while maintaining backward compatibilit...

(EVOLVE_OVER_TIME)

docs/deploy.md

[typographical] ~22-~22: It seems that a comma is missing after this introductory phrase.
Context: ...the 4th step. - Sign and Submit. > As of april 9th 2025 the try-runtime cli is broken,...

(AS_OF_COMMA)

docs/linear-emission.md

[uncategorized] ~9-~9: ‘Amount of’ should usually only be used with uncountable or mass nouns. Consider using “number” if this is not the case.
Context: ...ew block (target: 8 seconds), a certain amount of tokens is added to the `PendingEmiss...

(AMOUNTOF_TO_NUMBEROF)


[style] ~11-~11: ‘taken into account’ might be wordy. Consider a shorter alternative.
Context: ...mission recycling percentage. Those are taken into account inside the `get_total_emission_per_bloc...

(EN_WORDINESS_PREMIUM_TAKEN_INTO_ACCOUNT)


[uncategorized] ~15-~15: Possible missing article found.
Context: ...e, subject to change via proposals, but default value is 100 blocks. We use `pallet-...

(AI_HYDRA_LEO_MISSING_THE)


[locale-violation] ~17-~17: In American English, ‘afterward’ is the preferred variant. ‘Afterwards’ is more commonly used in British English and other dialects.
Context: ...yAPI to issue tokens and deposit them afterwards. This is very important. Theissue` fu...

(AFTERWARDS_US)


[style] ~17-~17: As an alternative to the over-used intensifier ‘very’, consider replacing this phrase.
Context: ...ns and deposit them afterwards. This is very important. The issue functions returns a `Negat...

(EN_WEAK_ADJECTIVE)


[uncategorized] ~31-~31: Possible missing comma found.
Context: ...ollowing order: 1. iterate through all agents delegating weight control to other vali...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~32-~32: Possible missing comma found.
Context: ...ator; 2. iterate through all registered agents removing from the consensus member list...

(AI_HYDRA_LEO_MISSING_COMMA)


[typographical] ~32-~32: The word “otherwise” is an adverb that can’t be used like a conjunction, and therefore needs to be separated from the sentence.
Context: ...t, an input with the correct weights is created, otherwise, an empty input is used with no weights;...

(THUS_SENTENCE)


[uncategorized] ~35-~35: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...arger than the MinValidatorStake value and it has weights set, the weights are fil...

(COMMA_COMPOUND_SENTENCE)


[uncategorized] ~35-~35: Use a comma before “and” if it connects two independent clauses (unless they are closely connected and short).
Context: ...t weights set on themselves are excluded and the remaining ones only refer to regist...

(COMMA_COMPOUND_SENTENCE_2)


[uncategorized] ~57-~57: It seems likely that a singular genitive (’s) apostrophe is missing.
Context: ...es for compact storage in the consensus members record. 9. Finally, the emissions are ...

(AI_HYDRA_LEO_APOSTROPHE_S_XS)

docs/namespace.md

[uncategorized] ~68-~68: Possible missing comma found.
Context: ... Agents think carefully about namespace creation since deposits are locked. The base fee...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~121-~121: Possible missing comma found.
Context: ... to agent.memory.twitter to analytics agents while keeping other sources private. A...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~123-~123: Possible missing comma found.
Context: ...cture naturally represents the hardware taxonomy while permissions control access. API ...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~135-~135: Use a comma before “and” if it connects two independent clauses (unless they are closely connected and short).
Context: ...future versions as usage patterns emerge and economic requirements become clearer. ...

(COMMA_COMPOUND_SENTENCE_2)


[misspelling] ~149-~149: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ...# Security Considerations We will need a anti-spam system to emerge in the near ...

(EN_A_VS_AN)

docs/xtask-manual.md

[uncategorized] ~139-~139: Possible missing comma found.
Context: ...nnect to each other and start producing blocks since they're both configured as valida...

(AI_HYDRA_LEO_MISSING_COMMA)


[style] ~151-~151: Consider shortening or rephrasing this to strengthen your wording.
Context: ...y cover the codebase, particularly when making changes to the pallets. ## Internal Implementatio...

(MAKE_CHANGES)

CONTRIBUTING.md

[uncategorized] ~44-~44: Loose punctuation mark.
Context: ...nized into 5 main crates: - node/: Contains the actual node implementation...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~46-~46: Loose punctuation mark.
Context: ...rplate from substrate. - pallets/: Contains the runtime logic modules sepa...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~48-~48: Loose punctuation mark.
Context: ...ated by responsibility: - emission0: handles all token emission logic; - `...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~52-~52: Loose punctuation mark.
Context: ...ions with the network. - runtime/: Defines the configuration used by the n...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~56-~56: Possible missing comma found.
Context: ...delines We follow standard Rust coding conventions with some additional requirements speci...

(AI_HYDRA_LEO_MISSING_COMMA)

docs/permission0.md

[uncategorized] ~5-~5: ‘Amount of’ should usually only be used with uncountable or mass nouns. Consider using “number” if this is not the case.
Context: ...entage of incoming emissions or a fixed amount of tokens. The concept draws inspirati...

(AMOUNTOF_TO_NUMBEROF)


[grammar] ~30-~30: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...bles recursive delegation chains, where a permission can be derived from a higher-level perm...

(A_UNCOUNTABLE_NOUN)


[grammar] ~30-~30: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ... where a permission can be derived from a higher-level permission. This creates hierarchical delegation t...

(A_UNCOUNTABLE_NOUN)


[uncategorized] ~93-~93: Possible missing comma found.
Context: ...0000_1000; ``` > ROOT = 0b0001 exists but is reserved for future use. For now, on...

(AI_HYDRA_LEO_MISSING_COMMA)


[style] ~93-~93: As a shorter alternative for ‘able to’, consider using “can”.
Context: ... future use. For now, only the SUDO key is able to grant curator permissions. The `cooldo...

(BE_ABLE_TO)


[uncategorized] ~112-~112: Loose punctuation mark.
Context: ...ns flow through the network: - Manual: The grantee must explicitly call `execu...

(UNLIKELY_OPENING_PUNCTUATION)


[grammar] ~130-~130: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...rocessing. Revocation terms define how a permission can be revoked before its normal expira...

(A_UNCOUNTABLE_NOUN)


[grammar] ~144-~144: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ... parties. The grantee can ALWAYS revoke a permission as it is the one being benefitted. ## ...

(A_UNCOUNTABLE_NOUN)


[grammar] ~297-~297: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...> DispatchResult ``` Manually executes a permission with distribution control set to Manual...

(A_UNCOUNTABLE_NOUN)


[style] ~297-~297: To form a complete sentence, be sure to include a subject.
Context: ...the targets according to their weights. Can only be called by the grantor or root. ...

(MISSING_IT_THERE)


[grammar] ~309-~309: ‘an’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...` Enables or disables accumulation for an emission permission. Can be called by the grantor, root, or...

(A_UNCOUNTABLE_NOUN)


[style] ~309-~309: To form a complete sentence, be sure to include a subject.
Context: ...ccumulation for an emission permission. Can be called by the grantor, root, or enfo...

(MISSING_IT_THERE)


[grammar] ~320-~320: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...onId, ) -> DispatchResult ``` Executes a permission through the enforcement authority mecha...

(A_UNCOUNTABLE_NOUN)


[grammar] ~333-~333: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...r updates the enforcement authority for a permission. Can only be called by the grantor or r...

(A_UNCOUNTABLE_NOUN)


[style] ~333-~333: To form a complete sentence, be sure to include a subject.
Context: ...enforcement authority for a permission. Can only be called by the grantor or root. ...

(MISSING_IT_THERE)


[style] ~510-~510: As a shorter alternative for ‘able to’, consider using “can”.
Context: ...isms By using the Currency trait, we are able to use reserves for fixed amount emissions...

(BE_ABLE_TO)


[grammar] ~510-~510: Using ‘plenty’ without ‘of’ is considered to be informal.
Context: ..., we are able to use reserves for fixed amount emissions, and negative imbalances to avoid emitt...

(PLENTY_OF_NOUNS)

🪛 markdownlint-cli2 (0.17.2)
README.md

3-3: Images should have alternate text (alt text)

(MD045, no-alt-text)

docs/pallet-structure.md

21-21: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

docs/permission0.md

489-489: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: check
  • GitHub Check: build-n-push
  • GitHub Check: check
  • GitHub Check: docker
🔇 Additional comments (172)
.gitignore (1)

1-2: LGTM! Good addition for local development files.

The *.local.* pattern is a sensible addition that will help developers exclude local configuration files without affecting the main codebase.

.vscode/extensions.json (1)

4-5: LGTM! Good addition for coverage visualization.

The coverage gutters extension will help developers visualize code coverage directly in the editor, which aligns with the coverage improvements mentioned in the PR.

node/src/cli/eth.rs (2)

30-31: LGTM! Good doc comment formatting improvements.

The multi-line formatting improves readability and follows Rust documentation conventions.

Also applies to: 56-57


1-1: Verify the necessity of result_large_err lint suppression

I couldn’t locate the definition of ServiceError in the repo—please confirm its location and inspect the size of its variants before you suppress this lint. The result_large_err warning exists to flag potentially large error types that can impact performance. If ServiceError is indeed large, consider one of the following instead of a blanket suppression:

  • Box the error payload (e.g., Box<dyn std::error::Error + Send + Sync>)
  • Split out smaller, more focused error enums
  • Implement a lightweight wrapper or use thiserror with minimal variant data

If after review ServiceError is small (or the performance impact is negligible), please add a comment explaining why the suppression is safe. The doc comment tweaks look good.

docker-compose.yml (1)

12-29: LGTM! Improved command formatting.

The multi-line YAML array format is more readable and easier to maintain than the single-line format.

pallets/torus0/src/fee.rs (1)

4-6: LGTM! Good import consolidation.

Consolidating related imports from the same crate improves code organization and follows Rust best practices.

node/src/command.rs (1)

24-28: LGTM: Import reorganization improves code structure.

The reorganization of imports to separate crate imports from external dependencies follows good Rust practices and improves code readability.

node/src/command/benchmarking.rs (2)

5-5: LGTM: Import reordering improves organization.

The import reorganization follows good practices by grouping standard library imports separately from local crate imports.

Also applies to: 18-18


174-174: LGTM: Modern error formatting syntax.

The change to {e:?} uses the modern Rust formatting syntax introduced in Rust 1.58+, which is more concise and readable.

node/Cargo.toml (2)

16-16: LGTM: Testnet feature addition.

The new testnet feature properly enables testnet-specific functionality in the torus-runtime, supporting the expanded runtime capabilities.


109-110: LGTM: New RPC dependencies added.

The addition of pallet-permission0-rpc and pallet-torus0-rpc as workspace dependencies properly supports the new permission and namespace management RPC functionality.

pallets/governance/Cargo.toml (2)

49-49: LGTM: Permission API dependency added.

The addition of pallet-permission0-api as a workspace dependency properly integrates the permission system API into the governance pallet.


53-53: LGTM: Permission pallet dev-dependency added.

The addition of pallet-permission0 as a dev-dependency enables proper testing of the permission system integration within the governance pallet.

node/src/rpc.rs (4)

30-31: LGTM: New RPC module imports added.

The imports for Permission0Rpc and Torus0Rpc properly expose the new RPC functionality for permission and namespace management.


89-89: LGTM: Consistency improvement for client usage.

Adding .clone() to the client reference for TransactionPayment::new() creates consistency with the pattern used for the new RPC modules below. Since Arc::clone() is cheap (just increments reference count), this is a good practice.


90-91: LGTM: New RPC modules properly integrated.

The integration of Permission0Rpc and Torus0Rpc follows the same pattern as other RPC modules, using client.clone() and proper error handling with the ? operator.


25-25: Arc import is necessary
Verified there are no other imports of Arc in node/src/rpc.rs; the explicit use std::sync::Arc; should remain. All other changes—adding .clone() for TransactionPayment and the new RPC module integrations—are consistent and approved.

.vscode/settings.json (3)

5-11: LGTM: Enhanced Rust analyzer configuration.

The environment variable formatting is cleaner and the addition of the "testnet" feature aligns with the broader project changes introducing testnet support across multiple crates.


12-12: LGTM: Coverage gutters integration.

The coverage configuration complements the enhanced CI coverage reporting workflow.


14-25: LGTM: Comprehensive spell checker configuration.

The custom word list includes appropriate domain-specific terms that would otherwise trigger false positives in documentation and code comments.

pallets/emission0/api/src/lib.rs (2)

3-3: LGTM: Required import for new API method.

The DispatchResult import is necessary for the new delegate_weight_control method signature.


17-17: LGTM: Well-designed API extension.

The delegate_weight_control method signature is consistent with the implementation and follows Rust conventions. The method properly takes account references and returns a DispatchResult, allowing proper error handling for delegation operations.

.devcontainer/devcontainer.json (1)

1-8: LGTM: Standardized development environment.

The devcontainer configuration properly sets up a consistent development environment with Nix flakes support and direnv integration, aligning with the project's development approach described in the documentation.

pallets/permission0/rpc/Cargo.toml (1)

1-14: LGTM: Well-structured RPC crate manifest.

The configuration follows workspace conventions with appropriate dependencies for RPC functionality. The feature flags and dependency specifications are correctly configured for the RPC interface.

.github/workflows/build-docker-node.yml (3)

1-1: LGTM: More descriptive workflow name.

The updated name "Build Torus node Docker image" is more specific and clearly indicates the workflow's purpose.


5-8: LGTM: Expanded branch triggers.

Adding the 'dev' branch to the trigger list is appropriate for continuous integration of development changes.


22-22: LGTM: Updated checkout action.

Updating to actions/checkout@v4 is a good practice to use the latest stable version with security updates and improvements.

pallets/torus0/rpc/Cargo.toml (1)

1-15: LGTM! Well-structured RPC crate manifest.

The RPC crate configuration follows best practices with proper workspace integration, appropriate dependencies for JSON-RPC functionality, and consistent use of workspace features.

pallets/torus0/api/Cargo.toml (3)

9-11: Good addition of workspace lints.

Adding the workspace lints configuration ensures consistent code quality across the crate.


14-14: Appropriate expansion of std feature.

Including codec/std and scale-info/std in the std feature is necessary for the expanded API functionality.


19-26: Well-structured dependencies update.

The addition of explicit codec and scale-info dependencies with derive features, and the expansion of polkadot-sdk features appropriately support the enhanced API functionality.

pallets/governance/tests/config.rs (2)

7-26: Comprehensive test coverage for set_emission_params.

The test properly verifies both the successful execution with root origin and the resulting state changes in both pallet_emission0 and pallet_governance storage.


28-40: Good negative test case.

The test properly verifies that non-root origins are rejected with the expected BadOrigin error.

pallets/governance/src/whitelist.rs (2)

5-5: Clear and helpful documentation.

The documentation clearly explains the function's purpose in the context of agent registration management.


20-21: Comprehensive documentation for removal function.

The documentation accurately describes both the prevention of new registrations and the deregistration of existing agents.

.github/workflows/build-runtime.yml (2)

40-41: Well-implemented conditional testnet feature flag.

The conditional logic properly detects testnet tags and applies the appropriate feature flag while providing clear feedback about the build configuration.


19-19: Runner label availability confirmed
The ubicloud-standard-16 label is a valid Ubicloud self-hosted runner (Ubuntu 22.04, 16 vCPU, 64 GB RAM). No changes to the workflow are required.

node/src/rpc/eth.rs (3)

3-7: LGTM! Good import organization.

The addition of the "// Frontier" comment and grouping of related imports improves code readability and organization.


55-56: LGTM! Improved comment formatting.

The reformatting of the multiline comment to a single line improves readability while maintaining the same semantic meaning.


98-98: LGTM! Consolidated imports.

Merging TxPool and TxPoolApiServer into the main import statement reduces redundancy and improves organization.

pallets/faucet/src/ext.rs (1)

1-8: LGTM! Standard Substrate type aliases.

The type aliases follow standard Substrate patterns and provide clean abstractions for balance and account ID types within the faucet pallet.

pallets/torus0/Cargo.toml (2)

19-21: LGTM! Appropriate API dependencies added.

The addition of the new pallet API dependencies (pallet-emission0-api, pallet-governance-api, pallet-permission0-api) to both the std feature and dependencies aligns with the permission management system being introduced.

Also applies to: 39-39


34-34: Dependency change from substrate-fixed to libm.

The switch from substrate-fixed to libm suggests moving away from fixed-point arithmetic. Ensure this change is consistent with the pallet's mathematical operations and that precision requirements are still met.

.github/workflows/build-docs.yml (2)

14-14: Verify custom runner label.

The runner label ubicloud-standard-2 is not a standard GitHub Actions runner. Ensure this is a valid self-hosted runner available in your environment.


32-34: LGTM! Appropriate documentation generation.

The use of cargo doc --workspace --no-deps is correct for generating documentation without external dependencies, which is appropriate for GitHub Pages deployment.

pallets/torus0/api/src/api.rs (2)

6-12: LGTM! Well-structured runtime API trait.

The runtime API trait follows Substrate conventions with appropriate generic constraints. The method signature for namespace_path_creation_cost correctly returns a Result with a tuple of balance values for fee and deposit calculation.


10-10: No issues with NamespacePathInner availability

The type NamespacePathInner is defined and exported in pallets/torus0/api/src/lib.rs as a pub type. It’s correctly available in the api crate, so no changes are needed.

pallets/emission0/Cargo.toml (3)

19-21: LGTM: Dependency additions align with permission system integration.

The addition of pallet-governance-api/std and pallet-permission0-api/std to the std feature correctly integrates the new permission and governance APIs into the emission pallet.


26-27: LGTM: Runtime benchmarks feature properly extended.

The runtime benchmarks for the new governance and permission0 API pallets are correctly added to support performance testing.


42-42: LGTM: Workspace dependency correctly added.

The pallet-permission0-api.workspace = true dependency is properly declared to maintain workspace consistency.

pallets/emission0/src/ext.rs (3)

1-1: LGTM: Import expansion for frame_system.

The addition of frame_system to the import simplifies the type alias references and improves readability.


3-6: LGTM: Type aliases updated for public visibility and consistency.

The changes to make BalanceOf and AccountIdOf public and use the simplified frame_system::Config reference are appropriate for the permission system integration.


8-10: LGTM: New NegativeImbalanceOf type alias correctly defined.

The NegativeImbalanceOf type alias is properly structured to represent the negative imbalance from the Currency trait, which is essential for emission distribution logic.

CLAUDE.md (1)

1-35: LGTM: Comprehensive documentation for Claude Code guidance.

This documentation file provides excellent guidance covering:

  • Project references and architecture docs
  • Core pallet responsibilities
  • Essential development commands
  • Critical safety rules for runtime development

The safety rules section is particularly valuable, emphasizing proper arithmetic operations and panic avoidance in runtime code.

pallets/faucet/Cargo.toml (1)

1-37: LGTM: Well-structured faucet pallet manifest.

The faucet pallet manifest is properly configured with:

  • Appropriate testnet feature gating on line 17
  • Minimal runtime dependencies focused on balances functionality
  • Comprehensive dev dependencies for testing integration
  • Clear description indicating testnet-only proof-of-work token distribution

The structure follows established patterns in the codebase.

pallets/permission0/api/Cargo.toml (1)

1-32: LGTM: Well-structured permission0 API manifest.

The permission0 API crate manifest is properly configured with:

  • Standard workspace integration and feature flags
  • Appropriate dependencies including bitflags for efficient permission representation
  • Integration with pallet-torus0-api for system consistency
  • Clean separation of concerns as an API-only crate

The structure supports modular development and clean API boundaries.

pallets/permission0/Cargo.toml (1)

1-43: LGTM! Well-structured Cargo.toml for the permission0 pallet.

The manifest follows Substrate pallet conventions with proper workspace configuration, appropriate feature flags, and correctly configured dependencies. The local API dependencies are properly set with default-features = false which is the standard practice for pallet dependencies.

.github/workflows/build-docker-xtask.yml (2)

1-51: Well-structured Docker build workflow.

The workflow follows best practices with proper path-based triggers, appropriate permissions, Docker Buildx setup, and efficient caching configuration. The tagging strategy with SHA and conditional latest tag is appropriate for this use case.


19-19: Verify the custom runner label
The runner label ubicloud-standard-2 isn’t one of GitHub’s hosted runners. We didn’t find any other references to it in .github/workflows, so please confirm whether:

  • You have a self-hosted runner registered under this label in your organization or repository settings.
  • If not, consider switching to a GitHub-hosted runner (for example, ubuntu-latest) to avoid workflow failures.

File to check:

  • .github/workflows/build-docker-xtask.yml (line 19)
pallets/governance/src/config.rs (2)

2-5: Improved type safety with BlockNumberFor.

The import changes to use BlockNumberFor<T> from the polkadot-sdk prelude align with Substrate best practices and provide better type safety compared to generic aliases.


14-19: Consistent type updates for block number fields.

The migration from generic BlockAmount to explicit BlockNumberFor<T> for time-related fields provides better type safety and explicit typing. This change is consistent across all block number fields in the configuration.

pallets/governance/tests/delegation.rs (1)

1-34: Well-structured delegation tests with good coverage.

The tests provide comprehensive coverage for the vote delegation functionality, testing both enabling and disabling delegation. The test structure is clear with proper setup, action, and assertion patterns. The use of NotDelegatingVotingPower storage item for verification is appropriate for testing the delegation state.

docker/xtask.dockerfile (1)

1-18: Builder stage is well-configured.

The builder stage properly installs all necessary build dependencies for compiling Rust/Substrate projects and correctly builds the xtask binary.

pallets/torus0/src/burn.rs (3)

2-10: LGTM: Import reorganization improves clarity.

The reorganization of imports with polkadot_sdk grouping and moving the BalanceOf import after SDK imports follows good organization practices.


41-45: LGTM: Documentation improves function clarity.

The added documentation clearly explains the burn adjustment mechanism and its trigger conditions.


71-101: Double-check FixedU128 fractional precision and range compatibility

The refactor replaces substrate_fixed::I110F18 (which uses 18 fractional bits) with sp_runtime::FixedU128. Because from_inner()/into_inner() perform raw bit casts, please verify that:

  • FixedU128 uses the same 18-bit fractional scale (or adjust conversion if it does not).
  • All arithmetic calls (from_u32, const_checked_mul, const_checked_div) preserve the intended precision and do not introduce unintended rounding or overflow.
  • Edge cases in pallets/torus0/src/burn.rs (lines 71–101) still yield correct min/max clamping as before.

Ensure the burn update logic remains numerically equivalent to the original I110F18 implementation.

docs/deploy.md (1)

1-21: LGTM: Comprehensive deployment guide.

The deployment instructions are well-structured and cover all essential steps from testing to runtime deployment. The integration with GitHub Actions and the verification steps provide good safety measures.

node/src/service.rs (3)

17-17: LGTM: Appropriate clippy allowance for large error types.

The result_large_err allowance is reasonable for node service code which often deals with complex error types from various subsystems.


157-183: LGTM: Type alias improves code readability.

The AuraData type alias significantly improves readability by replacing a complex nested Pin<Box<dyn Future>> type with a clear, named alias. The refactored function signature is much cleaner.


499-503: LGTM: Comment formatting enhances readability.

The reformatted comments provide clearer explanation of the pubsub notification sink mechanism.

pallets/emission0/src/benchmarking.rs (1)

1-91: LGTM: Comprehensive benchmarking implementation.

The benchmarking module follows best practices:

  • Proper feature gating with runtime-benchmarks
  • Uses frame_benchmarking v2 API correctly
  • Each benchmark sets up realistic state conditions
  • Covers all main extrinsics with appropriate test data
  • Uses the modern #[extrinsic_call] macro for accurate measurement

The setup logic properly integrates with the Torus and Governance pallets to establish required preconditions.

pallets/emission0/src/weights.rs (3)

5-5: LGTM: Updated benchmark date reflects recent weight generation.

The benchmark date update from January to June 2025 indicates these weights were recently regenerated to account for the pallet changes.


55-60: LGTM: Storage access changes align with governance integration.

The addition of Governance::Whitelist and Governance::Allocators reads, along with the replacement of Emission0::MinStakePerWeight with Torus0::MinValidatorStake, correctly reflects the pallet's integration with the governance system and updated stake validation logic.

Also applies to: 75-77


68-70: LGTM: Weight increases reflect additional storage operations.

The increased execution times and database read counts are appropriate given the additional governance checks and storage operations required by the updated pallet logic.

Also applies to: 85-87, 98-100

pallets/emission0/src/migrations.rs (1)

22-22: Review single-allocator usage in the V2 migration

File: pallets/emission0/src/migrations.rs (line 22)

Using allocators.first() always delegates every agent’s weight control to the smallest-ordered AccountId, introducing an arbitrary, single-point-of-control:

• Centralization risk: all delegations run through one allocator
• Unpredictable choice: ordering by AccountId isn’t governance-driven

Please consider revising to one of the following:

  • Distribute delegations across multiple allocators (e.g. round-robin or weighted)
  • Select a known allocator via an on-chain parameter or governance proposal
  • Expose the allocator-selection strategy as a configurable runtime setting

Let me know if you’d like an example implementation that rotates or balances delegations.

justfile (1)

1-1: Build and development workflow improvements look good!

The changes enhance the development experience:

  • Running fmt by default ensures consistent code style
  • Separate mainnet/testnet builds with timing info aid in optimization
  • --tests flag for clippy catches more potential issues
  • Permission0 benchmark integration is properly configured

Also applies to: 5-9, 14-14, 19-20, 51-54, 62-62

.github/workflows/check.yml (3)

21-21: Verify the custom runner configuration.

The runner label ubicloud-standard-8 is not a standard GitHub-hosted runner. Ensure this custom runner is properly configured and available in your repository settings.


14-20: LGTM: Explicit permissions configuration.

The explicit permissions configuration follows security best practices by granting only the necessary permissions for the workflow operations.


102-118: Verify S3 Upload Credentials and Variables

Please confirm that the following are defined in your repository settings, as they’re referenced in .github/workflows/check.yml (lines 102–118):

  • Secrets
    • COV_AWS_ACCESS_KEY_ID
    • COV_AWS_SECRET_ACCESS_KEY
  • Variables
    • COV_ENDPOINT_URL
    • COV_BUCKET_NAME
    • COV_DEFAULT_REGION

These must exist and hold valid values to ensure the aws s3 sync step succeeds.

pallets/permission0/rpc/src/lib.rs (1)

1-49: LGTM: Well-structured RPC implementation.

The RPC implementation follows Polkadot SDK best practices:

  • Proper use of jsonrpsee macros for trait definition
  • Consistent error handling with meaningful error codes
  • Appropriate type definitions using SDK traits
  • Clean separation of client interface and implementation

The code is production-ready and follows standard patterns for Substrate RPC modules.

pallets/emission0/tests/weights.rs (1)

89-89: LGTM: Updated to use configured minimum stake.

Using MinValidatorStake::<Test>::get() instead of hardcoded values improves maintainability and aligns with the pallet's configuration.

pallets/permission0/tests/curator.rs (1)

1-132: LGTM: Comprehensive curator permission test coverage.

The test suite provides excellent coverage of curator permission functionality:

  • Origin validation: Tests both signed and root origins appropriately
  • Duplicate prevention: Ensures permissions cannot be granted twice
  • Security: Verifies ROOT flags are properly filtered out
  • Permission enforcement: Validates that users can only execute actions they have permissions for
  • Cooldown behavior: Tests the cooldown mechanism after permission execution
  • Error handling: Covers all relevant error cases

The tests are well-structured, use appropriate helper functions, and follow good testing practices. This provides confidence in the curator permission system's correctness.

pallets/governance/tests/application.rs (4)

7-7: LGTM: Improved integration with permission system.

The replacement of direct Curators storage manipulation with grant_curator_permission calls is a significant improvement:

  • Proper validation: Tests now exercise the actual permission validation logic
  • Consistency: Aligns with the new permission-based architecture
  • Maintainability: Uses the public API instead of internal storage manipulation

This ensures tests accurately reflect the runtime behavior and catch permission-related issues.

Also applies to: 19-19, 46-46, 72-72, 127-127, 184-184, 219-219, 285-285, 329-329


126-126: Good variable naming improvements.

The renaming from adding_key to removing_key in the removal test improves code clarity and makes the test's intent more obvious.

Also applies to: 140-140, 150-150, 165-165


273-277: LGTM: Explicit test configuration.

Setting the expiration blocks explicitly within the test makes the test behavior predictable and self-contained, which is a good testing practice.

Also applies to: 321-325


264-264: Consistent treasury address usage.

Using Governance::dao_treasury_address() instead of Test::dao_treasury_address() maintains consistency with the governance pallet's API.

Also applies to: 312-312

Cargo.toml (3)

7-7: LGTM!

The addition of the RPC pattern to workspace members is consistent with the new RPC modules being added for pallets.


35-41: LGTM!

The new pallet dependencies are properly configured with default-features = false to support no_std builds, consistent with other local dependencies.


51-57: All dependencies are up-to-date and match the latest stable versions on crates.io.
No further action required.

pallets/permission0/tests/lifetime.rs (4)

1-4: LGTM!

The imports are clean and minimal, importing only what's needed for the tests.


5-38: Test logic is correct.

The test properly verifies that permissions cannot be executed after their expiration block. Good coverage of the edge case where UntilBlock(1) is used.


40-82: Comprehensive test for irrevocable permissions.

The test correctly verifies that:

  • Irrevocable permissions cannot be revoked by the grantor
  • They cannot be revoked by unrelated agents
  • They can still be revoked by the grantee (important security feature)

190-201: Excellent validation coverage.

The test properly validates edge cases for arbiter configuration:

  • Empty arbiters list
  • Zero required votes
  • Required votes exceeding arbiter count
pallets/emission0/src/weight_control.rs (5)

27-29: Good security enhancement.

Adding the whitelist check alongside registration ensures only approved agents can set weights. This two-factor verification strengthens the access control.


36-38: Simplified stake requirement.

The change from per-weight stake calculation to a fixed validator stake threshold simplifies the logic and makes it more predictable. This aligns with the validator role requirements.


47-49: Consistent access control for targets.

Good to see the same registration and whitelist checks applied to target agents. This ensures weights can only be assigned to approved participants.


68-71: Improved function signature.

The change to explicit account IDs instead of origin makes the function more flexible and clearer in its intent. This is particularly useful for programmatic delegation.


87-90: Appropriate delegatee restriction.

Requiring the delegatee to be an allocator makes sense at the current network stage, as noted in the comment. This ensures weight control is only delegated to trusted validators.

pallets/governance/tests/roles.rs (3)

11-37: Well-structured test helper function.

The register function properly handles balance setup, whitelist addition, agent registration, and staking. Good defensive programming with balance checks.


86-86: Good use of helper function.

Using grant_curator_permission helper keeps the test focused and readable.


124-155: Excellent edge case coverage.

This test catches an important constraint - preventing whitelist removal when there's an active application. This ensures data consistency and prevents orphaned applications.

README.md (3)

7-9: Excellent project description.

The updated description clearly conveys the project's purpose and technology stack. The metaphor of a "self-assembling and evolving peer-to-peer organism" is both memorable and accurate.


28-36: Clear and helpful Docker instructions.

The quick start section provides excellent guidance with explanations of what each command does. The warp sync recommendation is particularly useful for new users.


140-164: Outstanding terminology section!

This comprehensive glossary is invaluable for understanding the codebase. The consistent format with descriptions and source file references makes it easy to navigate. Great addition to the documentation.

pallets/permission0/src/ext/namespace_impl.rs (1)

16-34: LGTM!

The is_delegating_namespace implementation correctly checks if a grantor has permissions over the specified namespace path by iterating through granted permissions and verifying scope inclusion.

docs/xtask-manual.md (1)

1-192: Excellent documentation!

The xtask manual provides comprehensive guidance for developers with clear examples, troubleshooting tips, and well-organized sections covering all major commands.

CONTRIBUTING.md (1)

66-69: Critical safety guidelines!

Excellent emphasis on avoiding panics in runtime code. The clear explanation about WASM runtime's inability to unwind and the potential chain-halting consequences provides crucial context for contributors.

pallets/governance/src/roles.rs (1)

34-66: Well-implemented permission-based access control

The integration with the Permission0 pallet for curator permission checks is clean and follows security best practices. The function properly validates the penalty percentage and emits a comprehensive event.

flake.nix (2)

69-81: Good build environment setup

The explicit configuration of LLVM 17 paths and prioritization in PATH is well-documented and necessary for Polkadot SDK compatibility. The shellHook provides clear feedback about the clang version being used.


5-5: Verify nixpkgs-25.05 compatibility with your dependencies

Nixpkgs 25.05 brings several upstream changes that may affect your project—please confirm none apply or adjust as needed:

• GCC upgrade (13→14) and Linux kernel bump (6.6→6.12/6.14):
– Check your C/C++ toolchain (e.g. RocksDB builds) for any new compiler errors or flag changes.
• Mesa graphics and NVIDIA defaults:
– If you rely on GPU drivers in development shells, ensure hardware.graphics.package and hardware.nvidia.open still yield the correct modules.
• Database changes:
– Verify you’re not using the deprecated services.postgresql.ensurePermissions option.
– If you bundle MongoDB, note the default was updated from 5.0→7.0.
• Android SDK relocation:
– If your CI or shells reference androidenv.androidPkgs_9_0, switch to androidenv.androidPkgs.

Bullet-point locations to review in your flake.nix or dependent Nix files:

  • C/C++ build inputs for RocksDB/LLVM17 settings
  • Any services.* overrides (postgresql, gnome, nvidia, etc.)
  • Android SDK references, MongoDB package pins
pallets/permission0/src/permission/curator.rs (1)

25-40: Well-structured permission flags

The use of bitflags for curator permissions is efficient and follows best practices. Each permission has a clear purpose and the bit patterns avoid conflicts.

pallets/emission0/tests/distribution.rs (4)

79-83: Good edge case testing for overflow protection

Testing the behavior when PendingEmission is at u128::MAX ensures the system handles overflow scenarios correctly.


457-464: Comprehensive dividend and incentive tracking

The addition of assertions for last_dividends and last_incentives fields ensures the consensus member state is properly updated during distribution.


579-621: Excellent test coverage for delegation edge cases

The test for weight delegation fees to validators without permits covers an important edge case in the delegation system.


658-673: Clean test helper function

The set_emissions_params() helper function effectively centralizes test setup and improves test maintainability.

docs/linear-emission.md (1)

1-71: Comprehensive and well-structured documentation

The documentation provides an excellent overview of the emission distribution mechanism. The step-by-step explanation of the linear distribution algorithm is particularly helpful for understanding the complex process.

pallets/governance/tests/voting.rs (2)

64-74: LGTM! Good handling of minimum balance.

The function correctly ensures the account maintains a minimum balance after staking, preventing complete depletion.


224-224: Unclear why penalization is needed in this test.

The test calls penalize_agent but it's not clear how this relates to testing proposal expiration. Consider removing this line if it's not essential to the test.

pallets/torus0/src/benchmarking.rs (2)

110-110: Verify the intention of resetting cooldown to default.

Setting AgentUpdateCooldown to default (likely 0) allows immediate agent updates in the benchmark. Ensure this represents a realistic scenario for benchmarking.


14-21: LGTM! Well-structured helper function.

The register_test_agent helper provides a clean abstraction for agent registration in benchmarks.

pallets/faucet/src/lib.rs (1)

1-227: Excellent documentation and feature gating!

The pallet has comprehensive documentation and properly uses feature flags to ensure it's only available on testnets. The unsigned transaction validation is well-implemented.

pallets/permission0/tests/enforcement.rs (7)

13-24: LGTM!

The helper functions are well-structured and provide clean abstractions for test setup.


26-100: LGTM!

Comprehensive test coverage for enforcement authority setting, properly verifying that only the grantor can modify enforcement settings.


102-167: LGTM!

Well-structured test that validates the complete accumulation toggle lifecycle and its effects on emission distribution.


169-216: LGTM!

Good negative test case ensuring proper authorization checks for toggling accumulation.


218-259: LGTM!

Clean test validating successful enforcement execution and resulting balance changes.


303-415: LGTM!

Excellent comprehensive test for multi-controller voting scenarios, properly validating vote tracking and threshold enforcement.


417-457: LGTM!

Good edge case test ensuring enforcement execution is restricted to manual distribution control.

pallets/permission0/src/ext.rs (6)

21-34: LGTM!

Clean trait implementation with proper delegation to internal functions.


36-48: LGTM!

Proper validation ensuring block numbers are in the future.


50-84: LGTM!

Comprehensive validation for revocation terms with proper boundary checks.


86-116: LGTM!

Consistent validation pattern for enforcement authority matching the revocation terms approach.


127-150: LGTM!

Proper authorization checks and clean delegation to scope-specific implementations.


152-221: LGTM!

Well-implemented multi-controller voting logic with proper vote tracking, threshold enforcement, and cleanup.

pallets/governance/src/application.rs (2)

57-126: LGTM!

Well-structured application submission with proper validation, fee handling, and safe arithmetic for expiration calculation.


172-225: LGTM!

The remaining functions are well-implemented with clear logic for application denial, expiration handling, and existence checking.

docs/pallet-structure.md (1)

1-222: Excellent documentation!

This is a comprehensive and well-structured guide that clearly explains the pallet architecture, design decisions, and best practices. The examples and explanations will be very helpful for developers working with the codebase.

pallets/faucet/tests/faucet.rs (2)

1-326: LGTM!

Comprehensive runtime configuration with all necessary pallets and proper use of saturating arithmetic for token conversion.


361-417: Well-structured faucet tests

The tests properly validate both failure and success cases for the proof-of-work faucet mechanism.

pallets/governance/src/weights.rs (2)

5-5: LGTM! Weight file updated to reflect governance pallet refactoring.

The autogenerated weights correctly reflect the architectural changes:

  • Removal of curator management functions (add_curator, remove_curator)
  • Addition of freezing toggle functions (toggle_agent_freezing, toggle_namespace_freezing)
  • Integration with the new Permission0 pallet

Also applies to: 57-58


86-211: Weight increases are justified by Permission0 integration.

The significant increases in execution time and storage operations for whitelist management and application functions (lines 86-211) are expected due to:

  • Permission checks now requiring 4 additional storage reads/writes for Permission0 indices
  • Larger proof sizes (up to 11KB) for permission data structures
  • Enforcement of curator permissions through the Permission0 pallet

This aligns with the PR's objective of replacing direct curator management with a comprehensive permission system.

pallets/torus0/src/migrations.rs (1)

103-108: Hardcoded burn configuration values need validation.

The migration sets specific burn values:

  • min_burn: 15 TORS
  • max_burn: 1000 TORS
  • max_registrations_per_interval: 16

These hardcoded values should be validated against the network's economic model.

Are these burn configuration values aligned with the tokenomics design? Consider making them configurable or documenting the rationale for these specific values.

pallets/faucet/src/faucet.rs (1)

65-68: Consider the implications of u64 block number conversion.

The conversion from BlockNumberFor<T> to u64 could fail if the block number exceeds u64::MAX. While this is unlikely in practice, consider documenting this limitation or using a larger type.

pallets/emission0/src/distribute.rs (1)

14-15: Verify the impact of changing from I96F32 to FixedU128.

The change from I96F32 to FixedU128 represents a significant change in numeric representation. Ensure that:

  1. The precision is sufficient for all calculations
  2. Existing stored values are properly migrated
  3. The change doesn't affect emission calculations adversely
pallets/permission0/src/permission.rs (1)

83-140: Well-implemented revocation logic with proper authorization.

The revocation method handles multiple authorization scenarios correctly, including multi-signature voting and time-based revocation. The implementation properly tracks votes and ensures proper cleanup.

pallets/torus0/api/src/lib.rs (1)

79-214: Well-implemented namespace path validation and navigation.

The NamespacePath implementation provides comprehensive validation with clear rules for segments, proper bounds checking, and useful navigation methods (parent, parents, is_parent_of). The test coverage is thorough.

pallets/torus0/src/agent.rs (1)

174-176: Document or prevent cooldown bypass via re-registration

The update cooldown can be bypassed by unregistering and re-registering an agent. If this is intentional, it should be documented. Otherwise, consider tracking cooldowns separately from agent records.

Is bypassing the cooldown through re-registration an intended feature? If not, consider maintaining a separate cooldown storage that persists across registrations.

Also applies to: 215-236

pallets/emission0/src/distribute/math.rs (7)

11-29: LGTM! Safe refactoring to FixedU128.

The normalization functions correctly use saturating_add for accumulation and const_checked_div with fallback to prevent division by zero.


209-215: Good adaptation of comparison logic for FixedU128.

The assert helpers correctly use into_inner().abs_diff() for comparing FixedU128 values, which is appropriate for the internal representation.


145-154: Conversion logic verified – no additional bounds checks needed.

The divisor FixedU128::DIV is a non-zero compile-time constant, so the raw u128.checked_div(FixedU128::DIV) will never return None.
The ratio is computed to map the largest element to u16::MAX, and saturating_mul guarantees no intermediate overflow. Casting the final quotient to u16 is therefore safe.


5-29: Proper migration to FixedU128 with safe arithmetic.

The refactoring correctly uses saturating arithmetic and checked division, preventing overflow and division by zero errors.


45-92: Sparse matrix operations correctly handle FixedU128.

Excellent use of pattern matching for bounds checking and consistent application of saturating arithmetic throughout the sparse matrix operations.


162-237: Well-designed test infrastructure for FixedU128.

The epsilon-based comparison functions properly handle floating-point precision issues in tests.


239-310: Comprehensive test coverage with appropriate precision checks.

Tests properly verify mathematical operations with FixedU128, including edge cases and precision validation.

pallets/torus0/src/lib.rs (2)

141-163: Well-designed namespace storage structure.

The double map for namespaces with ownership and path as keys provides efficient lookups, and the count tracking enables proper limit enforcement.


564-595: Good API extensions for staking and namespace queries.

The new sum_staking_to and namespace_exists methods provide useful query capabilities for the extended functionality.

pallets/permission0/src/ext/emission_impl.rs (2)

222-256: Correct implementation of manual permission execution.

The function properly validates the distribution method, accumulation state, and ensures non-zero amounts before distribution.


259-331: Well-implemented enforcement voting mechanism.

The function correctly handles different authorization levels (root, grantor, controllers) and properly tracks/clears votes for the accumulation toggle.

pallets/governance/src/lib.rs (3)

207-247: Excellent integration with the permission system.

The curator permission checks are consistently applied with appropriate flags for each operation type (whitelist, application review).


391-427: Clean implementation of freezing controls.

The toggle functions properly check curator permissions and emit informative events including the curator's identity.


589-595: Good permission logic for frozen states.

The implementation correctly allows whitelisted accounts to bypass freezing restrictions, providing flexibility for trusted entities.

pallets/permission0/api/src/lib.rs (2)

14-90: Well-designed permission system types.

The use of H256 for IDs and comprehensive enums for allocation, distribution, duration, revocation, and enforcement provides a flexible and extensible permission framework.


128-142: Well-structured curator permission flags.

The bitflags implementation provides efficient permission checking with clear, descriptive flag names and proper bit spacing.

pallets/governance/src/proposal.rs (3)

104-105: Namespace pricing config integration looks good

The addition of namespace_pricing_config to global parameters is properly integrated with validation, storage updates, and struct definitions.

Also applies to: 118-119, 237-238


666-689: Fixed-point arithmetic implementation looks solid

The migration to FixedU128 with checked arithmetic operations (const_checked_mul, const_checked_div) provides safe and precise calculations for the exponential decay formula.


569-589: Delegation-aware stake calculation is well implemented

The function correctly prevents double-counting by zeroing own stake for delegating voters and properly aggregates delegated stakes.

docs/permission0.md (1)

1-517: Excellent comprehensive documentation for Permission0 pallet

The documentation provides thorough coverage of:

  • Permission contract architecture and lifecycle
  • Emission and curator permission scopes
  • Distribution control mechanisms
  • Enforcement authority system with multi-sig governance
  • Storage design optimized for performance
  • Integration with emission distribution
  • Clear code examples and flow diagrams

The technical content is accurate and the explanations are clear.

pallets/emission0/src/lib.rs (5)

9-15: LGTM! Import consolidation improves readability.

The consolidation of polkadot_sdk imports into a single use statement follows Rust best practices.


41-69: Storage items are well-structured and documented.

The new storage items properly support the permission management integration with appropriate types and value queries.


149-150: Error variant properly added.

The WeightControlNotEnabled error follows the existing naming convention and is well-documented.


179-179: Good security practice to ensure signed origin.

Explicitly validating the origin as signed before delegation prevents unauthorized access and follows security best practices.


220-225: API method correctly implements delegation.

The new delegate_weight_control method properly forwards to the internal implementation with appropriate parameter handling.

Comment on lines +9 to +10
[lints]
workspace = true
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

[lints] table is unstable and requires nightly Cargo

The lints table is guarded by the -Z lints nightly feature. Building this crate with stable toolchains will error with “unknown table”. Ensure CI enforces nightly, or move these settings to package.metadata / wait for stabilization.

🤖 Prompt for AI Agents
In pallets/governance/api/Cargo.toml at lines 9 to 10, the use of the unstable
[lints] table requires a nightly Cargo toolchain and causes errors on stable
builds. To fix this, either configure the CI to use a nightly Rust toolchain or
remove the [lints] table from Cargo.toml and move any necessary lint settings
under package.metadata or wait until the feature stabilizes before using it.

torus-node:
container_name: torus-node
image: ghcr.io/renlabs-dev/torus-substrate:f6efa2e
image: ghcr.io/renlabs-dev/torus-substrate:latest
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using a specific version tag instead of latest.

Using latest tag can lead to non-reproducible builds and unexpected behavior when the image is updated. Consider pinning to a specific version or commit hash for production deployments.

-    image: ghcr.io/renlabs-dev/torus-substrate:latest
+    image: ghcr.io/renlabs-dev/torus-substrate:v1.0.0  # Use specific version
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
image: ghcr.io/renlabs-dev/torus-substrate:latest
image: ghcr.io/renlabs-dev/torus-substrate:v1.0.0 # Use specific version
🤖 Prompt for AI Agents
In docker-compose.yml at line 4, the image tag is set to 'latest', which can
cause non-reproducible builds and unexpected behavior. Replace 'latest' with a
specific version tag or commit hash of the image to ensure consistent and
predictable deployments.

build-n-push:
permissions: write-all
runs-on: ubuntu-22.04-32core-karl
runs-on: ubicloud-standard-16
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

❓ Verification inconclusive

Verify the custom runner label configuration.

The runner label ubicloud-standard-16 is not recognized as a standard GitHub Actions runner. If this is a custom self-hosted runner, ensure it's properly configured and consider documenting the runner requirements.


🏁 Script executed:

#!/bin/bash
# Description: Check if ubicloud runner configuration is documented in the repository

# Search for ubicloud runner documentation or configuration
rg -i "ubicloud" --type md
rg -i "runner.*16" --type md
rg -i "self-hosted" --type md

Length of output: 87


Include the self-hosted label and document your custom runner

The workflow is currently targeting only ubicloud-standard-16, which isn’t a GitHub-hosted runner. To ensure this job picks up your self-hosted machine and to make the requirement discoverable, update the runner label and add (or link to) documentation.

• .github/workflows/build-docker-node.yml:20

  • Change the single string to an array including self-hosted.
  • Example diff:
-   runs-on: ubicloud-standard-16
+   runs-on:
+     - self-hosted
+     - ubicloud-standard-16

• Docs:

  • Create or update a section (e.g. in README.md or a new RUNNERS.md) that describes the setup, OS requirements, and any pre-installed software for your ubicloud-standard-16 runner.
  • Reference this documentation from your CONTRIBUTING or CI guide.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
runs-on: ubicloud-standard-16
runs-on:
- self-hosted
- ubicloud-standard-16
🧰 Tools
🪛 actionlint (1.7.7)

20-20: label "ubicloud-standard-16" is unknown. available labels are "windows-latest", "windows-latest-8-cores", "windows-2025", "windows-2022", "windows-2019", "ubuntu-latest", "ubuntu-latest-4-cores", "ubuntu-latest-8-cores", "ubuntu-latest-16-cores", "ubuntu-24.04", "ubuntu-24.04-arm", "ubuntu-22.04", "ubuntu-22.04-arm", "ubuntu-20.04", "macos-latest", "macos-latest-xl", "macos-latest-xlarge", "macos-latest-large", "macos-15-xlarge", "macos-15-large", "macos-15", "macos-14-xl", "macos-14-xlarge", "macos-14-large", "macos-14", "macos-13-xl", "macos-13-xlarge", "macos-13-large", "macos-13", "self-hosted", "x64", "arm", "arm64", "linux", "macos", "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file

(runner-label)

🤖 Prompt for AI Agents
In .github/workflows/build-docker-node.yml at line 20, change the runner
specification from a single string "ubicloud-standard-16" to an array including
"self-hosted" and "ubicloud-standard-16" to ensure the job targets your
self-hosted runner properly. Additionally, create or update documentation (e.g.,
README.md or a new RUNNERS.md) describing the setup, OS requirements, and
pre-installed software for the "ubicloud-standard-16" runner, and reference this
documentation from your CONTRIBUTING or CI guide to make the requirement clear
and discoverable.

Comment on lines +19 to +35
FROM debian:bullseye-slim

WORKDIR /app

RUN apt-get update && apt install -y --no-install-recommends \
ca-certificates \
curl \
build-essential \
protobuf-compiler \
libclang-dev \
git \
pkg-config \
libssl-dev

COPY --from=builder /usr/src/app/target/release/xtask /usr/local/bin

ENTRYPOINT ["xtask"]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize runtime stage by removing unnecessary build dependencies.

The runtime stage includes the same build dependencies as the builder stage, which defeats the purpose of a multi-stage build. The runtime stage should only include dependencies needed to run the binary, not build tools.

 FROM debian:bullseye-slim
 
 WORKDIR /app
 
 RUN apt-get update && apt install -y --no-install-recommends \
     ca-certificates \
-    curl \
-    build-essential \
-    protobuf-compiler \
-    libclang-dev \
-    git \
-    pkg-config \
-    libssl-dev
+    libssl1.1 \
+    && rm -rf /var/lib/apt/lists/*
 
 COPY --from=builder /usr/src/app/target/release/xtask /usr/local/bin
 
 ENTRYPOINT ["xtask"]

This optimization reduces the final image size by removing unnecessary build tools while keeping only the runtime dependencies needed for SSL connections.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
FROM debian:bullseye-slim
WORKDIR /app
RUN apt-get update && apt install -y --no-install-recommends \
ca-certificates \
curl \
build-essential \
protobuf-compiler \
libclang-dev \
git \
pkg-config \
libssl-dev
COPY --from=builder /usr/src/app/target/release/xtask /usr/local/bin
ENTRYPOINT ["xtask"]
FROM debian:bullseye-slim
WORKDIR /app
RUN apt-get update && apt install -y --no-install-recommends \
ca-certificates \
libssl1.1 \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /usr/src/app/target/release/xtask /usr/local/bin
ENTRYPOINT ["xtask"]
🤖 Prompt for AI Agents
In docker/xtask.dockerfile lines 19 to 35, the runtime stage installs build
dependencies that are unnecessary for running the binary. Remove all build tools
and development packages like build-essential, protobuf-compiler, libclang-dev,
git, and pkg-config from the runtime stage. Keep only essential runtime
dependencies such as ca-certificates and libssl-dev to minimize the final image
size while ensuring the binary runs correctly.

Comment on lines +81 to +83
let alpha = FixedU128::from_inner(adjustment_alpha as u128)
.const_checked_div(FixedU128::from_inner(u64::MAX as u128))
.unwrap_or_else(|| FixedU128::from_inner(0));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Potential division by zero vulnerability.

The alpha calculation uses u64::MAX as divisor, but the unwrap_or_else fallback to zero could mask division errors. Consider using a non-zero fallback value that maintains the intended alpha scaling behavior.

-    let alpha = FixedU128::from_inner(adjustment_alpha as u128)
-        .const_checked_div(FixedU128::from_inner(u64::MAX as u128))
-        .unwrap_or_else(|| FixedU128::from_inner(0));
+    let alpha = FixedU128::from_inner(adjustment_alpha as u128)
+        .const_checked_div(FixedU128::from_inner(u64::MAX as u128))
+        .unwrap_or_else(|| FixedU128::from_inner(1)); // Use 1 instead of 0 to maintain scaling
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let alpha = FixedU128::from_inner(adjustment_alpha as u128)
.const_checked_div(FixedU128::from_inner(u64::MAX as u128))
.unwrap_or_else(|| FixedU128::from_inner(0));
let alpha = FixedU128::from_inner(adjustment_alpha as u128)
.const_checked_div(FixedU128::from_inner(u64::MAX as u128))
.unwrap_or_else(|| FixedU128::from_inner(1)); // Use 1 instead of 0 to maintain scaling
🤖 Prompt for AI Agents
In pallets/torus0/src/burn.rs around lines 81 to 83, the division uses u64::MAX
as the divisor and unwrap_or_else falls back to zero on error, which may mask
division issues. To fix this, ensure the divisor is never zero before division
or replace unwrap_or_else with proper error handling or a fallback value that
preserves the alpha scaling logic instead of zero, preventing silent masking of
division errors.

Comment on lines +595 to +604
let block_number: u64 = block_number
.try_into()
.ok()
.expect("blocknumber wont be greater than 2^64");
let proposal_reward_interval: u64 = governance_config
.proposal_reward_interval
.try_into()
.ok()
.expect("blocknumber wont be greater than 2^64");

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace multiple .expect() calls with safer conversions

The function has multiple panic points from .expect() calls during type conversions.

Apply safer conversions:

-    let block_number: u64 = block_number
-        .try_into()
-        .ok()
-        .expect("blocknumber wont be greater than 2^64");
-    let proposal_reward_interval: u64 = governance_config
-        .proposal_reward_interval
-        .try_into()
-        .ok()
-        .expect("blocknumber wont be greater than 2^64");
+    let block_number: u64 = block_number
+        .try_into()
+        .unwrap_or(u64::MAX);
+    let proposal_reward_interval: u64 = governance_config
+        .proposal_reward_interval
+        .try_into()
+        .unwrap_or(100); // Use default interval if conversion fails

And similarly for the proposal block conversion:

-        let proposal_block: u64 = unrewarded_proposal
-            .block
-            .try_into()
-            .ok()
-            .expect("blocknumber wont be greater than 2^64");
+        let proposal_block: u64 = unrewarded_proposal
+            .block
+            .try_into()
+            .unwrap_or(0); // Treat as old proposal if conversion fails

Also applies to: 616-621

🤖 Prompt for AI Agents
In pallets/governance/src/proposal.rs around lines 595 to 604 and also 616 to
621, the code uses multiple .expect() calls on type conversions which can cause
panics. Replace these .expect() calls with safer conversion methods such as
using match statements or if let constructs to handle the Result or Option
returned by try_into(), and handle the error cases gracefully without panicking,
for example by returning a Result or logging an error.

Comment on lines +438 to +442
.try_into()
.ok()
.expect("blocknumber wont be greater than 2^64");
if block_number_u64 % 100 != 0 {
return;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle block number conversion more safely

The conversion could theoretically panic if BlockNumberFor<T> exceeds u64::MAX. While unlikely, this runs frequently and a panic would be critical.

Apply this diff for safer conversion:

-    let block_number_u64: u64 = block_number
-        .try_into()
-        .ok()
-        .expect("blocknumber wont be greater than 2^64");
+    let block_number_u64: u64 = block_number
+        .try_into()
+        .unwrap_or(u64::MAX);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let block_number_u64: u64 = block_number
.try_into()
.ok()
.expect("blocknumber wont be greater than 2^64");
if block_number_u64 % 100 != 0 {
let block_number_u64: u64 = block_number
.try_into()
.unwrap_or(u64::MAX);
if block_number_u64 % 100 != 0 {
🤖 Prompt for AI Agents
In pallets/governance/src/proposal.rs around lines 438 to 442, the conversion of
block_number to u64 uses expect which can panic if the value exceeds u64::MAX.
To fix this, replace the expect call with proper error handling that safely
deals with the conversion failure without panicking, such as returning an error
or using a fallback, ensuring the code does not panic even in edge cases.

Comment on lines 549 to 557
for (key, value) in votes_for {
reward_votes_for
.try_insert(key, value)
.expect("this wont exceed u32::MAX");
let _ = reward_votes_for.try_insert(key, value);
}

let mut reward_votes_against: BoundedBTreeMap<
T::AccountId,
BalanceOf<T>,
ConstU32<{ u32::MAX }>,
> = BoundedBTreeMap::new();
let mut reward_votes_against: AccountStakes<T> = BoundedBTreeMap::new();
for (key, value) in votes_against {
reward_votes_against
.try_insert(key, value)
.expect("this probably wont exceed u32::MAX");
let _ = reward_votes_against.try_insert(key, value);
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Log errors when map insertions fail

Using let _ = silently ignores insertion failures when the BoundedBTreeMap reaches capacity. This makes debugging difficult.

Consider logging failures:

    let mut reward_votes_for = BoundedBTreeMap::new();
    for (key, value) in votes_for {
-        let _ = reward_votes_for.try_insert(key, value);
+        if reward_votes_for.try_insert(key, value).is_err() {
+            error!("Failed to insert vote for account {:?} in proposal {}", key, proposal_id);
+        }
    }

    let mut reward_votes_against: AccountStakes<T> = BoundedBTreeMap::new();
    for (key, value) in votes_against {
-        let _ = reward_votes_against.try_insert(key, value);
+        if reward_votes_against.try_insert(key, value).is_err() {
+            error!("Failed to insert vote against account {:?} in proposal {}", key, proposal_id);
+        }
    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let mut reward_votes_for = BoundedBTreeMap::new();
for (key, value) in votes_for {
reward_votes_for
.try_insert(key, value)
.expect("this wont exceed u32::MAX");
let _ = reward_votes_for.try_insert(key, value);
}
let mut reward_votes_against: BoundedBTreeMap<
T::AccountId,
BalanceOf<T>,
ConstU32<{ u32::MAX }>,
> = BoundedBTreeMap::new();
let mut reward_votes_against: AccountStakes<T> = BoundedBTreeMap::new();
for (key, value) in votes_against {
reward_votes_against
.try_insert(key, value)
.expect("this probably wont exceed u32::MAX");
let _ = reward_votes_against.try_insert(key, value);
}
let mut reward_votes_for = BoundedBTreeMap::new();
for (key, value) in votes_for {
if reward_votes_for.try_insert(key, value).is_err() {
error!(
"Failed to insert vote for account {:?} in proposal {}",
key, proposal_id
);
}
}
let mut reward_votes_against: AccountStakes<T> = BoundedBTreeMap::new();
for (key, value) in votes_against {
if reward_votes_against.try_insert(key, value).is_err() {
error!(
"Failed to insert vote against account {:?} in proposal {}",
key, proposal_id
);
}
}
🤖 Prompt for AI Agents
In pallets/governance/src/proposal.rs around lines 549 to 557, the code silently
ignores errors from try_insert calls on BoundedBTreeMap, which can hide capacity
issues. Modify the code to check the Result returned by try_insert for errors
and log an appropriate error message when insertion fails, including relevant
details like the key and value that failed to insert.

Comment on lines +51 to +58
match self.data {
ProposalData::Emission { .. } => self.creation_block.saturating_add(21_600),
ProposalData::Emission { .. } => self.creation_block.saturating_add(
U256::from(21_600)
.try_into()
.ok()
.expect("this is a safe conversion"),
),
_ => self.expiration_block,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace .expect() with proper error handling

The conversion from U256 to BlockNumberFor<T> could fail if the value exceeds the target type's capacity. While 21,600 is small, using .expect() in production code is risky.

Apply this diff to handle the conversion safely:

-            ProposalData::Emission { .. } => self.creation_block.saturating_add(
-                U256::from(21_600)
-                    .try_into()
-                    .ok()
-                    .expect("this is a safe conversion"),
-            ),
+            ProposalData::Emission { .. } => {
+                let emission_delay = U256::from(21_600)
+                    .try_into()
+                    .unwrap_or_else(|_| {
+                        // Use a sensible default if conversion fails
+                        21_600u32.into()
+                    });
+                self.creation_block.saturating_add(emission_delay)
+            }
🤖 Prompt for AI Agents
In pallets/governance/src/proposal.rs around lines 51 to 58, the code uses
`.expect()` after trying to convert a U256 value to BlockNumberFor<T>, which can
panic if the conversion fails. Replace the `.expect()` call with proper error
handling by checking if the conversion returns Some value; if it returns None,
handle the error gracefully, for example by returning a default value or
propagating an error, to avoid panics in production.

#[frame::pallet]
pub mod pallet {
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify storage migration implementation.

The storage version increment from 1 to 2 indicates breaking storage changes. Ensure the migration module properly handles the transition.


🏁 Script executed:

#!/bin/bash
# Description: Verify migration module implementation for v1 to v2

# Check if migration module exists and handles v2
fd -t f "migrations" pallets/emission0/src | xargs rg -A 10 "v2|V2|version.*2"

# Check for OnRuntimeUpgrade implementation
ast-grep --pattern 'impl$$$OnRuntimeUpgrade$$$'

Length of output: 1054


🏁 Script executed:

#!/bin/bash
# Check for pallet storage version attribute
rg -n '\[pallet::storage_version' -n pallets/emission0/src/lib.rs

# Check for migrations attribute in pallet macro
rg -n '\[pallet::migrations' -n pallets/emission0/src/lib.rs

# Check for Hooks implementation
rg -n 'impl.*Hooks' -n pallets/emission0/src/lib.rs

# Check for VersionedMigration usage in lib.rs
rg -n 'VersionedMigration' -n pallets/emission0/src/lib.rs

Length of output: 360


🏁 Script executed:

#!/bin/bash
# Verify whether the pallet macro registers the migrations module
rg -n '#\[pallet::pallet' -A 5 pallets/emission0/src/lib.rs

Length of output: 267


Ensure the migration is registered in the pallet macro

While you’ve correctly added StorageVersion::new(2) and provided an UncheckedOnRuntimeUpgrade impl under migrations/v2, there’s no #[pallet::migrations] attribute on the pallet to wire it up. Without it, your v1→v2 migration won’t run.

Please update your pallet declaration in pallets/emission0/src/lib.rs to include:

 #[pallet::pallet]
+#[pallet::migrations]
 #[pallet::storage_version(STORAGE_VERSION)]
 pub struct Pallet<T>(_);

This will ensure Substrate invokes your VersionedMigration<1, 2, …> on runtime upgrade.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In pallets/emission0/src/lib.rs at line 27, you have set STORAGE_VERSION to 2
and implemented the migration logic, but you have not registered the migration
in the pallet macro. To fix this, update your pallet declaration by adding the
#[pallet::migrations] attribute with your VersionedMigration from version 1 to
2. This will ensure the migration runs automatically on runtime upgrade.

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: 0

🧹 Nitpick comments (4)
CHANGELOG.md (4)

23-25: Comma missing between two independent clauses

Insert a comma after “treasury” to avoid a run-on sentence.

- - Base fees go to treasury while refundable deposits incentivize efficient storage use.
+ - Base fees go to the treasury, while refundable deposits incentivize efficient storage use.

49-51: Minor punctuation for clarity

Add a comma after “refunded”; it improves readability and matches the pause you’d use when reading aloud.

- - Critical fix ensuring stakes are properly refunded before clearing storage during de-registration.
+ - Critical fix ensuring stakes are properly refunded, before clearing storage during de-registration.

118-118: Use a proper heading instead of bold emphasis

Markdown-lint flags this (MD036). Convert the bold text to a heading to keep style consistent with the rest of the changelog.

-**Original Stakers (OS)**
+#### Original Stakers (OS)

3-3: Header naming consistency

Earlier specs use “Spec version X”. Consider aligning the new header with that pattern for uniform navigation.

-## Spec 21
+## Spec version 21
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 498642d and e0b999d.

📒 Files selected for processing (1)
  • CHANGELOG.md (2 hunks)
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.md

[uncategorized] ~24-~24: Possible missing comma found.
Context: ...legation of services. - Base fees go to treasury while refundable deposits incentivize e...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~50-~50: Possible missing comma found.
Context: ...Fixes & Safety Improvements - Critical fix ensuring stakes are properly refunded b...

(AI_HYDRA_LEO_MISSING_COMMA)

🪛 markdownlint-cli2 (0.17.2)
CHANGELOG.md

118-118: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: check
  • GitHub Check: build-n-push
  • GitHub Check: check

@saiintbrisson saiintbrisson changed the title Dev Spec 21 Jul 7, 2025
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: 0

🧹 Nitpick comments (5)
CLAUDE.md (5)

1-4: File name & audience could be clearer

Naming the contributor-facing guideline file CLAUDE.md (and addressing “Claude Code” on line 3) may confuse newcomers who are not aware of the internal AI workflow. Consider renaming to something neutral such as CODING_GUIDELINES.md and removing persona-specific wording to keep the repository contributor-centric.


11-16: Broken intra-repo links – use relative Markdown links

Using the @README.md syntax is not standard Markdown and will not render as a link on GitHub. Replace with relative links ([README.md](./README.md), etc.) so the references are clickable in the web UI.


65-70: Absolute ban on raw operators may need scoped exceptions

Forbidding every use of + – * / (even on literals or compile-time constants) can lead to noisy saturating_* wrappers in obviously safe contexts and hinders readability. Clarify that the prohibition targets runtime balance/math in pallets, allowing constants and test code to use plain operators.


88-92: Manual call_index requires collision checks

Mandating #[pallet::call_index(n)] for every extrinsic is good for stability but error-prone during refactors. Add a CI script or xtask that scans pallets to verify there are no duplicate indices and that they remain stable across migrations.


149-149: Heading with trailing colon violates markdownlint rule

The “Before committing:” heading triggers MD026. Remove the trailing colon for clean lint passes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0b999d and 7952818.

📒 Files selected for processing (1)
  • CLAUDE.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
CLAUDE.md

[uncategorized] ~19-~19: Loose punctuation mark.
Context: ...gorithm ## Core Pallets - torus0: Agent registration, staking, burn mecha...

(UNLIKELY_OPENING_PUNCTUATION)


[grammar] ~97-~97: It appears that a hyphen is missing in the plural noun “to-dos”?
Context: ...d to client SDKs - MUST NEVER leave TODOs or incomplete implementations in produc...

(TO_DO_HYPHEN)

🪛 markdownlint-cli2 (0.17.2)
CLAUDE.md

149-149: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: check
  • GitHub Check: check
  • GitHub Check: build-n-push
🔇 Additional comments (1)
CLAUDE.md (1)

101-104: Umbrella-crate rule may conflict with upstream changes

polkadot_sdk is in flux; newer Substrate versions occasionally reorganise modules. Re-confirm that pinning to the umbrella crate will not block future upgrades or require work-arounds for crates still outside polkadot_sdk (e.g., benchmarking helpers).

@github-actions
Copy link

github-actions bot commented Jul 7, 2025

Code Coverage

Package Line Rate Health
pallets.permission0.src 84%
pallets.governance.src 93%
pallets.permission0.src.ext 91%
pallets.emission0.src 92%
pallets.permission0.src.permission 79%
pallets.emission0.src.distribute 90%
pallets.torus0.api.src 79%
pallets.torus0.src 96%
pallets.permission0.api.src 83%
Summary 90% (2969 / 3281)

@github-actions
Copy link

github-actions bot commented Jul 7, 2025

Detailed coverage report

@saiintbrisson saiintbrisson merged commit 80af423 into main Jul 7, 2025
5 checks passed
This was referenced Aug 10, 2025
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.

6 participants