Skip to content

Conversation

@saiintbrisson
Copy link
Collaborator

@saiintbrisson saiintbrisson commented Aug 10, 2025

Check all the changes in CHANGELOG.md, entries 22 and 23.

Summary by CodeRabbit

  • New Features

    • Introduced a type-safe, ergonomic Rust client library for interacting with the Torus blockchain, including auto-generated interfaces for storage, extrinsics, events, and RPCs.
    • Added command-line tools for project metadata selection and code generation.
    • Enhanced permission delegation with hierarchical, instance-limited curator and namespace permissions, including support for multi-parent delegation and revocation cascades.
    • Improved staking to use named reserves, ensuring staked tokens remain in user balances.
  • Improvements

    • Streamlined agent registration by removing redundant parameters and enforcing unique agent names.
    • Refined event and error naming for clarity and consistency (e.g., "grantor/grantee" → "delegator/recipient", "unregister" → "deregister").
    • Granular event emission for namespace creation and deletion.
    • Improved documentation and changelogs for recent runtime changes.
  • Bug Fixes

    • Enhanced error handling and validation in staking, permission, and namespace operations.
    • Fixed edge cases in fee and deposit calculations for namespaces.
  • Documentation

    • Updated and expanded user and developer documentation, including detailed migration and changelog guides.
  • Chores

    • Updated dependencies, configuration files, and build scripts to support new features and improved developer tooling.
  • Tests

    • Added and updated comprehensive tests covering permission delegation, staking, agent lifecycle, and namespace management.
  • Refactor/Style

    • Refactored codebase for improved readability, maintainability, and consistent terminology.
    • Reordered imports and improved code style throughout the project.
  • Migrations

    • Added runtime migrations for permission and staking systems to ensure seamless upgrades and data integrity.

saiintbrisson and others added 25 commits July 7, 2025 12:41
Substrate development is HEAVY. Our simple chain has over 2000
dependencies in total, most of which are unused and just included
because of the umbrella dependency `polkadot-sdk`.

This new crate allows you to select which crates and dependencies
you want rust-analyzer to index:

```sh
just select
just select pallet-torus0,pallet-emission0
just select node 1 # will only fetch up to second-level transient dependencies
```
…119)

Renames the permission terminology from Grantor/Grantee/Grant to
Delegator/Recipient/Delegate. This plays better with the terminology
throughout the project.
The built-in chain specfile for main and testnet have been out of date
for a while. This patch updates it to ship with a new one containing the
correct bootnodes.

Closes CHAIN-117
Because an agent can now exist without being whitelisted, it doesn't
make sense to de-register it when removed from the whitelist. Closes
CHAIN-118.
This change stops the charging of deposit and fee when registering an
agent regarding the root namespace created. Only the agent burn will
charged when registering.

Closes CHAIN-119.
Emit events on emission accumulation and distribution. This helps
tracking where streams are flowing to. This change replaces
`PermissionExecuted` and `AutoDistributionExecuted` for
`EmissionDistribution` with a `reason` field and a new
`AccumulatedEmission`.
This change limits to whom you may delegate a namespace permission. From
now on, only registered agents will be eligible for receiving namespace
contracts. Closes CHAIN-114.
Some entries in the accumulation storage were lost in the early
permission0 days. This migration patch re-inserts them, resuming the
accumulation and distribution of tokens.

Closes CHAIN-115
This change prevents errors that might happen when we wrongly track
stake changes. By moving to reserved balances, we avoid minting tokens
when unstaking from accounts.

Closes CHAIN-104.
This patch introduces the first version of namespace permission
re-delegation.

Closes CHAIN-107.
# Interface Changes: Permission Redelegation and Cascading Revocation

## Extrinsic Signature Changes

### `delegate_namespace_permission` - BREAKING CHANGE
```rust
// BEFORE
pub fn delegate_namespace_permission(
    origin: OriginFor<T>,
    recipient: T::AccountId,
    paths: BoundedBTreeSet<NamespacePathInner, T::MaxNamespacesPerPermission>,
    duration: PermissionDuration<T>,
    revocation: RevocationTerms<T>,
) -> DispatchResult

// AFTER
pub fn delegate_namespace_permission(
    origin: OriginFor<T>,
    recipient: T::AccountId,
    paths: BoundedBTreeMap<
        Option<PermissionId>,  // Parent permission (None for root)
        BoundedBTreeSet<NamespacePathInner, T::MaxNamespacesPerPermission>,
        T::MaxNamespacesPerPermission,
    >,  // Now supports inheritance from parent permissions
    duration: PermissionDuration<T>,
    revocation: RevocationTerms<T>,
    instances: u32,  // ADDED: Max re-delegation capacity
) -> DispatchResult
```

