1

2

Table of Contents
Executive Summary
Project Context
Audit scope
Security RatingStandardised Checks
Intended Smart Contract Functions
Code Quality
Audit Resources
Dependencies
Severity Definitions
Audit Findings

4
4
7
8
9
11
12
12
12
13
13

High

14
[H-01] Malicious users can deposit after bonding period to steal rewards from other stakers
14
Description
14
Vulnerability Details
14
Impact14
Recommendation15[H-02] rpTokensQty[token] is not updated in topUpRewardsPoolFor which will cause a dos
when attempting to claim rewards
16
Description
16
Vulnerability Details
16
Impact16
Recommendation
16
StatusResolved
16
Medium16[M-01] If a partner reward token if removed users will lose rewards
16
Description
16
Vulnerability Details
17
Impact17
Recommendations
17[M-02] Time distributed reward updates are sometimes skipped
17
Description
17
Vulnerability Details
17
Impact17
Recommendations
17
Status17
Resolved
18[M-03] Stake’s veAlgmQty is not reset if user unstakes all ALGM
18
Description
18

Hashlock Pty Ltd

3

Vulnerability Details
18
Impact18
Recommendations
18
Status18
Resolved
18[M-04] ALGMStaking - Precision loss due to division before multiplication
18
Description
18
Vulnerability Details
18
Impact19
Recommendations
19
Status19
Resolved
19[M-05] If WASTR is used as a partner token the claimRewards function could be dosed or
double rewards may be claimed
19
Description
19
Vulnerability Description
19
Impact19
Recommendations
19
Status20
Resolved
20
Low
20[L-01] Missing sanity checks for instances of msg.value
20
Recommendations
20
Status20
Resolved
20[L-02] to can be set to zero address
20
Recommendations
20
Status20
Resolved
20
Gas
20[G-01] Initialize calcPredicted as false
20
Status21
Resolved
21[G-02] Storing totalPartnerTokens is unnecessary as partnerTokens is already stored
21
Status21
Resolved
21

Centralisation
Conclusion
Our Methodology
Disclaimers
About Hashlock

22
23
24
26
27

Hashlock Pty Ltd

4Hashlock Pty Ltd

5

CAUTION
THIS DOCUMENT IS A SECURITY AUDIT REPORT AND MAY CONTAINCONFIDENTIAL
INFORMATION.
THIS
INCLUDESIDENTIFIEDVULNERABILITIES AND MALICIOUS CODE WHICH COULD BE USED TOCOMPROMISE THE PROJECT. THIS DOCUMENT SHOULD ONLY BE FOR
INTERNAL USE UNTIL ISSUES ARE RESOLVED. ONCE VULNERABILITIES AREREMEDIATED, THIS REPORT CAN BE MADE PUBLIC. THE CONTENT OF THISREPORT IS OWNED BY HASHLOCK PTY LTD FOR USE OF THE CLIENT.

Hashlock Pty Ltd

6

Executive Summary
The Algem team partnered with Hashlock to conduct a security audit of their
Governance Staking smart contracts. Hashlock manually and proactively reviewed thecode in order to ensure the project’s team and community that the deployed contracts
are secure.

Project Context
Algem is a DeFi dApp built on Astar Network that allows you to stay liquid while staking
your ASTR. Staying liquid means you can double-dip with your Astar tokens by staking
while yield farming.
Simply put, you don't have to choose between staking and yield farming with your Astartokens. You can do both.
Project Name: Algem
Compiler Version: ^0.8.4
Website: https://www.algem.io/

Hashlock Pty Ltd

7

Logo:

Visualised Context:

Hashlock Pty Ltd

8Project Visuals:

Hashlock Pty Ltd

9Audit scope
We at Hashlock audited the solidity code within the Algems Staking Project, the scopeof works included a comprehensive review of the smart contracts listed below. We
tested the smart contracts to check for their security and efficiency. These tests were
undertaken primarily through manual line by line analysis and were supported bysoftware assisted testing.

Description

Project Review and Security Analysis Report for
Algem Protocol Smart Contracts and otherfactors.

Platform

Ethereum / Solidity

Audit Date

August, 2023

Contract 1

ALGMStaking.sol

Contract 1 MD5 Hash

f18c2fe1b45226f8dc3f8cbae0cd0d47

Contract 2

veALGM.sol

Contract 2 MD5 Hash

d4b2caa5c29abc8f0dda0c7ab68b27f3

Hashlock Pty Ltd

