Reach out for an audit or to learn more about Macro
or Message on Telegram

Towns A-8

Security Audit

December 3, 2024

Version 1.0.0

Presented by 0xMacro

Table of Contents

Introduction

This document includes the results of the security audit for Towns's smart contract code as found in the section titled ‘Source Code’. The security audit was performed by the Macro security team from October 24 to 31, 2024.

The purpose of this audit is to review the source code of certain Towns Solidity contracts, and provide feedback on the design, architecture, and quality of the source code with an emphasis on validating the correctness and security of the software in its entirety.

Disclaimer: While Macro’s review is comprehensive and has surfaced some changes that should be made to the source code, this audit should not solely be relied upon for security, as no single audit is guaranteed to catch all possible bugs.

Overall Assessment

The following is an aggregation of issues found by the Macro Audit team:

Severity Count Acknowledged Won't Do Addressed
Medium 2 - - 2
Low 1 - - 1
Code Quality 6 1 2 3

Towns was quick to respond to these issues.

Specification

Our understanding of the specification was based on the following sources:

Source Code

The following source code was reviewed during the audit:

Specifically, we audited the following contracts within this repository.

Token Changes (a3fb570e4bdf9e3c889ea2fc5da2d883a4f6dc4e):

Source Code SHA256
./src/tokens/lock/ILock.sol

f59e24b075faedf4122bdbf8e5e0270d2492304a922c9cea1961fa4732bd4c7d

./src/tokens/lock/LockBase.sol

1ac232c03126c99ded3247867ccbb187485af4d57a90baa2ccc37446606d9c88

./src/tokens/lock/LockFacet.sol

d9934664f3b9acd4000d46b3632a0152c806ecb1a23bde3a6db3a647e5c89251

./src/tokens/lock/LockStorage.sol

322317689ef981bd8c19bb083f2f419c30f91ed575d321e18bafb244097e9f9a

./src/tokens/river/base/IOptimismMintableERC20.sol

c222a02756b1a49061984690e0d30c2948a874ecc0cdc59b422887ba9218616d

./src/tokens/river/base/ISemver.sol

430e4b262f9c1b7cc688febc727ce882c051bf54ac37ab570ed397d5739501b2

./src/tokens/river/base/River.sol

fb55232c38d34e1555d4f984d3788818439c2baab6b2a2b1bc4d6757537e0b4f

./src/tokens/river/base/delegation/IMainnetDelegation.sol

4f80543002fdfa74f7dec3aa65ee045451b19f36e878141e83b28d84751d50ef

./src/tokens/river/base/delegation/MainnetDelegation.sol

ae08207f8e9e6d061c70becb828d2d2b41c8834f6cb8beb4c56e49de8264e786

./src/tokens/river/base/delegation/MainnetDelegationBase.sol

eb7bcd2a684b9609d043877fd0c20f341e91a47efd2afb22a4d4dd9a122be0bd

./src/tokens/river/base/delegation/MainnetDelegationStorage.sol

a8a17529bec7f6d43a1dbdd18c316d3e46aedb5455f7d156d021cd8e5f4dc0cd

Merkle Drop (883b14f8279ebab454076e3c94bf8b8c3abfb4e5):

Source Code SHA256
./src/tokens/drop/DropFacet.sol

6a64173cdd60f5b0811bb5f441c1796f8e2526a3150d7b4a54d677ce3014890a

./src/tokens/drop/DropFacetBase.sol

45c6dff5dd8a77d798243ae9d1cf2f3834a5f7294950115c586550a122204fef

./src/tokens/drop/DropStorage.sol

493ee2cb2a5eb231d90473b6ab05df86af2a9c4dc20552b34eaaef17744d8baf

./src/tokens/drop/IDropFacet.sol

4fea15e3c6806774e0e026e42a848e3d50bee7d2ae26e7a78932ca07123e93a5

Rewards Distribution V2 (b3626867eba5c43049f88132aa040732d3ee53c5):

Source Code SHA256
./src/base/registry/facets/distribution/v2/DelegationProxy.sol

8fe84be4e34aa3ce71135cfa9dba5393e48a81099a01c793f52280e63895bc22

./src/base/registry/facets/distribution/v2/IRewardsDistribution.sol

14e1744971f1c459927e50c324e3e319afa3d17660defd3b3078c80db525fc91

./src/base/registry/facets/distribution/v2/RewardsDistribution.sol

b74f478491d88e832a6f318e1a225338e0903ef6e9d188239f6938f13aabe41c

./src/base/registry/facets/distribution/v2/RewardsDistributionBase.sol

daee6fdf98830b92b6a4c90e9210d312c9dbdbe44d5951764ccf5d5d8bd725ee

./src/base/registry/facets/distribution/v2/RewardsDistributionStorage.sol

d7cd783dcb1425a3c78e73112cd4a81dfe527b430668a8ab520128e38cf5f091

./src/base/registry/facets/distribution/v2/StakingRewards.sol

be9a36a9df289f5ff564087abc9f9fe60bf3856d3577f6ba29a4a418a0881b81