## Structure Changes

### `PermissionContract<T>` - BREAKING CHANGES
```rust
// BEFORE
pub struct PermissionContract<T: Config> {
    ...
    pub parent: Option<PermissionId>,  // REMOVED
}

// AFTER
pub struct PermissionContract<T: Config> {
    ...
    pub max_instances: u32,                         // ADDED: Controls re-delegation capacity
    pub children: BoundedBTreeSet<H256, T::MaxChildrenPerPermission>, // ADDED: Enables cascading revocation
}
```

### `NamespaceScope<T>` - BREAKING CHANGE
```rust
// BEFORE
pub struct NamespaceScope<T: Config> {
    pub paths: BoundedBTreeSet<NamespacePath, T::MaxNamespacesPerPermission>,
}

// AFTER
pub struct NamespaceScope<T: Config> {
    pub paths: BoundedBTreeMap<
        Option<PermissionId>,      // Parent permission that granted these paths.
                                   // None if path belongs to delegator itself
        BoundedBTreeSet<NamespacePath, T::MaxNamespacesPerPermission>,
        T::MaxNamespacesPerPermission,
    >,
}
```

## Behavioral Changes

### Instance Management
- `max_instances` controls how many child permissions can be created
- Each child consumes instances from parent, preventing unlimited
delegation

### Inheritance Validation
- Child permissions must have weaker or equal revocation terms than
parent
- Namespace paths must be accessible through parent permissions
- Supports granular delegation of more specific namespaces

### Cascading Revocation
- Revoking a permission automatically revokes ALL child permissions
recursively
- Multiple `PermissionRevoked` events emitted for each revoked
permission

## Migration Impact
- All existing permissions get `max_instances = 1` and empty `children`
set

## Client SDK Requirements
1. Update `delegate_namespace_permission` call construction
2. Handle new error variants in error handling
3. Update struct parsing for `PermissionContract` and `NamespaceScope`
4. Change event listening from `Permissiondelegated` to
`PermissionDelegated`
5. Use accessor methods instead of direct field access
6. Implement cascading revocation event handling
7. Add hierarchy validation using `RevocationTerms::is_weaker()`
This change finished CHAIN-105 by implementing the same re-delegation
system for curator scopes.
This pull request adds the torus-client `client/` to the repo complete
with examples and readme.

---------

Co-authored-by: Kelvin Steiner <[email protected]>
Co-authored-by: Luiz Carvalho <[email protected]>
@coderabbitai
Copy link

coderabbitai bot commented Aug 10, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces a comprehensive overhaul of the permission and agent systems, focusing on renaming core entities from "grantor/grantee" to "delegator/recipient" and shifting from permission granting to hierarchical delegation. It implements deep changes to the permission0 and torus0 pallets, including new extrinsics, storage structures, migration logic, staking mechanics, event emission, and extensive test and documentation updates. The runtime version is incremented, and new migrations are added.

Changes

