PWN
Staking & Governance

PWN holders can lock their tokens for a set time to get voting power and a share of protocol revenue. We reviewed the staking and governance contracts behind that system.
report id
0365
category
Token & RWA
language
Solidity
final report
November 13, 2024
lines of code
1112
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind Security for PWN smart contracts. The PWN team is implementing an on-chain governance system where holders of $PWN tokens can stake their tokens for a predefined time. The owners of the staked tokens are granted voting power and revenue share.

This security review focuses exclusively on the smart contracts listed in Section 2 (Audited Files).

The audit was performed using (a) manual analysis of the codebase and (b) creation of test cases.

Audit assessment
Audit TypeSecurity Review
Initial ReportNov 13, 2024
Response from ClientRegular responses during audit engagement
Final ReportNov 13, 2024
Repositorypwn_dao
Commit (Audit)51bf87dc5d
Commit (Final)0e77ede940
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
3
Fixed
2
Acknowledged
1
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium0
  • Low0
  • Informational3
  • Best Practices0

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1PWNEpochClock.sol201995%847
2token/PWN.sol13210277%52285
3token/StakedPWN.sol4854112%28130
4token/VoteEscrowedPWN.sol401640%965
5token/vePWN/VoteEscrowedPWNBase.sol934649%35174
6token/vePWN/VoteEscrowedPWNStake.sol35715944%77591
7token/vePWN/VoteEscrowedPWNPower.sol1474832%35223
8token/vePWN/VoteEscrowedPWNStorage.sol2539156%1781
9token/vePWN/VoteEscrowedPWNStakeMetadata.sol1521610%26191
10lib/BitMaskLib.sol2224109%955
11lib/SlotComputingLib.sol1531206%854
12lib/EpochPowerLib.sol251872%750
13lib/Error.sol36822%953
Total111258052.2%3201999

4

System Overview

The PWN ecosystem utilizes three different tokens as shown in the figure below: PWN, StakedPWN, and VoteEscrowedPWN. This section provides an overview of each token contract and its core functionalities.

4.1 PWN token

The PWN token is the main governance token of the PWN DAO and is used as a reward for participants who vote on proposals. The contract owner is the PWN DAO, which holds control over certain functionalities of the token. Initially, the token is non-transferable. The owner can later enable transfers or configure the contract to allow transfers only by specific actors.

The token is designed to have a maximum supply of 100 million tokens, and only the contract owner is authorized to mint new tokens through the mint(...) function.

function mint(uint256 amount) external onlyOwner

In addition to minting, token holders have the ability to burn their tokens. This is done through the burn(...) function.

function burn(uint256 amount) external

4.1.1 Voting Rewards

The contract owner can set a reward percentage for each voting contract via the setVotingReward(...) function. This reward is capped at 1% of the total supply of PWN tokens.

function setVotingReward(address votingContract, uint256 votingReward) external onlyOwner

Once the reward percentage is set, the voting contract can invoke the assignProposalReward(...) function to calculate and assign rewards for individual proposals. This function computes the reward amount based on the assigned percentage of the current total supply.

function assignProposalReward(uint256 proposalId) external

Once a proposal is executed, voters who participated in the vote can claim their rewards through the claimProposalReward(...) and claimProposalRewardBatch(...) functions to claim individual or batched proposals, respectively.

function claimProposalReward(address votingContract, uint256 proposalId) public
function claimProposalRewardBatch(address votingContract, uint256[] calldata proposalIds) external

4.2 StakedPWN token

The StakedPWN token is an ERC721 token that represents a stake in the PWN DAO. By default, this token is non-transferable. However, the contract owner can enable transfers using the enableTransfers() function:

function enableTransfers() external onlyOwner

Alternatively, specific addresses can be allowed to transfer StakedPWN tokens through the setTransferAllowlist(...) function:

function setTransferAllowlist(address addr, bool isAllowed) external onlyOwner

Additionally, the minting and burning of StakedPWN tokens is restricted to the SupplyManager address, which points to the VoteEscrowedPWN contract.

4.3 VoteEscrowedPWN token

The VoteEscrowedPWN token contract handles the main logic for staking PWN tokens and voting powers calculation for stakers.

4.3.1 Stake creation

Users can stake their PWN tokens through the createStake(...) or createStakeOnBehalfOf(...) function, the latter allowing them to stake on behalf of another staker. These functions require users to specify the amount of PWN tokens to stake and the lockup period (measured in epochs) for the stake. The lockup period must be between 1 and 5 years or exactly 10 years. The tokens are transferred from the user to the contract, and a StakedPWN token representing the stake is minted back to the user.

function createStake(uint256 amount, uint256 lockUpEpochs) external returns (uint256)
function createStakeOnBehalfOf(address staker, address beneficiary, uint256 amount, uint256 lockUpEpochs)
public
returns (uint256 stakeId)

Upon creating a stake, the beneficiary receives voting power based on the staked amount and the lockup period. This voting power decreases over time according to a predefined schedule, reaching zero when the lockup period ends.

