Skip to content

feat: create and join agent-wallet rules for a fundable address#1386

Merged
MicBun merged 2 commits into
mainfrom
feat/maa-rule-store
Jun 2, 2026
Merged

feat: create and join agent-wallet rules for a fundable address#1386
MicBun merged 2 commits into
mainfrom
feat/maa-rule-store

Conversation

@MicBun
Copy link
Copy Markdown
Contributor

@MicBun MicBun commented Jun 1, 2026

resolves: https://github.com/truflation/website/issues/4035

Summary by CodeRabbit

  • New Features

    • MAA now uses a rule + instance model: create immutable rules and join them to derive deterministic MAA addresses (rule IDs are stable 32-byte identifiers).
    • New public actions to create rules, join rules, and query rules, instances, allowed actions, and paginated events.
  • Bug Fixes / Validation

    • Stronger input validation, canonicalized/deduplicated allow-lists, and clarified fee handling; tighter rejection of invalid joins or malformed inputs.
  • Tests

    • Updated golden-vector and lifecycle tests covering rule IDs, derived MAA addresses, canonical ordering, and validation cases.

@MicBun MicBun self-assigned this Jun 1, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 1, 2026

Review Change Stack

Warning

Review limit reached

@MicBun, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 32 minutes and 8 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 50a17b7e-ff6e-429b-a18b-9d036d281f48

📥 Commits

Reviewing files that changed from the base of the PR and between 8b311b4 and 8dcfead.

📒 Files selected for processing (5)
  • extensions/tn_utils/maa.go
  • extensions/tn_utils/maa_test.go
  • extensions/tn_utils/precompiles.go
  • internal/migrations/048-maa.sql
  • tests/streams/maa/create_test.go
📝 Walkthrough

Walkthrough

Replaces single-step MAA with a rule-centric flow: new precompiles compute rules_hash and derive a 32-byte rule_id and 20-byte maa_address; migrations add rule, allowed_actions, instances, and events tables; tests rewritten to exercise maa_create_rule then maa_join and updated getters.

Changes

Modular Agent Address (MAA) System

Layer / File(s) Summary
Precompile contract and core algorithms
extensions/tn_utils/maa.go, extensions/tn_utils/precompiles.go
Adds derive_rule_id, updates compute_rules_hash (removes bridge, accepts fee_mode/fee_bps/fee_flat + namespaces/actions/body_hashes), and changes derive_maa_address to accept (unrestricted, restricted, rule_id). Implements canonicalization, LP8 encoding, decimal parsing, validation, and keccak256 preimage outputs (rule_id 32B; maa_address low 20B).
Precompile unit tests
extensions/tn_utils/maa_test.go
Updates golden vectors and adds tests for deriveRuleID; validates rules-hash ordering/dedup semantics, body-hash handling, determinism, and input-length validation for precompiles.
Database schema and event helpers
internal/migrations/048-maa.sql
Reworks schema to maa_rules keyed by rule_id, maa_allowed_actions (by rule_id + namespace/action), maa_instances (maa_address → rule_id + unrestricted_addr), and rule-scoped maa_events; adds maa_record_event helper that decodes tx hash and records block metadata.
Create_rule, join, and read views
internal/migrations/048-maa.sql
Replaces maa_create with maa_create_rule($salt, ...) → rule_id and maa_join($rule_id) → maa_address. maa_create_rule validates fees/arrays, computes rules_hash, derives rule_id, inserts rule + allowed actions, and emits CREATE_RULE; maa_join derives deterministic maa_address and inserts instance; read views adapted to rule_id/instance model.
Integration tests (rule + join flow)
tests/streams/maa/create_test.go
Refactors tests to call maa_create_rule (assert golden rule_id), maa_join (assert golden maa_address), verify getters, allowed-actions ordering, events (CREATE_RULE, JOIN), and validation error cases (duplicate rule, fee bounds, duplicate allow-list, unknown join, self-join, double join).

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant computeRulesHash as compute_rules_hash
  participant deriveRuleID as derive_rule_id
  participant deriveMAA as derive_maa_address
  participant SQL as migrations / actions

  Client->>computeRulesHash: (fee_mode, fee_bps, fee_flat, namespaces[], actions[], body_hashes[])
  computeRulesHash->>computeRulesHash: normalize, dedupe, sort, encode RULES_PREIMAGE
  computeRulesHash-->>Client: rules_hash (32B)
  Client->>deriveRuleID: (restricted, rules_hash)
  deriveRuleID->>deriveRuleID: validate, encode preimage
  deriveRuleID-->>Client: rule_id (32B)
  Client->>deriveMAA: (unrestricted, restricted, rule_id)
  deriveMAA->>deriveMAA: encode preimage, keccak256, truncate 20B
  deriveMAA-->>SQL: insert maa_instances / use maa_address in maa_join
  SQL-->>Client: confirmation, events (CREATE_RULE / JOIN)
Loading

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

  • trufnetwork/node#1387: Related precompile changes to compute_rules_hash/derive_maa_address and preimage updates.
  • trufnetwork/node#1388: Related modifications to tn_utils precompiles and derivation behavior building on the same spec updates.

Suggested reviewers

  • pr-time-tracker

"I hopped through bytes and salted seeds,
I hashed the rules and planted deeds,
Now rule_id's steady and addresses true,
I joined the rule and returned a view,
A rabbit's dance for the dev-review crew! 🐇"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: introducing a two-step flow to create rules and join them to derive fundable MAA addresses, which aligns with the core refactoring across all modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/maa-rule-store

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

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@holdex
Copy link
Copy Markdown

holdex Bot commented Jun 1, 2026

Time Submission Status