Cohort / File(s) Change Summary
Permission System Overhaul
pallets/permission0/src/lib.rs, pallets/permission0/src/permission.rs, pallets/permission0/src/permission/curator.rs, pallets/permission0/src/permission/emission.rs, pallets/permission0/src/permission/namespace.rs, pallets/permission0/src/ext.rs, pallets/permission0/src/ext/curator_impl.rs, pallets/permission0/src/ext/emission_impl.rs, pallets/permission0/src/ext/namespace_impl.rs, pallets/permission0/src/benchmarking.rs, pallets/permission0/src/weights.rs, pallets/permission0/src/migrations.rs, pallets/permission0/tests/*
Refactors permission logic from "granting" to "delegating," renames entities to "delegator/recipient," introduces hierarchical curator and namespace permission delegation, adds instance tracking, new error variants, new configuration constants, and new migration logic. Updates all related extrinsics, storage, events, and tests.
Agent System and Staking Overhaul
pallets/torus0/src/lib.rs, pallets/torus0/src/agent.rs, pallets/torus0/src/stake.rs, pallets/torus0/src/namespace.rs, pallets/torus0/src/benchmarking.rs, pallets/torus0/src/weights.rs, pallets/torus0/src/migrations.rs, pallets/torus0/tests/*
Removes explicit agent_key parameter, switches agent removal from "unregister" to "deregister," overhauls staking to use named reserves, updates event emissions, adds new migration for staking, and updates all related tests and documentation.
Runtime and Config Updates
runtime/src/lib.rs, runtime/src/configs.rs, runtime/src/apis.rs, runtime/src/configs/eth.rs
Increments runtime spec version, updates migration tuple, adds new permission and staking configuration constants, updates type aliases, and reorders imports.
Emission and Governance Adjustments
pallets/emission0/src/lib.rs, pallets/emission0/src/distribute.rs, pallets/emission0/src/distribute/math.rs, pallets/emission0/src/migrations.rs, pallets/emission0/tests/*, pallets/governance/src/*, pallets/governance/tests/*
Renames "registered" to "whitelisted" for agents, updates event and error terminology, removes obsolete migrations, updates permission API usage, and adjusts test logic accordingly.
API and Documentation Synchronization
pallets/permission0/api/src/lib.rs, pallets/torus0/api/src/lib.rs, docs/permission0.md, docs/namespace.md, docs/changes/spec-22.md, docs/changes/spec-23.md, CHANGELOG.md, CLAUDE.md
Updates API traits and documentation to match new delegation semantics, renames methods and parameters, and details migration and behavioral changes in changelogs and specs.
Client Library and Code Generation
client/*, client/codegen/*, client/examples/*, Cargo.toml, client/Cargo.toml, client/codegen/Cargo.toml, client/codegen/src/*
Introduces a new Rust client library for the Torus blockchain, including code generation from runtime metadata, async build scripts, workspace configuration, and usage examples.
Project Selector Tool
project-selector/Cargo.toml, project-selector/src/main.rs
Adds a new command-line tool for generating IDE-compatible project metadata from the Cargo workspace, with dependency resolution and JSON output.
Configuration and Housekeeping
.gitignore, .vscode/settings.json, justfile, flake.nix, node/Cargo.toml, node/src/*, docs/changelog_prompt.md
Updates ignore patterns, editor settings, build recipes, shell environments, node version, and adds procedural documentation for changelogs.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant Runtime
  participant Permission0
  participant Torus0
  participant Agent
  participant Storage

  User->>Runtime: Call delegate_namespace_permission (delegator, recipient, paths, ...)
  Runtime->>Permission0: Validate delegator/recipient, paths, instances
  Permission0->>Storage: Check parent permissions, delegation depth, instance limits
  Permission0->>Storage: Create PermissionContract with parent-child links
  Permission0-->>Runtime: Emit PermissionDelegated event

  User->>Runtime: Call register_agent (name, url, metadata)
  Runtime->>Torus0: Derive agent_key from origin
  Torus0->>Agent: Check uniqueness, register agent
  Torus0-->>Runtime: Emit AgentRegistered event

  User->>Runtime: Call add_stake (staker, staked, amount)
  Runtime->>Torus0: Reserve tokens using NamedReservableCurrency
  Torus0->>Storage: Update StakingTo, StakedBy, TotalStake
  Torus0-->>Runtime: Emit StakeAdded event
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90+ minutes

Possibly related PRs

  • #120: Also adds rust-project.json to .gitignore and updates VSCode Rust analyzer settings, sharing configuration changes but not core logic.
  • #92: Implements the permission0 pallet and related delegation system, directly corresponding to the permission and namespace delegation features updated in this PR.

Suggested reviewers

  • functor-flow
  • steinerkelvin
  • devwckd

Poem

In the warren of code, permissions now flow,
From delegator to recipient, the new titles bestow.
Staking is reserved, agents register with pride,
Namespace chains deepen, with parents at their side.
Migrations march onward, events now more precise—
This rabbit approves: the system feels nice!
🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link

Code Coverage

Package Line Rate Health
pallets.permission0.api.src 100%
pallets.torus0.src 96%
pallets.permission0.src.ext 88%
pallets.emission0.src 92%
pallets.governance.src 93%
pallets.emission0.src.distribute 90%
pallets.permission0.src 86%
pallets.permission0.src.permission 83%
pallets.torus0.api.src 79%
Summary 90% (3156 / 3489)

@github-actions
Copy link

Detailed coverage report

@saiintbrisson saiintbrisson merged commit 832647d into main Aug 10, 2025
4 of 5 checks passed
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.

3 participants