Note: This document contains an audit solely of the Solidity contracts listed above. Specifically, the audit pertains only to the contracts themselves, and does not pertain to any other programs or scripts, including deployment scripts.

Issue Descriptions and Recommendations

Click on an issue to jump to it, or scroll down to see them all.

Security Level Reference

We quantify issues in three parts:

  1. The high/medium/low/spec-breaking impact of the issue:
    • How bad things can get (for a vulnerability)
    • The significance of an improvement (for a code quality issue)
    • The amount of gas saved (for a gas optimization)
  2. The high/medium/low likelihood of the issue:
    • How likely is the issue to occur (for a vulnerability)
  3. The overall critical/high/medium/low severity of the issue.

This third part – the severity level – is a summary of how much consideration the client should give to fixing the issue. We assign severity according to the table of guidelines below:

Severity Description
(C-x)
Critical

We recommend the client must fix the issue, no matter what, because not fixing would mean significant funds/assets WILL be lost.

(H-x)
High

We recommend the client must address the issue, no matter what, because not fixing would be very bad, or some funds/assets will be lost, or the code’s behavior is against the provided spec.

(M-x)
Medium

We recommend the client to seriously consider fixing the issue, as the implications of not fixing the issue are severe enough to impact the project significantly, albiet not in an existential manner.

(L-x)
Low

The risk is small, unlikely, or may not relevant to the project in a meaningful way.

Whether or not the project wants to develop a fix is up to the goals and needs of the project.

(Q-x)
Code Quality

The issue identified does not pose any obvious risk, but fixing could improve overall code quality, on-chain composability, developer ergonomics, or even certain aspects of protocol design.

(I-x)
Informational

Warnings and things to keep in mind when operating the protocol. No immediate action required.

(G-x)
Gas Optimizations

The presented optimization suggestion would save an amount of gas significant enough, in our opinion, to be worth the development cost of implementing it.

Issue Details

M-1

Incomplete eligibility reset for conditions

Topic
Data Consistency
Status
Impact
Medium
Likelihood
Medium

The DropFacet contract allows the owner to set an array of conditions by calling setClaimConditions(). By setting the resetElegibility boolean, the previously suppliedClaimedByWallet will not prevent an account from claiming the set conditions, as a new, unused ID will be used.

However, combining mixed eligibility configurations can cause the contract to improperly clear the previous condition IDs, leading to unintended preservation of claim history and inconsistent behavior when resetting eligibility. Consider the following potential order of configurations being set and their final state:

  1. Initial configuration with three conditions is set:
conditionById[0] = Condition A
conditionById[1] = Condition B
conditionById[2] = Condition C
conditionCount = 3
conditionStartId = 0
  1. A second configuration with two conditions is set with resetElegibility false:
conditionById[0] = New Condition X
conditionById[1] = New Condition Y
conditionById[2] = (deleted)
conditionCount = 2
conditionStartId = 0
  1. A third configuration is set with three new conditions with resetElegibility true:
conditionById[0] = (deleted)
conditionById[1] = (deleted)
conditionById[2] = New Condition 1 (With previous condition C claim history)
conditionById[3] = New Condition 2
conditionById[4] = New Condition 3
conditionCount = 3
conditionStartId = 2

This renders a scenario where the conditionById[2] is re-used even if resetElegibility was true for the latest configuration, disallowing users to claim this condition.

Remediations to Consider:

Consider keeping track of the highest condition ID used and starting from this index when resetting eligibility.

M-2

Inconsistent reward accrual

Topic
Protocol Design
Status
Impact
Medium
Likelihood
Low

The RewardsDistribution contract accrues rewards to users who stake and delegate their voting power to spaces or valid operators. If users delegate to a space, the delegation points to the space’s delegation. However, if a space stops delegating or an operator becomes inactive, users who initially staked and delegated to these will continue accruing rewards. This occurs because the earning power is updated at the stake or delegation execution, through functions stake(), permitAndStake(), increaseStake(), changeBeneficiary(), and redelegate(). Ultimately, calling into the StakingRewards library’s internal functions that update the earning power.

Additionally, the _sweepSpaceRewardsIfNecessary() function transfers accrued rewards from spaces treasure to their delegated operators. However, when a space redelegates to a new operator, the sweep function uses the current operator mapping. This means all accumulated rewards (including those earned by the previous operator) will be sent to the new operator, resulting in incorrect reward attribution.

This issue could lead to unintended reward distribution and potential economic imbalances within the protocol. It may also indirectly incentivize users to maintain outdated delegations.

Remediations to Consider:

  1. Implementing a sweep internal mechanism for spaces when redelegating to update the previous operator rewards.
  2. Incentivize users to maintain updated their delegations.
L-1

Users claiming penalty is not predictable

Topic
Slippage
Status
Impact
Medium
Likelihood
Low

In the DropFacet contract, users can execute a claimWithPenalty() call to receive their allocated tokens according to the parameters of their leaf in the claim data and the configured conditions. After the logic verifies the claim arguments, the function deducts the penaltyBps configured for that specific condition ID:

