Skip to content

refactor: EVM authorization contract ordered standard Authorization execution #355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

keyleu
Copy link
Contributor

@keyleu keyleu commented May 21, 2025

These changes slightly refactor how Standard authorizations are created and executed in the EVM authorizations contract. ZK flow remains untouched.

Authorizations are now created with a label (similar to CW flow), a set of users that can execute that authorization label, and an array of AuthorizationData (contract address + execution type + function_selector/call) that can be executed.

When executing a label, we will verify that the subroutine passed calls the same contracts in the same way in the same order. This adds order to our authorizations. Before this change we could execute any contract in any order, now we will respect the order of execution because we are saving this in an array of AuthorizationData.

Additionally, allows creating authorizations that only verify the function selector (name of the function) instead of the entire function call. This is useful if we want to allow someone to execute the function of the library with any parameters

In general kinda it's cleaner although it increases the storage cost a little but, although not much.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Authorization is now managed using labels, enabling batch handling of authorized addresses and ordered contract call sequences.
    • Message sending requires specifying a label to validate authorization for grouped contract calls.
  • Refactor

    • Authorization logic transitioned from per-user and per-call mappings to a label-based scheme for streamlined management.
    • Event notifications for authorization changes now emit only the label identifier.
  • Tests

    • Expanded test coverage for label-based authorization, including validation by call hash and function selector.
    • Added tests for permissionless access, mixed validation modes, and various execution success and failure scenarios.

Copy link
Contributor

coderabbitai bot commented May 21, 2025

"""

Walkthrough

The Authorization contract was refactored from a user-contract-call mapping system to a label-based authorization scheme. Authorizations are now grouped under labels, each mapping to authorized addresses and ordered authorization data. Events, function signatures, and internal logic were updated to support this new structure, with corresponding updates to the test suite.

Changes

File(s) Change Summary
solidity/src/authorization/Authorization.sol Refactored authorization logic from triple nested mapping to label-based system; replaced per-user mappings with label-keyed authorized addresses and authorization data arrays; changed events to emit label strings; updated function signatures for batch operations using labels; revised internal authorization checks and message sending to use label-based verification.
solidity/test/authorization/AuthorizationStandard.t.sol Updated test contract to reflect label-based authorization; replaced flat arrays with nested arrays and labels; modified calls to authorization functions and assertions to use new label and authorization data structures; added tests for function selector and call hash authorization modes; expanded tests for execution success and failure scenarios; adjusted test calls to new function signatures.

Sequence Diagram(s)

sequenceDiagram
    participant Owner
    participant AuthorizationContract
    participant User

    Owner->>AuthorizationContract: addStandardAuthorizations(labels, users, authorizationData)
    AuthorizationContract-->>Owner: emit AuthorizationAdded(label)

    User->>AuthorizationContract: sendProcessorMessage(label, message)
    AuthorizationContract->>AuthorizationContract: _checkAddressIsAuthorized(sender, label, authorizationData)
    AuthorizationContract-->>User: Process message if authorized
Loading

Possibly related PRs

  • feat: EVM Authorizations contract #343: Refactors the Authorization contract’s internal data structure and logic from per-user mapping to label-based system, modifying core authorization logic and function signatures introduced in the initial Authorization contract PR.

Suggested reviewers

  • bekauz

Poem

🐇
Labels now rule the authorization land,
No more tangled mappings, just strings in hand.
Batch your permissions, keep order in view,
Authorization’s simpler, and testing is too!
With hops and with hashes, the contract’s renewed—
A rabbit’s delight, for code that’s improved!
🥕
"""


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 48e2e3d and 46735b6.