10Security Rating
After Hashlock’s Audit, we found the smart contracts to be “Secure”. The contracts allfollow simple logic, with correct and detailed ordering. They use a series of interfaces,
and the protocol uses a list of Open Zeppelin contracts. We initially identified somesignificant vulnerabilities that have since been addressed.

The ‘Hashlocked’ rating is reserved for projects that ensure ongoing security via bug bounty programs or
on chain monitoring technology.

All issues uncovered during automated and manual analysis were meticulously reviewed
and applicable vulnerabilities are presented in the Audit overview section. General
overview is presented in the Function list section and all identified issues can be foundin the Audit overview section.
All vulnerabilities initially identified have now been resolved and acknowledged.
Hashlock found:2 High severity vulnerabilities
5 Medium severity vulnerabilities
2 Low severity vulnerabilities
2 Gas Optimisations

Caution: Hashlock’s audits do not guarantee a project's success or ethics, and are notliable or responsible for security. Always conduct independent research about any
project before interacting.

Hashlock Pty Ltd

11Standardised Checks
Main Category

Subcategory

ResultGeneral Code
ChecksSolidity/compiler version stated

PassedConsistent pragma version across each contract

PassedOutdated Solidity Version

Reviewed

Overflow/underflow

PassedCorrect checks, effects, interaction order

Reviewed

Lack of check on input parameters

Reviewed

Function input parameters check bypass

PassedCorrect Access control

Reviewed

Built in emergency features

Reviewed

Correct event logs

PassedHuman/contract checks bypass

PassedRandom number generation/use vulnerability

PassedFallback function misuse

PassedRace condition

PassedLogical vulnerability

Reviewed

Features claimed

Passeddelegatecall() vulnerabilities

PassedOther programming issues

Reviewed

Correctly declared function visibility

PassedCorrectly declared variable storage location

PassedUse keywords/functions to be deprecatedPassedUnused code

Reviewed“Out of Gas” Issue

Reviewed

High consumption ‘for/while’ loop

Reviewed

Code
Specification

Gas
Optimization

Hashlock Pty Ltd

12Tokenomics
Risk

High consumption ‘storage’ storage

Reviewed

Assert() misuse

PassedThe maximum limit for mintage not set

Passed“Short Address” Attack

Passed“Double Spend” Attack

PassedInitial Audit Result: VULNERABLE
Revised Audit Result: PASSED

Hashlock Pty Ltd

13Intended Smart Contract Functions
Claimed Behaviour

Actual Behaviour

ALGMStaking

The contract achieves this-Allows users to stake and unstake their ALGM

behaviour however, as it

tokens in exchange for rewards.

can be seen from the below

Allows admins to have access to special functions findings, there may be
for the purpose of configuration and settings up

some instances where

rewards tokens.

rewards tokens may bestolen or denial of service
conditions may be met.

veAlgm-This contract achieves its

Acts as an ERC20 token contract which is given
to users as a representation of their staking
position in the staking contract.

Hashlock Pty Ltd

intended behaviour.

14

Code Quality
This audit scope involves the solidity smart contracts of the Algem project, as outlinedin the Audit Scope section. All contracts, libraries and interfaces mostly follow standard
best practices and to help avoid unnecessary complexity that increases the likelihood of
exploitation, however some refactoring is required.
The code is very well commented and closely follows best practice nat-spec styling. Allcomments are correctly aligned with code functionality.

Audit Resources
We were given the Algem Protocol’s smart contract code in the form of Github access.
As mentioned above, code parts are well commented. The logic is straightforward, andtherefore it is easy to quickly comprehend the programming flow as well as the complex
code logic. The comments are helpful in understanding the overall architecture of the
protocol.

Dependencies
As per our observation, the libraries used in this smart contracts infrastructure arebased on well known industry standard open source projects.
Apart from libraries, its functions are used in external smart contract calls.

Hashlock Pty Ltd

15

Severity Definitions
SignificanceHigh

MediumDescription
High severity vulnerabilities can result in loss of funds,
asset loss, access denial, and other critical issues thatwill result in the direct loss of funds and control by theowners and community.
Medium level difficulties should be solved before
deployment, but won't result in loss of funds.

Low

Low level vulnerabilities are areas that lack best practices
that may cause small complications in the future.

Gas

Gas Optimisations, issues and inefficiencies

Hashlock Pty Ltd

16