function claimWithPenalty(
    Claim calldata claim
  ) external returns (uint256 amount) {
    DropStorage.Layout storage ds = DropStorage.layout();

    _verifyClaim(ds, claim);

    ClaimCondition storage condition = ds.getClaimConditionById(
      claim.conditionId
    );

    **amount = claim.quantity;
    uint256 penaltyBps = condition.penaltyBps;
    if (penaltyBps > 0) {
      unchecked {
        uint256 penaltyAmount = BasisPoints.calculate(
          claim.quantity,
          penaltyBps
        );
        amount = claim.quantity - penaltyAmount;
      }
    }**

    ...
  }

Reference: DropFacet.sol#L34-74

However, users can not ensure the current penaltyBps will be used as there is no expected output or slippage to ensure this. Although highly unlikely, users might end up with a different quantity of tokens than initially expected if the condition they’re attempting to claim modifies this penalty fee before their transactions are included in a validated block.

Remediations to Consider:

Consider adding an expected penaltyBps to the input arguments and comparing the used value to match the user value.

Q-1

Lack of public view function to retrieve all claimable conditions

Topic
Data Retrieval
Status
Quality Impact
Low

The DropFacet contract lacks an external view function to fetch all existing configured conditions. Consider adding a new view function to complement the existing getActiveCondition(), enabling retrieval of all present conditions.

Q-2

Lack of granular claim condition management

Topic
Admin Configuration
Status
Quality Impact
Medium

The DropFacet contract’s current implementation only allows setting or resetting all claim conditions at once through the setClaimConditions() function. While this approach works, it may be less efficient and more prone to errors when only a single condition needs to be updated or a new one added. A more granular approach to managing claim conditions could improve the contract's flexibility and reduce potential mistakes when modifying conditions.

Consider implementing additional explicit functions that allow for more targeted modifications of claim conditions, such as:

  • A function to update a single existing condition by its ID.
  • A function to add a new condition without affecting existing ones.
  • A function to remove a specific condition by its ID
Q-3

Permit deadline is not checked internally

Topic
Sanity Checks
Status
Wont Do
Quality Impact
Low

In RewardsDistribution, the current implementation of stakeOnBehalf() wraps the permit call to the token with a try-catch statement and empty error handling to prevent any denial of service issues by a potential third-party actor using the passed signature. It continues the function call if the allowance is present. However, there is no internal verification on the deadline that can filter non-valid permit signatures to prevent this call. Consider checking the deadline internally to prevent expired signatures from being used.

Response by Towns

This concerns the permitAndStake function which follows UniStaker. The intention is to delegate signature verification to the EIP-2612 compatible ERC-20 token and attempt to stake even if the permit call fails.

Q-4

increaseStake operations lack zero amount check

Topic
Validation
Status
Wont Do
Quality Impact
Low

In RewardsDistribution, increaseStake() doesn't validate the input amount. A user could call this with zero amount, causing unnecessary state updates, like reward calculations, and emitting an event without any actual stake increase.

Response by Towns

This is intentional for poking state updates.

Q-5

Lack of direct reward compounding functionality

Topic
Use Cases
Status
Acknowledged
Quality Impact
Medium

Currently, if users desire to compound their rewards, they’d need to execute a reward claim and then increase stake or stake separately. To reduce friction in this potential user case, consider having a claimAndStake() function that allows users to claim and stake atomically.

Q-6

initiateWithdrawal lacks distinct event for mainnet delegation withdrawals

Topic
Events
Status
Quality Impact
Low

In RewardsDistribution, staking delegations use a two-step process for deposit withdrawals. In contrast, mainnet delegations use a single step to remove the delegated amount directly. However, the current event structure does not provide any arguments to differentiate between local delegation withdrawals and mainnet delegation withdrawals. To enhance transparency and improve data tracking, consider adding a separate event for mainnet delegation withdrawals or including an identifier parameter in the existing event.

Disclaimer

Macro makes no warranties, either express, implied, statutory, or otherwise, with respect to the services or deliverables provided in this report, and Macro specifically disclaims all implied warranties of merchantability, fitness for a particular purpose, noninfringement and those arising from a course of dealing, usage or trade with respect thereto, and all such warranties are hereby excluded to the fullest extent permitted by law.

Macro will not be liable for any lost profits, business, contracts, revenue, goodwill, production, anticipated savings, loss of data, or costs of procurement of substitute goods or services or for any claim or demand by any other party. In no event will Macro be liable for consequential, incidental, special, indirect, or exemplary damages arising out of this agreement or any work statement, however caused and (to the fullest extent permitted by law) under any theory of liability (including negligence), even if Macro has been advised of the possibility of such damages.

The scope of this report and review is limited to a review of only the code presented by the Towns team and only the source code Macro notes as being within the scope of Macro’s review within this report. This report does not include an audit of the deployment scripts used to deploy the Solidity contracts in the repository corresponding to this audit. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. In this report you may through hypertext or other computer links, gain access to websites operated by persons other than Macro. Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such websites’ owners. You agree that Macro is not responsible for the content or operation of such websites, and that Macro shall have no liability to your or any other person or entity for the use of third party websites. Macro assumes no responsibility for the use of third party software and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software.