📒 Files selected for processing (1)
  • solidity/src/authorization/Authorization.sol (11 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: solidity contracts
  • GitHub Check: setup-local-ic
  • GitHub Check: build-and-deploy
🔇 Additional comments (10)
solidity/src/authorization/Authorization.sol (10)

19-19: Documentation updated to reflect ordered execution.

The comment correctly reflects the new ordered execution requirement introduced by this refactor.


67-78: Event simplification aligns with new label-based model.

The events now emit only the label string instead of detailed user and call information, which is consistent with the new authorization model where all details are grouped under a label.


115-143: Well-structured data model for label-based authorizations.

The new data structures properly support the refactored authorization model:

  • authorizations mapping from labels to authorized addresses
  • AuthorizationData struct with flexible verification options (function selector vs call hash)
  • authorizationsData mapping for ordered authorization data per label

The design enables both permissionless access (address(0)) and flexible verification modes.


265-296: Robust batch authorization addition with proper validation.

The function correctly handles batch operations and includes all necessary validations as confirmed by past review feedback:

  • Array length validation
  • Non-empty users array validation
  • Non-empty authorization data validation with descriptive error messages
  • Proper storage updates and event emissions

The overwriting behavior is intentionally allowed as clarified in past reviews.


303-312: Clean batch removal implementation.

The removal function properly cleans up both mappings and emits appropriate events for each label.


320-341: Enhanced message sending with label-based authorization.

The function signature correctly adds the label parameter to support the new authorization model. The routing logic for different message types is preserved and authorization is properly delegated to type-specific handlers.


349-367: InsertMsgs handling maintains admin-only access.

The function correctly requires admin access for InsertMsgs operations and properly sets the execution ID.


376-400: SendMsgs handling with proper authorization delegation.

The function correctly delegates authorization verification to subroutine-specific functions while maintaining consistent message modifications (priority and execution ID).


493-543: Comprehensive authorization verification logic.

The authorization checking function correctly implements the ordered verification:

  1. ✅ Verifies sender is in authorized addresses (including permissionless via address(0))
  2. ✅ Checks authorization data array length matching
  3. ✅ Verifies contract addresses match in order
  4. ✅ Conditionally checks function selector vs call hash based on useFunctionSelector flag

The logic properly enforces the ordered execution requirement and flexible verification modes.


408-436:

❌ Incorrect review comment

Verify authorization data construction for atomic subroutines.

The function constructs AuthorizationData arrays correctly, but there's a potential issue with the authorization verification approach:

The function always sets useFunctionSelector: true in the constructed authorization data, but the stored authorization data may have different useFunctionSelector values. This could cause mismatches during verification.


🏁 Script executed:

#!/bin/bash
# Description: Check if there are any tests that verify mixed useFunctionSelector scenarios
# Expected: Tests should cover cases where stored authorization data has different useFunctionSelector values

rg -A 10 -B 5 "useFunctionSelector.*false" solidity/test/

Length of output: 4485


🏁 Script executed:

#!/bin/bash
# Search for the definition of AtomicSubroutine in the codebase
rg -R "struct AtomicSubroutine" -A3 -B3 solidity/src

Length of output: 459


🏁 Script executed:

#!/bin/bash
# Search tests for any handling of atomic subroutines
rg -n "AtomicSubroutine" -C3 solidity/test
rg -n "subroutine" -C3 solidity/test

Length of output: 35436


🏁 Script executed:

#!/bin/bash
# Inspect AuthorizationData struct and _checkAddressIsAuthorized implementation
rg -n "struct AuthorizationData" -C5 solidity/src/authorization/Authorization.sol
rg -n "function _checkAddressIsAuthorized" -C20 solidity/src/authorization/Authorization.sol

Length of output: 2474


🏁 Script executed:

#!/bin/bash
# Print the full implementation of _checkAddressIsAuthorized
sed -n '493,650p' solidity/src/authorization/Authorization.sol

Length of output: 7162


Misunderstood useFunctionSelector in verification logic

The useFunctionSelector flag on the passed AuthorizationData is never consulted when deciding which field to compare. The code always branches on the stored labelAuthorizationData[i].useFunctionSelector, then compares either:

  • labelAuthorizationData[i].functionSelector vs. authorizationData[i].functionSelector, or
  • labelAuthorizationData[i].callHash vs. authorizationData[i].callHash

Since _verifyAtomicSubroutineAuthorization correctly populates both functionSelector and callHash, and the branch uses only the stored flag, mixed-validation tests (with some entries having useFunctionSelector: false) pass as expected.

No changes required. Please disregard the original concern.

Likely an incorrect or invalid review comment.


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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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

@keyleu keyleu requested a review from bekauz May 21, 2025 16:27
@keyleu keyleu changed the title refactor: modify EVM authorization contract for standard Authorizations refactor: modify EVM authorization contract for standard Authorizations order execution May 21, 2025
@keyleu keyleu changed the title refactor: modify EVM authorization contract for standard Authorizations order execution refactor: modify EVM authorization contract for standard Authorizations execution order May 21, 2025
Copy link
Contributor

@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: 1

🧹 Nitpick comments (5)
solidity/src/authorization/Authorization.sol (3)

115-122: Use a cheaper, collision-resistant key type for authorizations / authorizationsData

string keys are hashed (keccak256) for every storage access and incur noticeably higher gas costs than fixed-size value types.
If the label never needs to be re-encoded on-chain (e.g. it is only human-readable off-chain), consider storing the keccak256(bytes(label)) as bytes32, or even an uint256, and keep the human name only in events. This lowers:

  • SSTORE/SLOAD cost per access
  • Memory-to-calldata copy cost when the label is passed as string calldata
- mapping(string => address[]) public authorizations;
- mapping(string => AuthorizationData[]) public authorizationsData;
+ mapping(bytes32 => address[]) public authorizations;
+ mapping(bytes32 => AuthorizationData[]) public authorizationsData;

bytes32 labelKey = keccak256(bytes(label)); can be computed once in each public/​internal function.
This is an optional change but pays for itself quickly if the contract is called frequently.


397-424: Duplicate code between _verifyAtomicSubroutineAuthorization and _verifyNonAtomicSubroutineAuthorization

Both functions build an AuthorizationData[] and then call _checkAddressIsAuthorized. The only difference is the subroutine type they decode.

Refactor to a single private helper to reduce byte-code size and maintenance burden:

-function _verifyAtomicSubroutineAuthorization(string calldata label, IProcessorMessageTypes.SendMsgs memory sendMsgs) private view { ... }
-
-function _verifyNonAtomicSubroutineAuthorization(string calldata label, IProcessorMessageTypes.SendMsgs memory sendMsgs) private view { ... }
+function _verifySubroutineAuthorization(
+    string calldata label,
+    IProcessorMessageTypes.FunctionTarget[] memory functions,
+    bytes[] memory messages
+) private view { ... }

Call this helper from both branches with the proper arrays.


481-520: Linear scans become expensive for large access lists

_checkAddressIsAuthorized performs two O(n) loops:

  1. Scan authorizedAddresses
  2. Scan labelAuthorizationData

Gas grows linearly with each authorised address or function.

If labels are expected to hold many users or large call sequences, consider:

  • Mapping address => bool for quick membership checks
  • Storing a single bytes32 hash = keccak256(abi.encodePacked(authorizationData)) and comparing hashes instead of element-by-element loops.

This change would bring membership checks to O(1) and shrink calldata copying.

solidity/test/authorization/AuthorizationStandard.t.sol (2)

29-33: Prefer constructing test fixtures in setUp() to avoid contract-level storage

users, labels, and authorizationData are declared as state variables, which means each test deployment incurs an unnecessary SSTORE gas cost and byte-code growth. Initialising them inside setUp() (as memory variables) keeps the test contract lighter and avoids unintended cross-test coupling.

This is a minor optimisation but makes the test suite cleaner.


71-78: Helper to build AuthorizationData would reduce duplication

The same four-line block that fills users, labels, and authorizationData appears in several tests. Extracting it into a private helper (e.g., _initUpdateConfigAuth()) improves readability and reduces copy-paste errors.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 2ae1e36 and 6634650.

📒 Files selected for processing (2)
  • solidity/src/authorization/Authorization.sol (11 hunks)
  • solidity/test/authorization/AuthorizationStandard.t.sol (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: build-and-deploy
🔇 Additional comments (1)
solidity/src/authorization/Authorization.sol (1)

365-389: Priority is force-overwritten – verify that this is intended

sendMsgs.priority is unconditionally set to Priority.Medium, discarding any priority chosen by the caller.
If callers should be able to request a lower/higher priority (e.g. Low, High), the contract should validate instead of overwrite, or at least expose a constant policy.
Please confirm that hard-coding Medium is a deliberate product decision.

@keyleu keyleu changed the title refactor: modify EVM authorization contract for standard Authorizations execution order refactor: EVM authorization contract ordered standard Authorization execution May 21, 2025
Copy link
Contributor

@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

♻️ Duplicate comments (1)
solidity/src/authorization/Authorization.sol (1)

261-289: 🛠️ Refactor suggestion

Avoid overwriting existing labels without warning

While the implementation now checks for empty arrays (addressing a previous comment), it still silently overwrites existing authorization labels without warning. This could lead to unexpected behavior if a label is accidentally reused.

function addStandardAuthorizations(
    string[] memory _labels,
    address[][] memory _users,
    AuthorizationData[][] memory _authorizationData
) external onlyOwner {
    require(
        _labels.length == _authorizationData.length && _labels.length == _users.length, "Array lengths must match"
    );

    for (uint256 i = 0; i < _labels.length; i++) {
        string memory label = _labels[i];
        address[] memory users = _users[i];
        require(users.length > 0, "Users array cannot be empty");
        AuthorizationData[] memory authorizationData = _authorizationData[i];
        require(authorizationData.length > 0, "Authorization data array cannot be empty");

+       // Log existing authorization overwrite
+       if (authorizations[label].length > 0) {
+           emit AuthorizationRemoved(label);
+       }

        authorizations[label] = users;
        authorizationsData[label] = authorizationData;

        emit AuthorizationAdded(label);
    }
}

If you want to make the overwrite behavior more explicit, consider adding an optional boolean parameter to control whether overwriting is allowed.

🧹 Nitpick comments (6)
solidity/src/authorization/Authorization.sol (6)

115-139: Consider using bytes32 keys for better storage efficiency

The refactoring to a label-based system is a good improvement for clarity, but using string keys for mappings in Solidity is less gas-efficient than using bytes32 keys. This is especially important for storage mappings that will be accessed frequently.

- mapping(string => address[]) public authorizations;
+ mapping(bytes32 => address[]) public authorizations;

- mapping(string => AuthorizationData[]) public authorizationsData;
+ mapping(bytes32 => AuthorizationData[]) public authorizationsData;

If the string labels need to be maintained for easier usage in interfaces, consider using keccak256(bytes(label)) to convert the string to bytes32 before accessing the mapping.


283-286: Consider optimizing storage operations for gas efficiency

Direct assignment of arrays from memory to storage can be gas-intensive. For large arrays, consider using a more gas-efficient approach.

- authorizations[label] = users;
- authorizationsData[label] = authorizationData;
+ // Clear existing arrays first if any
+ delete authorizations[label];
+ delete authorizationsData[label];
+
+ // Use a more efficient storage pattern for the arrays
+ for (uint256 j = 0; j < users.length; j++) {
+     authorizations[label].push(users[j]);
+ }
+ 
+ for (uint256 j = 0; j < authorizationData.length; j++) {
+     authorizationsData[label].push(authorizationData[j]);
+ }

This approach ensures that if an array already exists, it's properly cleared before new elements are added. It's more explicit and can be more gas-efficient for large arrays.


463-464: Use more specific error messages for authorization failures

The current error message "Unauthorized access" is used in multiple places with different context, which makes debugging more difficult.

- revert("Unauthorized access");
+ revert("User not authorized for this label");

For line 427:

- revert("Unauthorized access");
+ revert("User not authorized for atomic subroutine");

For line 463:

- revert("Unauthorized access");
+ revert("User not authorized for non-atomic subroutine");

Also applies to: 427-428


478-525: Improve error information for authorization checks

The _checkAddressIsAuthorized function returns a simple boolean, which doesn't provide specific information about why authorization failed. Consider providing a more informative response.

Consider refactoring this function to return a more specific error code or message by using custom errors:

enum AuthorizationErrorCode {
    Success,
    UserNotAuthorized,
    WrongNumberOfCalls,
    InvalidContractSequence,
    InvalidCallSequence
}

function _checkAddressIsAuthorized(
    address _address,
    string calldata label,
    AuthorizationData[] memory _authorizationData
) internal view returns (bool authorized, AuthorizationErrorCode errorCode) {
    // Check if the address is in the list of authorized addresses for this label
    address[] memory authorizedAddresses = authorizations[label];

    bool isAuthorized = false;
    for (uint256 i = 0; i < authorizedAddresses.length; i++) {
        if (authorizedAddresses[i] == _address || authorizedAddresses[i] == address(0)) {
            isAuthorized = true;
            break;
        }
    }

    if (!isAuthorized) {
        return (false, AuthorizationErrorCode.UserNotAuthorized);
    }

    // Check if the authorization data matches the order
    AuthorizationData[] memory labelAuthorizationData = authorizationsData[label];

    // Check that the lengths are the same
    if (labelAuthorizationData.length != _authorizationData.length) {
        return (false, AuthorizationErrorCode.WrongNumberOfCalls);
    }

    // Check that each element is the same
    for (uint256 i = 0; i < labelAuthorizationData.length; i++) {
        if (labelAuthorizationData[i].contractAddress != _authorizationData[i].contractAddress) {
            return (false, AuthorizationErrorCode.InvalidContractSequence);
        }
        if (labelAuthorizationData[i].callHash != _authorizationData[i].callHash) {
            return (false, AuthorizationErrorCode.InvalidCallSequence);
        }
    }

    return (true, AuthorizationErrorCode.Success);
}

Then, update the calling functions to use the error code for more specific error messages.


314-335: Add event emission for denied authorizations

Currently, there's no visibility when an authorization is denied. Consider adding an event for failed authorization attempts to aid in monitoring and debugging.

First, add a new event:

/**
 * @notice Event emitted when an authorization is denied
 * @dev This event is emitted when an unauthorized access attempt is made
 * @param sender The address that attempted the unauthorized access
 * @param label The label of the authorization that was attempted
 */
event AuthorizationDenied(address indexed sender, string label);

Then in the verification functions, emit this event before reverting:

if (!_checkAddressIsAuthorized(msg.sender, label, authorizationData)) {
+   emit AuthorizationDenied(msg.sender, label);
    revert("Unauthorized access");
}

This provides better observability into access control issues.


509-522: Consider using a hash comparison for authorization data

Instead of comparing each element of the authorization data arrays individually, consider hashing the entire array to perform a single comparison. This can be more gas-efficient for large arrays.

For validating ordered execution, computing and comparing a single hash of the authorization data could be more efficient:

- // Check that the lengths are the same
- if (labelAuthorizationData.length != _authorizationData.length) {
-     return false;
- }
- 
- // Check that each element is the same
- for (uint256 i = 0; i < labelAuthorizationData.length; i++) {
-     if (
-         labelAuthorizationData[i].contractAddress != _authorizationData[i].contractAddress
-             || labelAuthorizationData[i].callHash != _authorizationData[i].callHash
-     ) {
-         return false;
-     }
- }

+ // Compute hash of stored authorization data on first use and cache it
+ bytes32 storedHash = keccak256(abi.encode(labelAuthorizationData));
+ 
+ // Compare with hash of provided authorization data
+ if (storedHash != keccak256(abi.encode(_authorizationData))) {
+     return false;
+ }

You could also consider caching the hash of authorization data when it's first set to save even more gas on subsequent checks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 6634650 and 8f98aa8.

📒 Files selected for processing (1)
  • solidity/src/authorization/Authorization.sol (11 hunks)
🔇 Additional comments (1)
solidity/src/authorization/Authorization.sol (1)

19-19: Good update to documentation reflecting ordered execution

The update to the documentation correctly reflects the new capability of enforcing order of execution through the stored array of AuthorizationData. This is an important change that improves the clarity and security of the contract.

Copy link
Contributor

@bekauz bekauz left a comment

Choose a reason for hiding this comment

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

on a high level this makes sense to me. not the easiest to review given the byte splitting parts (bytes4 and stuff), but the test seems to be covering that!

Comment on lines 280 to 285
address[] memory users = _users[i];
// Check that users is not empty
require(users.length > 0, "Users array cannot be empty");
AuthorizationData[] memory authorizationData = _authorizationData[i];
// Check that the authorization data is not empty
require(authorizationData.length > 0, "Authorization data array cannot be empty");
Copy link
Contributor

Choose a reason for hiding this comment

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

maybe here it would be nice to return error messages that include the label (or its index) that caused the error?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

added!

Comment on lines 265 to 294
function addStandardAuthorizations(
string[] memory _labels,
address[][] memory _users,
AuthorizationData[][] memory _authorizationData
) external onlyOwner {
// Check that the arrays are the same length
// We are allowing adding multiple authorizations at once for gas optimization
// The arrays must be the same length because for each user we have a contract and a call
require(_users.length == _contracts.length && _contracts.length == _calls.length, "Array lengths must match");
// The arrays must be the same length because for each label we have a list of authorization data
require(
_labels.length == _authorizationData.length && _labels.length == _users.length, "Array lengths must match"
);

for (uint256 i = 0; i < _users.length; i++) {
bytes32 callHash = keccak256(_calls[i]);
authorizations[_users[i]][_contracts[i]][callHash] = true;
emit AuthorizationAdded(_users[i], _contracts[i], callHash);
for (uint256 i = 0; i < _labels.length; i++) {
// Get the label and the authorization data
string memory label = _labels[i];
address[] memory users = _users[i];
// Check that users is not empty
require(users.length > 0, "Users array cannot be empty");
AuthorizationData[] memory authorizationData = _authorizationData[i];
// Check that the authorization data is not empty
require(authorizationData.length > 0, "Authorization data array cannot be empty");

// Add the label to the mapping
authorizations[label] = users;
// Add the authorization data to the mapping
authorizationsData[label] = authorizationData;

emit AuthorizationAdded(label);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we validate the labels being added to prevent overriding existing entries in case they already exist? iirc that's how cw authorizations work, right?

Copy link
Contributor Author

@keyleu keyleu May 28, 2025

Choose a reason for hiding this comment

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

Actually it's not a bug, it's a feature.

Like you say, it's right that In CW we don't allow removing authorizations, just disabling/enabling them. Reason for this is because we tokenize them and we would have conflicts if we remove and try to add again with same label (token already exists).

For solidity we are not tokenizing them (and we don't have an authorization state to enable/disable), so they can just be removed and added again. Therefore, to make it cheaper and not require 2 transactions to "rewrite" an authorization. We allow the owner to "redefine" the authorization.
I was initially checking if the label already existed but then decided that this way is more flexible and cheaper to operate in case an authorization needs to be overwritten

Copy link
Contributor Author

Choose a reason for hiding this comment

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

coderabbit also told me this btw #355 (comment) 😃

view
returns (bytes memory)
{
function _handleSendMsgsMessage(
Copy link
Contributor

Choose a reason for hiding this comment

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

nit but what about just _handleSendMsgs or _handleSendMsgsRequest?

Copy link
Contributor Author

@keyleu keyleu May 28, 2025

Choose a reason for hiding this comment

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

changed! Changed also for _handleInsertMsgs

Comment on lines +499 to +505
bool isAuthorized = false;
for (uint256 i = 0; i < authorizedAddresses.length; i++) {
if (authorizedAddresses[i] == _address || authorizedAddresses[i] == address(0)) {
isAuthorized = true;
break;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

clean

@keyleu keyleu requested a review from bekauz May 28, 2025 18:10
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.

2 participants