Audit FindingsHigh[H-01] Malicious users can deposit after bonding period to steal rewards
from other stakers
Description
The ALGMStaking contract allows for users to stake their ALGM tokens and claim rewards
in the form of partner or ASTR tokens. These rewards accumulate over a period of timeto which users can unstake their tokens and claim their rewards; however, user rewards
will be inflated should they stake a significant amount after a certain period of time.
Vulnerability Details
When the contract calculates the quantity of ALGM staked into the contract, this value
can be added to or removed from at any point during the staking period and thecontract will believe that users have been staking that value from the beginning. This
will give exploiters an opportunity to inflate their entitled rewards by staking asignificant amount at a later date.
ImpactTheft of rewards from other users in the same pool. The proof of concept below
outlines this scenario:
function testTheftOfStakingRewards() public {// Setup scenarioalgm.mint(address(eve), 30_000 ether); // issue initial balance to the user
algm.mint(address(alice), 10_000 ether);algm.mint(address(bob), 10_000 ether);vm.startPrank(alice);algm.approve(address(staking), type(uint256).max);
staking.stake(0, 10_000 ether);vm.stopPrank();vm.startPrank(bob);algm.approve(address(staking), type(uint256).max);
staking.stake(0, 10_000 ether);vm.stopPrank();// Malicious user deposits the same amount into the staking contract using a
malicious contract

Hashlock Pty Ltd

17vm.startPrank(eve);algm.approve(address(staking), type(uint256).max);
staking.stake(0, 10_000 ether);vm.stopPrank();vm.warp(10 days); // set block timestamp to accumulate rewards// 10 days have passed and it's time to collect rewards
vm.startPrank(address(eve));// Claimable rewards before(
uint256 astrQty,
IERC20[] memory tokensList,
uint256[] memory tokensQty,
bool rewardsAvailableFlag) = staking.calculateRewards(address(eve), 0);
uint256 astrQtyBefore = astrQty;
staking.stake(0, 20_000 ether);(
astrQty,tokensList,
tokensQty,
rewardsAvailableFlag) = staking.calculateRewards(address(eve), 0);
uint256 astrQtyAfter = astrQty;
vm.stopPrank();// Asserts that staking rewards are immediately inflated
assertGt(astrQtyAfter, astrQtyBefore);}

Recommendation
It’s recommended that user stakes are separated out into different buckets for example
stakes[poolID][staker][stakeID] which will allow each staking transaction to be handled
separately when calculating rewards. An alternative solution is to deny users fromstaking if they already have ALGM tokens in the contract and when they withdraw, they
are forced to withdraw their entire stake.

Hacker’s notes● Possibly susceptible to flashloan attacks

Hashlock Pty Ltd

18

StatusInvalid - Waiting 10 days does not generate rewards. 10 days is just an un-bonding
period during which one can not withdraw their staked ALGM.

[H-02] rpTokensQty[token] is not updated in topUpRewardsPoolFor which
will cause a dos when attempting to claim rewards
Description
The topUpRewardsPoolFor function will allow an owner to add rewards to certain ASTR orpartner tokens. Users can claim these rewards for staking their ALGM tokens in thecontract. msg.value is accounted for if ASTR tokens are used and ERC20 is used fortransferring other tokens to the contract.
Vulnerability Details
Various checks are made on the quantity and token being used to top the rewards poolup however, rpTokensQty is not updated with the amount of qty which has been added tothe pool which effectively means, a top up never happened. Because this state variable
is heavily relied upon when calling the claimRewards function, this may cause anunderflow which will deny users from claiming their rewards.
ImpactThis will create a denial of service condition against the claimRewards function.
Recommendation
It’s recommended that the rpTokensQty state variable is updated when an owner tops up
the reward pool in topUpRewardsPoolFor function.
StatusResolved

Medium
[M-01] If a partner reward token if removed users will lose rewards
Description
The staking contract owner can add partner tokens to the protocol in order toadminister rewards in this type of token through the calculation of rewards. If an ownerdeletes a partner token where there are pending rewards, the users may lose rewards
for their staking efforts.

Hashlock Pty Ltd

19