4.3.2 Stake operations

Stakers can merge two separate stakes into a single one using the mergeStakes(...) function. This operation requires that the first stake ends before the second one and that the first stake ends after the current epoch + 1. The function updates the total power in the contract and deletes the two original stakes by burning their corresponding StakedPWN tokens. A new stake is then created, with the staker acting as both the owner and beneficiary and the new stake amount being the sum of the merged stakes.

function mergeStakes(uint256 stakeId1, address stakeBeneficiary1, uint256 stakeId2, address stakeBeneficiary2)
external
returns (uint256 newStakeId)

Additionally, stakers can split their stakes into two separate stakes using the splitStake(...) function. This operation deletes the original stake and creates two new stakes with the staker as both the owner and beneficiary. The amount is split according to the specified splitAmount, and the total power in the contract remains unchanged.

function splitStake(uint256 stakeId, address stakeBeneficiary, uint256 splitAmount)
external
returns (uint256 newStakeId1, uint256 newStakeId2)

The increaseStake(...) function allows users to increase the amount or the lockup duration of their stakes. This requires deleting the original stake and burning its corresponding stakeId. A new stake is then created with the updated parameters, and the total power in the contract is adjusted to reflect the changes in the amount and lockup epochs.

function increaseStake(uint256 stakeId, address stakeBeneficiary, uint256 splitAmount)
external
returns (uint256 newStakeId1, uint256 newStakeId2)

4.3.3 Withdraw stake

Once the lockup period has expired, users can withdraw their staked PWN tokens using the withdrawStake(...) function. This process involves deleting the stake, burning the associated stakeId, and transferring the staked PWN tokens back to the user.

function withdrawStake(uint256 stakeId, address stakeBeneficiary) external

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 Invariant break when increasing stake

FileFix commitTypeStatus
VoteEscrowedPWNStake.sol0aec9d5InfoFixed

The contract enforces a limit on the maximum amount of tokens that can be staked by using the uint88 type. As seen in the following code snippet, the maximum stake is limited by the range of uint88:

In the increaseStake(...) function, the contract checks that the additionalAmount being staked does not exceed the uint88 limit. However, it only considers the additionalAmount and does not account for the user’s already staked amount. As a result, the total stake (current stake + additional stake) may exceed the uint88 limit.

function increaseStake(...) external returns (uint256 newStakeId){
// ...
// @audit only the additional amount is checked
if (additionalAmount > type(uint88).max) {
revert Error.InvalidAmount();
}
// ...
}

Recommendation

Update the check to ensure that the total stake, including both the current stake and the additionalAmount (stake.amount + additionalAmount), does not exceed the uint88 limit.

Resolution

Fixed by adding a check for the new amount in range of uint88 after stake increase.

Commit: 0aec9d5176fad7161663a89212bcaebbc5d38c95

6.2 Absence of a mechanism to disable transfers

FileFix commitTypeStatus
PWN.sol—InfoAcknowledged

The PWN contract has an enableTransfers() function which enables transfers of PWN tokens.

function enableTransfers() external onlyOwner {  //@audit no mechanism to disable transfers
if (transfersEnabled) {
revert Error.TransfersAlreadyEnabled();
}
transfersEnabled = true;
}

However, there is no mechanism to disable transfers if needed. As such, once transfer is enabled it cannot be disabled.

Recommendation

Consider implementing a functionality to disable transfers in the contract.

Resolution

It is an intended behaviour. PWN and stPWN tokens should have only one-time transfer enabler.

6.3 Inconsistency in conditions of mergeStakes(...) function

FileFix commitTypeStatus
VoteEscrowedPWNStake.sol3c286feInfoFixed

In the mergeStakes(...) function, there is an inconsistency between the comment and the actual condition implemented in the code. The comment suggests that both lockup ends must be greater than the current epoch (newInitialEpoch). However, the implemented condition only checks that finalEpoch1 is greater than or equal to the current epoch, not validating the lockup end of the second stake (finalEpoch2)

function mergeStakes(...) external returns (uint256 newStakeId) {
// ...
// the first stake lockup end must be greater than or equal to the second stake lockup end
// both stake lockup ends must be greater than the current epoch
// @audit The condition only checks if first stake lockup end is greater than the current epoch
if (finalEpoch1 < finalEpoch2 || finalEpoch1 <= newInitialEpoch) {
revert Error.LockUpPeriodMismatch();
}
// ...
}

Recommendation

Revise the intended behavior and update either the condition or the comment to ensure consistency.

Resolution

Commit: 3c286fec003c5d2a86586dc1c5ed08ea9d03b201

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

The PWN team has provided detailed and comprehensive documentation that offers a clear overview of the protocol, along with technical specifications for each token and its main functionalities. Additionally, the team has proactively addressed concerns and questions raised by the Nethermind Security team during their regular meetings.

Test suite
370Tests passed2Failed

The complete test output is in the full report.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.