Member Status Time Action Last Update
MicBun ✅ Submitted 4h Update time Jun 2, 2026, 9:14 AM

You can submit time with the command. Example:

@holdex pr submit-time 15m

See available commands to help comply with our Guidelines.

@MicBun MicBun requested a review from pr-time-tracker June 1, 2026 15:04
coderabbitai[bot]

This comment was marked as outdated.

@MicBun MicBun closed this Jun 1, 2026
@MicBun MicBun deleted the feat/maa-rule-store branch June 1, 2026 15:11
@MicBun MicBun restored the feat/maa-rule-store branch June 2, 2026 07:29
@MicBun MicBun reopened this Jun 2, 2026
@trufnetwork trufnetwork deleted a comment from coderabbitai Bot Jun 2, 2026
@trufnetwork trufnetwork deleted a comment from coderabbitai Bot Jun 2, 2026
@trufnetwork trufnetwork deleted a comment from coderabbitai Bot Jun 2, 2026
@trufnetwork trufnetwork deleted a comment from coderabbitai Bot Jun 2, 2026
@MicBun MicBun force-pushed the feat/maa-rule-store branch from d2c6f48 to 8b311b4 Compare June 2, 2026 07:30
@MicBun
Copy link
Copy Markdown
Contributor Author

MicBun commented Jun 2, 2026

@holdex pr submit-time 4h

@MicBun MicBun changed the title feat(maa): add agent-wallet rule store and address derivation feat: create and join agent-wallet rules for a fundable address Jun 2, 2026
@trufnetwork trufnetwork deleted a comment from coderabbitai Bot Jun 2, 2026
@MicBun
Copy link
Copy Markdown
Contributor Author

MicBun commented Jun 2, 2026

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 2, 2026

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

@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.

🧹 Nitpick comments (2)
internal/migrations/048-maa.sql (2)

146-151: 💤 Low value

Add explicit validation for fee_flat >= 0.

fee_bps is explicitly validated (line 149-151) but fee_flat relies solely on the table's CHECK constraint. While functionally correct, a constraint-violation error is less informative than a custom message. Add validation for consistency with the other fee parameter.

Suggested validation
     if $fee_bps < 0 OR $fee_bps > 10000 {
         ERROR('fee_bps must be between 0 and 10000 (10000 = 100%)');
     }
+    if $fee_flat < 0 {
+        ERROR('fee_flat must be non-negative');
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/migrations/048-maa.sql` around lines 146 - 151, Add an explicit
validation for fee_flat similar to fee_bps: in the same validation block (near
the checks referencing $fee_mode and $fee_bps) add a guard that checks if
$fee_flat is negative and raise a clear ERROR like "fee_flat must be >= 0";
update the function/migration around the existing checks so the new validation
runs before relying on the table CHECK constraint.

329-329: 💤 Low value

Address parsing assumes 0x prefix without validation.

substring(LOWER($agent), 3, 40) assumes the input has a 0x prefix. Malformed input (missing prefix, wrong length, non-hex characters) would silently produce incorrect bytes or empty results rather than a clear error.

Consider validating the input format or documenting the expected format clearly in the action signature. Alternatively, handle both prefixed and non-prefixed formats.

Also applies to: 350-350

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/migrations/048-maa.sql` at line 329, The current assignment to
$agent_bytes using decode(substring(LOWER($agent), 3, 40), 'hex') assumes a "0x"
prefix and valid hex of exact length; update the procedure to explicitly
validate and normalize $agent before decoding: accept both "0x"-prefixed and
non-prefixed values by stripping a leading "0x" if present, assert the remaining
string length matches the expected hex length, and assert it matches a hex
regexp (e.g. only 0-9a-f); if validation fails, RAISE EXCEPTION with a clear
message; then use decode(normalized_agent_hex, 'hex') to set $agent_bytes. Apply
the same validation/normalization for the other occurrence that currently uses
substring/LOWER($agent).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/migrations/048-maa.sql`:
- Around line 146-151: Add an explicit validation for fee_flat similar to
fee_bps: in the same validation block (near the checks referencing $fee_mode and
$fee_bps) add a guard that checks if $fee_flat is negative and raise a clear
ERROR like "fee_flat must be >= 0"; update the function/migration around the
existing checks so the new validation runs before relying on the table CHECK
constraint.
- Line 329: The current assignment to $agent_bytes using
decode(substring(LOWER($agent), 3, 40), 'hex') assumes a "0x" prefix and valid
hex of exact length; update the procedure to explicitly validate and normalize
$agent before decoding: accept both "0x"-prefixed and non-prefixed values by
stripping a leading "0x" if present, assert the remaining string length matches
the expected hex length, and assert it matches a hex regexp (e.g. only 0-9a-f);
if validation fails, RAISE EXCEPTION with a clear message; then use
decode(normalized_agent_hex, 'hex') to set $agent_bytes. Apply the same
validation/normalization for the other occurrence that currently uses
substring/LOWER($agent).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6ec2e5e1-76c3-49bc-9f11-3cbeda53a549

📥 Commits

Reviewing files that changed from the base of the PR and between e44b87c and 8b311b4.

📒 Files selected for processing (5)
  • extensions/tn_utils/maa.go
  • extensions/tn_utils/maa_test.go
  • extensions/tn_utils/precompiles.go
  • internal/migrations/048-maa.sql
  • tests/streams/maa/create_test.go

@MicBun MicBun force-pushed the feat/maa-rule-store branch from 8b311b4 to 8dcfead Compare June 2, 2026 09:14
@MicBun MicBun merged commit ba19890 into main Jun 2, 2026
6 of 7 checks passed
@MicBun MicBun deleted the feat/maa-rule-store branch June 2, 2026 09:15
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.

1 participant