Vulnerability Details
This is due to the lack of checks when attempting to delete a partner reward token. If atoken is removed, this is not accounted for in the claimRewards and _calculateRewards
function which effectively loses the accumulated rewards of users.
ImpactUsers will lose their rewards if a partner reward token is deleted.
Recommendations
Check if there are pending rewards before owners remove partner tokens.
StatusResolved[M-02] Time distributed reward updates are sometimes skipped
Description
The _updateTimeDistRewards function is responsible for updating the ARPS for tokens
which are distributed within TimeDistRewards. This will then delete the completed
TimeDistRewards entry from the storage of the contract; however, time distributed
rewards may be skipped.
Vulnerability Details
Because this deletes the TDR by replacing the last element with the current one thenpopping the last element within a for loop, the last TDR will be missed since it’s being
moved to the current index which has already been processed.
ImpactUser rewards may be skipped
Recommendations
It’s recommended that there are some additional checks on the token quantity inaddition to the timeframe and slicesDistributed to ensure that time dist reward indexes
aren’t accidentally deleted.

Hacker’s notes● Discovered in ALGMStaking#_updateTimeDistRewards
StatusHashlock Pty Ltd

20Resolved[M-03] Stake’s veAlgmQty is not reset if user unstakes all ALGM
Description
If the user unstakes their entire staked algmQty, then the veAlgmQty value inside theirstake does not get reset back to 0.
Vulnerability Details
If a user unstakes all of their ALGM tokens, then the veAlgmQty does not change if
stakedQty == unstakeQty in the unstake function. In the future once guages are
implemented, this may be exploited to have greater voting power than intended.
ImpactThe user’s stake.veAlgmQty value will show that they still have veALGM even though it has
been burnt. If this value is to be used for gauge weight voting in the future, it is possible
for an exploiter to be able to vote with veALGM that they no longer hold.
Recommendations
It’s recommended that the quantity of veAlgm is updated to zero if they unstake all of
their tokens.

Hacker’s notes● Discovered in ALGMStaking#unstake
StatusResolved[M-04] ALGMStaking - Precision loss due to division before multiplication
Description
There are multiple instances in ALGMStaking where division is applied before
multiplication. In particular, _updateTokenARPSinPools and _calculateVeALGM both divide
before multiplying. This results in lost rewards and veALGM.
Vulnerability Details
Because Solidity handles multiplication before division differently to division before
multiplication due to floating point errors, we instead get rounding errors. By doing themultiplication operations first, we can mitigate the rounding related issues as much as
possible.

Hashlock Pty Ltd

21

ImpactPrecision loss when attempting to calculate veAlgm tokens. This impact can be summed
up in the following example:
console.log((30 * 100 * 13) / 13)> 3000console.log((30 / 13) * 100 * 13)> 2999.9999999999995

Recommendations
It’s recommended that multiplication operations are done before division operations
throughout the code base.
StatusResolved[M-05] If WASTR is used as a partner token the claimRewards function could
be dosed or double rewards may be claimed
Description
The claimRewards function is being used to reward users for their staking efforts throughboth ASTR tokens and partner tokens. Both instances of rewards are iterated throughwith a for loop with minimal checks which may cause some issues if WASTR is
accidentally added as a partner token.
Vulnerability Description
Because the claimRewards function does two for loops with minimal checks, when WASTR
token is passed to rpTokensQty when attempting to determine the ERC20 rewards, theWASTR address could be used twice. If the rewards pool for WASTR was not funded this
could create a dos however if the rewards pool was funded with WASTR, this could
create duplicate rewards as ASTR token was transferred to the user via a call() in theprevious for loop iteration.
ImpactThis could result in a denial of service condition or double claim in rewards.
Recommendations
Because the WASTR address is already considered in the state variables, it’srecommended that owners are not allowed to add WASTR as a partner token. In
addition to this, it’s recommended that sanity checks are implemented to prevent

Hashlock Pty Ltd

22

WASTR from being transferred as an ERC20 when it was already transferred in a low
level call as native tokens in the previous iteration.
StatusResolved

Low[L-01] Missing sanity checks for instances of msg.value
Recommendations
Ensure that msg.value is zero so tokens are not lost.
StatusResolved
Hacker’s Notes● Discovered in ALGMStaking#topUpRewardsPool[L-02] to can be set to zero address
Recommendations
If from != address(0) then to can be the zero address. It’s recommended that this edge
case is checked for.

Hacker’s notes● Discovered in ALGMStaking/veALGM#_revertIfInvalidAddr
StatusResolved

Gas[G-01] Initialize calcPredicted as false
Hacker’s notes

Hashlock Pty Ltd

23● Discovered in ALGMStaking#_calculateRewards

StatusResolved[G-02] Storing totalPartnerTokens is unnecessary as partnerTokens isalready stored
Hacker’s notes● Discovered in ALGMStaking
StatusResolved

