Overview
This audit covered Swell Network's CumulativeMerkleDrop contract, which handles the initial distribution of the SWELL token using Merkle proofs, as well as the Staking contract where users can simply stake their SWELL tokens.
Our security assessment was a full review of the two smart contracts, spanning a total of 3 days.
During our audit we have identified several minor severity vulnerabilities and code optimisations.
Finally, all of our reported issues were fixed by the development team and consequently validated by us.
We can confidently say that the overall security and code quality have increased after completion of our audit.
Scope
The analyzed resources are located on:
https://github.com/SwellNetwork/swell-contracts/tree/2559c9e4f6140f6080bc0e3a2dc94410c82ac907
The issues described in this report were fixed in the following commit:
https://github.com/SwellNetwork/swell-contracts/tree/b13923d8c4a979bcfa5ceec9b35f65137e2e7634
Summary
Weaknesses
This section contains the list of discovered weaknesses.
SWSMC-1| CHANGING THE COOLDOWN TIME MAY RESULT IN FUNDS BEING UNEXPECTEDLY LOCKED FOR A LONGER TIME
Severity:
Status:
Fixed
Path:
Staking.sol:unlock()
Description:
There exists an edge case for the unlocking of funds, where an unlock request funds might persist for a longer time (based on the old cooldownTime) in the scenario described below, as the cycle within the unlock() function terminates when requests[i].unlockTime > block.timestamp.
- Let's assume that
cooldownTimeis 7 days. userlocks 1000 tokens.usedcallsrequestUnlock(300)to request 300 token unlock, sounlockRequests[msg.sender].unlockTimeisblock.timestamp + cooldownTime(current timestamp plus 7 days).ownerchangescooldownTimeto 1 day.usercallsrequestUnlock(700)to request 700 token unlock, sounlockRequests[msg.sender].unlockTimeisblock.timestamp + cooldownTime(current timestamp plus 1 day).- After passing 1 day user calls
unlock()function to unlock his 700 tokens. - Because the first request with index 0's
unlockTimeis later than current timestamp (requests[i].unlockTime > block.timestamp) the cycle insideunlockfunction will break, and theusershould wait at least 7 days to unlock his tokens, even if theunlockTimeof the second request has already expired.
function lock(address _account, uint256 _amount) external {
if (_account == address(0)) revert ADDRESS_NULL();
if (_amount == 0) revert AMOUNT_NULL();
ERC20(TOKEN).transferFrom(msg.sender, address(this), _amount);
balanceOf[_account] += _amount;
totalSupply += _amount;
emit Lock(_account, _amount);
}
/// @inheritdoc IStaking
function requestUnlock(uint256 _amount) external {
if (_amount == 0) revert AMOUNT_NULL();
if (balanceOf[msg.sender] < _amount) revert INSUFFICIENT_BALANCE();
if (unlockRequests[msg.sender].length >= MAX_REQUESTS) revert MAX_REQUESTS_REACHED();
balanceOf[msg.sender] -= _amount;
totalSupply -= _amount;
unlockRequests[msg.sender].push(Request(_amount, block.timestamp + cooldownTime));
emit RequestUnlock(msg.sender, _amount, block.timestamp + cooldownTime);
}
/// @inheritdoc IStaking
function unlock() external {
Request[] storage requests = unlockRequests[msg.sender];
uint256 total;
uint256 len = requests.length;
for (uint256 i; i < len; ++i) {
if (requests[i].unlockTime == 0) continue;
if (requests[i].unlockTime <= block.timestamp) {
total += requests[i].amount;
delete requests[i];
} else {
break;
}
}
if (total > 0) ERC20(TOKEN).transfer(msg.sender, total);
emit Unlock(msg.sender, total);
}
We would recommend allowing a user not to break the loop inside the unlock() function, based on a parameter, so breaking early is still possible as gas optimisation:
function unlock(bool stopEarly) external {
Request[] storage requests = unlockRequests[msg.sender];
uint256 total;
uint256 len = requests.length;
for (uint256 i; i < len; ++i) {
if (requests[i].unlockTime == 0) continue;
if (requests[i].unlockTime <= block.timestamp) {
total += requests[i].amount;
delete requests[i];
} else if (stopEarly) {
break;
}
}
if (total > 0) ERC20(TOKEN).transfer(msg.sender, total);
emit Unlock(msg.sender, total);
}
SWSMC-2 | GAS INEFFICIENT WAY OF HANDLING USER REQUESTS
Severity:
Status:
Fixed
Path:
Staking.sol
Description:
A user has to create an unlock request using requestUnlock, which will push a new unlock request to the array, keeping the order of timestamps.
The order of timestamps allows for a more gas efficient unlocking in unlock, however this function only deletes the data in the array entry upon unlock. Subsequent unlocks will still loop through these empty elements, which costs an extra SLOAD for each entry each time.
To prevent this, a user is supposed to call cleanEmptyRequests, which shifts the pending requests to the front and pops the empty requests. This can still cost a significant amount of gas, depending on the amount of empty requests, where fewer will have a higher gas cost.
So in both cases, the user will be paying more gas due to the gas inefficient way handling these requests.
function requestUnlock(uint256 _amount) external {
if (_amount == 0) revert AMOUNT_NULL();
if (balanceOf[msg.sender] < _amount) revert INSUFFICIENT_BALANCE();
if (unlockRequests[msg.sender].length >= MAX_REQUESTS) revert MAX_REQUESTS_REACHED();
balanceOf[msg.sender] -= _amount;
totalSupply -= _amount;
unlockRequests[msg.sender].push(Request(_amount, block.timestamp + cooldownTime));
emit RequestUnlock(msg.sender, _amount, block.timestamp + cooldownTime);
}
/// @inheritdoc IStaking
function unlock() external {
Request[] storage requests = unlockRequests[msg.sender];
uint256 total;
uint256 len = requests.length;
for (uint256 i; i < len; ++i) {
if (requests[i].unlockTime == 0) continue;
if (requests[i].unlockTime <= block.timestamp) {
total += requests[i].amount;
delete requests[i];
} else {
break;
}
}
if (total > 0) ERC20(TOKEN).transfer(msg.sender, total);
emit Unlock(msg.sender, total);
}
/// @inheritdoc IStaking
function cleanEmptyRequest() external {
Request[] storage requests = unlockRequests[msg.sender];
Request[] memory refRequests = requests;
uint256 emptySlots;
uint256 len = refRequests.length;
// Count the number of empty slots at the beginning of the array
for (uint256 i; i < len; ++i) {
if (refRequests[i].unlockTime == 0) ++emptySlots;
else break;
}
// Shift the elements to the left to override the empty slots
for (uint256 i; i < len - emptySlots; ++i) {
requests[i] = refRequests[i + emptySlots];
}
// Pop as much as empty slots
for (uint256 i; i < emptySlots; ++i) {
requests.pop();
}
}
Remediation:
We would recommend to implement a more gas efficient way of unlocking and removing a user's unlock requests.
For example by using a mapping instead of array and a linearly incremental pointer to the first valid unlock request in that mapping, as well as the current length.
requestUnlock would increment the length (totalUnlockRequests[msg.sender]) and store the unlock request in the mapping at that length.
unlock can loop from the pointer to the length (and possibly break earlier), while still deleting the mapping entries (for refund) and at the end simply increasing the pointer with the amount of unlocked requests. The next call would not have to loop over unlocked requests.
cleanEmptyRequests can be removed.
SWSMC-6 | LACK OF UPPER LIMIT CHECK FOR LOCK DURATION ALLOWS FREEZING OF ASSETS
Severity:
Status:
Fixed
Description:
In the Staking contract, cooldownTime represents the duration one must wait after requesting an unlock. While this variable is modifiable, the corresponding setter function lacks an upper-bound check for the values it accepts. Consequently, cooldownTime can be to any arbitrary uint256 value, thereby preventing the unlocking of user assets.
function setCooldownDuration(uint256 _duration) external onlyOwner {
emit CooldownUpdated(cooldownTime, _duration);
cooldownTime = _duration;
}
Remediation:
Sensible upper limits should be checked before setting the value.
SWSMC-3 | GAS IMPROVEMENTS FOR ARITHMETIC OPERATIONS
Severity:
Status:
Fixed
Path:
Staking.sol, CumulativeMerkleDrop.sol
Description:
Since there's no possibility of overflow/underflow within the contracts, it's advisable to relocate all arithmetic operations inside an unchecked block.
Steking.sol
/// @inheritdoc IStaking
function lock(address _account, uint256 _amount) external {
if (_account == address(0)) revert ADDRESS_NULL();
if (_amount == 0) revert AMOUNT_NULL();
ERC20(TOKEN).transferFrom(msg.sender, address(this), _amount);
balanceOf[_account] += _amount;
totalSupply += _amount;
emit Lock(_account, _amount);
}
/// @inheritdoc IStaking
function requestUnlock(uint256 _amount) external {
if (_amount == 0) revert AMOUNT_NULL();
if (balanceOf[msg.sender] < _amount) revert INSUFFICIENT_BALANCE();
if (unlockRequests[msg.sender].length >= MAX_REQUESTS) revert MAX_REQUESTS_REACHED();
balanceOf[msg.sender] -= _amount;
totalSupply -= _amount;
unlockRequests[msg.sender].push(Request(_amount, block.timestamp + cooldownTime));
emit RequestUnlock(msg.sender, _amount, block.timestamp + cooldownTime);
}
/// @inheritdoc IStaking
function unlock() external {
Request[] storage requests = unlockRequests[msg.sender];
uint256 total;
uint256 len = requests.length;
for (uint256 i; i < len; ++i) {
if (requests[i].unlockTime == 0) continue;
if (requests[i].unlockTime <= block.timestamp) {
total += requests[i].amount;
delete requests[i];
} else {
break;
}
}
if (total > 0) ERC20(TOKEN).transfer(msg.sender, total);
emit Unlock(msg.sender, total);
}
/// @inheritdoc IStaking
function cleanEmptyRequest() external {
Request[] storage requests = unlockRequests[msg.sender];
Request[] memory refRequests = requests;
uint256 emptySlots;
uint256 len = refRequests.length;
// Count the number of empty slots at the beginning of the array
for (uint256 i; i < len; ++i) {
if (refRequests[i].unlockTime == 0) ++emptySlots;
else break;
}
// Shift the elements to the left to override the empty slots
for (uint256 i; i < len - emptySlots; ++i) {
requests[i] = refRequests[i + emptySlots];
}
// Pop as much as empty slots
for (uint256 i; i < emptySlots; ++i) {
requests.pop();
}
}
CumulativeMerkleDrop.sol
/// @inheritdoc ICumulativeMerkleDrop
function claimAndLock(uint256 cumulativeAmount, uint256 amountToLock,
uint256 index, bytes32[] calldata merkleProof)
external
onlyClaimOpen
{
// Verify the merkle proof
if (!verifyProof(merkleProof, index, cumulativeAmount, msg.sender))
revert INVALID_PROOF();
// Mark it claimed
uint256 preclaimed = cumulativeClaimed[msg.sender];
if (preclaimed >= cumulativeAmount) revert NOTHING_TO_CLAIM();
cumulativeClaimed[msg.sender] = cumulativeAmount;
// Send the token
uint256 amount = cumulativeAmount - preclaimed;
if (amountToLock > amount) revert INSUFFICIENT_AMOUNT();
if (amountToLock > 0) _lock(amountToLock);
if (amount != amountToLock) ERC20(token).transfer(msg.sender, amount - amountToLock);
emit Claimed(msg.sender, amount);
}
Remediation:
Relocate all arithmetic operations inside an unchecked block.
SWSMC-5 | CUSTOM ERROR
Severity:
Status:
Fixed
Description:
In the CumulativeMerkleDrop contract, validation checks are executed through custom errors, with the require statement employed exclusively at a single location.
function setClaimStatus(uint8 status) external onlyOwner {
require(status == 1 || status == 2, "Invalid status");
claimIsOpen = status;
}
Remediation:
We would recommend replacing those checks with a custom error in favour of saving deployment gas and byte code size.