Skip to content

Conversation

@saiintbrisson
Copy link
Collaborator

@saiintbrisson saiintbrisson commented Aug 10, 2025

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

Summary by CodeRabbit

  • New Features

    • Introduced hierarchical permission delegation with parent-child relationships, instance tracking, and delegation depth limits for curator and namespace permissions.
    • Enhanced permission delegation APIs and events, supporting granular control and improved error handling.
    • Overhauled staking to use named reserves instead of token withdrawal/issuance.
    • Added a type-safe, auto-generated Rust client library (torus-client) with async extrinsic calls, storage access, event subscriptions, and RPC support.
    • Added command-line tools for project metadata selection and IDE integration.
  • Improvements

    • Updated terminology across the codebase from "grantor/grantee" to "delegator/recipient" for clarity and consistency.
    • Simplified agent registration and enforced unique agent names.
    • Improved event emission granularity and error reporting.
    • Added comprehensive documentation and changelogs for recent runtime specs and permission models.
  • Bug Fixes

    • Fixed agent deregistration naming and logic.
    • Improved staking and namespace operations to prevent inconsistencies and enforce correct behavior.
  • Documentation

    • Expanded technical documentation and changelogs, including migration guides and interface change summaries.
  • Tests

    • Added and updated extensive tests for permission delegation, namespace management, staking, and client usage.
  • Chores

    • Updated dependencies, build scripts, and workspace configuration for Rust 2024 edition and new client tooling.
    • Removed obsolete runtime migrations and refactored import orders for clarity.

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 change introduces a major overhaul of the permission system, agent registration, staking, and related runtime logic. It implements hierarchical permission delegation, reworks curator and namespace permissions, adds migration logic, and updates extrinsics, events, storage, and tests accordingly. The Torus client library is introduced with code generation infrastructure and comprehensive examples.

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/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/curator.rs, pallets/permission0/tests/enforcement.rs, pallets/permission0/tests/fixed.rs, pallets/permission0/tests/lifetime.rs, pallets/permission0/tests/namespace.rs, pallets/permission0/tests/stream.rs, pallets/permission0/api/src/lib.rs
Comprehensive refactor: replaces "grantor/grantee" with "delegator/recipient", introduces hierarchical permission delegation, bounded maps for curator/namespace permissions, instance limits, new extrinsics, events, errors, and migration logic. Updates all related tests and benchmarking.
Torus0 Pallet & Staking Redesign
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/agent.rs, pallets/torus0/tests/namespace.rs, pallets/torus0/tests/stake.rs
Removes explicit agent_key from registration; renames unregister to deregister; staking now uses named reserves; adds migration for stake conversion; updates tests and weights. Namespace creation/deletion events are now per-path.
Client Library Introduction
client/Cargo.toml, client/README.md, client/build.rs, client/src/lib.rs, client/src/chain.rs, client/src/client.rs, client/src/events.rs, client/src/error.rs, client/src/rpc.rs, client/src/interfaces.rs, client/src/utils.rs, client/examples/*
Adds a new Rust client library for Torus, with code generation, chain abstraction, event subscription, RPCs, error handling, and multiple usage examples.
Client Codegen Infrastructure
client/codegen/Cargo.toml, client/codegen/src/lib.rs, client/codegen/src/ir.rs, client/codegen/src/codegen/mod.rs, client/codegen/src/codegen/calls.rs, client/codegen/src/codegen/storage.rs, client/codegen/src/parser/mod.rs, client/codegen/src/parser/calls.rs, client/codegen/src/parser/storage.rs
Implements code generation for client wrappers based on runtime metadata, including IR definitions, parsing, and code emission for storage and calls.
Project Selector Tool
project-selector/Cargo.toml, project-selector/src/main.rs
Adds a new tool to generate IDE-compatible project metadata from Cargo workspaces, supporting crate filtering and outputting structured JSON.
Runtime & Config Updates
runtime/src/lib.rs, runtime/src/configs.rs, runtime/src/apis.rs, runtime/src/configs/eth.rs, runtime/src/precompiles/balance_transfer.rs, runtime/src/precompiles/mod.rs
Bumps runtime spec version, updates migrations, adds permission-related constants, adjusts balance reserve identifier, and refines parameter types for permissions.
Emission0 & Governance Pallet Updates
pallets/emission0/src/distribute.rs, pallets/emission0/src/distribute/math.rs, pallets/emission0/src/lib.rs, pallets/emission0/src/migrations.rs, pallets/emission0/tests/distribution.rs, pallets/emission0/tests/weights.rs, pallets/governance/src/application.rs, pallets/governance/src/benchmarking.rs, pallets/governance/src/lib.rs, pallets/governance/src/migrations.rs, pallets/governance/src/proposal.rs, pallets/governance/src/roles.rs, pallets/governance/src/voting.rs, pallets/governance/src/weights.rs, pallets/governance/src/whitelist.rs, pallets/governance/tests/application.rs, pallets/governance/tests/config.rs, pallets/governance/tests/delegation.rs, pallets/governance/tests/proposal.rs, pallets/governance/tests/roles.rs, pallets/governance/tests/voting.rs
Updates to reflect new permission delegation model, renames, event doc corrections, migration removals, and test updates.
Miscellaneous Pallet/Test Adjustments
pallets/faucet/src/faucet.rs, pallets/faucet/src/lib.rs, pallets/faucet/tests/faucet.rs
Minor import reordering, config updates, and test adjustments for new reserve identifier types.
Node and Build System Updates
node/Cargo.toml, node/src/chain_spec.rs, node/src/cli/eth.rs, node/src/command.rs, node/src/rpc.rs, node/src/rpc/eth.rs, node/src/service.rs
Version bump, import reordering, new chain spec loading, parameter passing adjustments, and telemetry handling.
IDE & Build Tooling
.gitignore, .vscode/settings.json, justfile, flake.nix
Updates ignore patterns, disables some Rust analyzer features, adds spellcheck words, adds a justfile recipe for project selection, and includes subxt in the dev shell.
Documentation & Changelogs
CHANGELOG.md, CLAUDE.md, docs/changelog_prompt.md, docs/changes/spec-22.md, docs/changes/spec-23.md, docs/namespace.md, docs/permission0.md
Adds detailed changelogs for spec 22/23, expands permission0 documentation, adds changelog prompt, and updates terminology for clarity.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant TorusClient
    participant SubstrateNode

    User->>TorusClient: Connect to Mainnet/Testnet
    TorusClient->>SubstrateNode: Establish WebSocket connection

    User->>TorusClient: Call extrinsic (e.g., delegate_permission)
    TorusClient->>SubstrateNode: Submit extrinsic (signed/unsigned)
    SubstrateNode-->>TorusClient: Extrinsic status updates
    TorusClient-->>User: Extrinsic hash / finalization status

    User->>TorusClient: Fetch storage data
    TorusClient->>SubstrateNode: Query storage at latest/specific block
    SubstrateNode-->>TorusClient: Return storage value
    TorusClient-->>User: Return decoded value

    User->>TorusClient: Subscribe to events
    TorusClient->>SubstrateNode: Subscribe to finalized blocks/events
    SubstrateNode-->>TorusClient: Stream events
    TorusClient-->>User: Stream decoded events

    User->>TorusClient: Call RPC (e.g., namespace cost)
    TorusClient->>SubstrateNode: Send RPC request
    SubstrateNode-->>TorusClient: Return RPC result
    TorusClient-->>User: Return result
Loading

Estimated code review effort

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

Possibly related PRs

  • #120: Updates .gitignore and .vscode/settings.json with similar IDE/editor configuration and ignore changes as in this PR.
  • #92: Introduces the permission0 pallet and namespace system, directly related to the permission delegation and namespace changes in this PR.

Suggested reviewers

  • functor-flow
  • steinerkelvin
  • devwckd

Poem

In fields of code where carrots grow,
The Torus rabbits hop and show:
Permissions branch, delegations bloom,
Agents register, namespaces groom.
With staking baskets neatly stacked,
And client burrows well-abstracted—
This patch, a warren, well compacted!

🥕🐇✨

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.

@saiintbrisson saiintbrisson merged commit 0acc792 into main Aug 10, 2025
5 of 6 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