Hashlock Pty Ltd

24

Centralisation
The project values security and utility over decentralisation.
The owner executable functions within the protocol increase security and functionality
but depend highly on internal team responsibility.

Hashlock Pty Ltd

25Conclusion
After Hashlocks analysis, the Algem project seems to have a sound and well tested code
base, however our findings need to be resolved in order to achieve security. Overall,most of the code is correctly ordered and follows industry best practices. The code iswell commented as well. To the best of our ability, Hashlock is not able to identify any
further vulnerabilities.

Hashlock Pty Ltd

26

Our Methodology
Hashlock strives to maintain a transparent working process and to make our audits acollaborative effort. The objective of our security audits are to improve the quality ofsystems and upcoming projects we review and to aim for sufficient remediation to help
protect users and project leaders. Below is the methodology we use in our security audit
process.
Manual Code Review:
In manually analysing all of the code, we seek to find any potential issues with code
logic, error handling, protocol and header parsing, cryptographic errors, and random
number generators. We also watch for areas where more defensive programming could
reduce the risk of future mistakes and speed up future audits. Although our primary
focus is on the in-scope code, we examine dependency code and behaviour when it isrelevant to a particular line of investigation.
Vulnerability Analysis:
Our methodologies include manual code analysis, user interface interaction, andwhitebox penetration testing. We consider the project's website, specifications, andwhitepaper (if available) to attain a high level understanding of what functionality thesmart contract under review contains. We then communicate with the developers andfounders to gain insight into their vision for the project. We install and deploy therelevant software, exploring the user interactions and roles. While we do this, webrainstorm threat models and attack surfaces. We read design documentation, review
other audit results, search for similar projects, examine source code dependencies, skim
open issue tickets, and generally investigate details other than the implementation.

Hashlock Pty Ltd

27Documenting Results:
We undergo a robust, transparent process for analysing potential security vulnerabilities
and seeing them through to successful remediation. When a potential issue isdiscovered, we immediately create an issue entry for it in this document, even though
we have not yet verified the feasibility and impact of the issue. This process is vast
because we document our suspicions early even if they are later shown to not represent
exploitable vulnerabilities. We generally follow a process of first documenting thesuspicion with unresolved questions, then confirming the issue through code analysis,
live experimentation, or automated tests. Code analysis is the most tentative, and we
strive to provide test code, log captures, or screenshots demonstrating ourconfirmation. After this we analyse the feasibility of an attack in a live system.
Suggested Solutions:
We search for immediate mitigations that live deployments can take and finally wesuggest the requirements for remediation engineering for future releases. The
mitigation and remediation recommendations should be scrutinised by the developers
and deployment engineers, and successful mitigation and remediation is an ongoingcollaborative process after we deliver our report, and before the contracts details are
made public.

Hashlock Pty Ltd

28Disclaimers
Hashlock’s Disclaimer
Hashlock’s team has analysed these smart contracts in accordance with the bestindustry practices at the date of this report, in relation to: cybersecurity vulnerabilities
and issues in the smart contract source code, the details of which are disclosed in thisreport, (Source Code); the Source Code compilation, deployment and functionality(performing the intended functions).
Due to the fact that the total number of test cases are unlimited, the audit makes nostatements or warranties on security of the code. It also cannot be considered as asufficient assessment regarding the utility and safety of the code, bugfree status or any
other statements of the contract. While we have done our best in conducting theanalysis and producing this report, it is important to note that you should not rely on
this report only. We also suggest conducting a bug bounty program to confirm the highlevel of security of this smart contract.
Hashlock is not responsible for the safety of any funds, and is not in any way liable forthe security of the project.

Technical Disclaimer
Smart contracts are deployed and executed on a blockchain platform. The platform, its
programming language, and other software related to the smart contract can have theirown vulnerabilities that can lead to attacks. Thus, the audit can’t guarantee explicit
security of the audited smart contracts.

Hashlock Pty Ltd

29

About Hashlock
Hashlock is an Australian based company aiming to help facilitate the successful
widespread adoption of distributed ledger technology. Our key services all have a focus
on security, as well as projects that focus on streamlined adoption in the businesssector.
Hashlock is excited to continue to grow its partnerships with developers and other web3
oriented companies to collaborate on secure innovation, helping businesses anddecentralised entities alike.
Website: hashlock.com.au
Contact: info@hashlock.com.au

Hashlock Pty Ltd

30Hashlock Pty Ltd