Dafi Staking Contract Final Audit

Share on facebook
Share on twitter
Share on linkedin

Table of Contents


Key Understandings


Name: Dafi
Auditor: Moazzam Arif | Shakeib Shaida
Platform: Ethereum/Solidity
Type of review: Super-staking with Rebasing
Methods: Architecture Review, Functional Testing, Computer-Aided Verification, Manual Review
Git Repository: (zip files provided)
White paper/Documentation: https://docs.dafiprotocol.io/
Document log: Initial Audit: 05th July 2021, Final Audit: 4th August 2021


The git-repository shared was checked for common code violations along with vulnerability-specific probing to detect major issues/vulnerabilities. Some specific checks are as follows:

Code reviewFunctional review
Reentrancy Unchecked external callBusiness Logics Review
Ownership TakeoverERC20 API violationFunctionality Checks
Timestamp DependenceUnchecked mathAccess Control & Authorization
Gas Limit and LoopsUnsafe type inferenceEscrow manipulation
DoS with (Unexpected) ThrowImplicit visibility levelToken Supply manipulation
DoS with Block Gas LimitDeployment ConsistencyAsset’s integrity
Transaction-Ordering DependenceRepository ConsistencyUser Balances manipulation
Style guide violationData ConsistencyKill-Switch Mechanism
Costly LoopOperation Trails & Event Generation


Executive Summary

The analysis indicates that the contracts audited are secured (with a few financial scalability issues).

Our team performed a technique called “Filtered Audit”, where the contract was separately audited by two individuals. After their thorough and rigorous process of manual testing, an automated review was carried out using Mythril, MythX and Slither. All the flags raised were manually reviewed and re-tested. 

Our team found:

# of issues Severity of the risk
0Critical Risk issue(s)
0High-Risk issue(s)
2Medium Risk issue(s)
3Low-Risk issue(s)
0Informatory issues(s)



Critical-risk issues

No issues found.

High-risk issues

No High risk issues were found.

Medium-risk issues

1. Rebasing and Reward Distribution Formula is flawed

File: RebaseEngine.sol

Distribution per second is calculated abnormally
In the following lines:-

uint poolCurrent = ((MAX_DAFI - dDAFIDistributed + feesDeposited) * demandFactorNew);
uint distributePerSecond = poolCurrent / database.getProgramDuration(); //

the remaining pools is divided by the whole program duration 

There needs to be an extensive discussion on how the current formula and financial model works, only then a revised version can be created.

Update (Aug 4th 2021):
We are working out the formula with the Dafi team. It’s not finalized yet. Once ready, we will share that too.

2. Malicious whitelisted account can withdraw all staked token

File: TokenPool.sol
In function transfer(address to, uint256 value)malicious whitelisted accounts can withdraw all tokens in the contract

As transfer function is only used in staking, only StakingManger should have access to this control. This can be done by creating OnlyStakingManager modifier.

Devs Response:
As TokenPool contract is deployed by stakingManger contract, and there is no way to whitelist users from stakingManger contract, so the only whitelisted account will be StakingManger contract’s Address. There is no way to withdraw staked tokens


As TokenPool smart contract is deployed from staking Manger so the funds are safe.

Low-risk issues

1. Reward Balance calculated incorrectly

File: StakingManagerv1.sol

function rewardBalance(address user) external view returns (uint) {
return (userStake.totalUnclaimed * networkDemand.calculateNetworkDemand()) / (userStake.lastDemandFactor);

When a user claims/unstake tokens, the reward fee is applied. But in the above function implementation no reward fee is adjusted. This will create a bad-user experience.

Adjust the reward fee while calculating reward balance.

2. Gas Cost Optimization While staking

File: RebaseEngine.sol
When a user stakes, the rebase function is called, which in turns calls the _rebase(address user) internal function which calculates the reward for the user. As the rewards are also calculated on claimRewards and Unstake. When calling the stake method, Only user’s stake metadata like lastStakingAccumulatedWeight and other params should be updated. Instead of calling the whole _rebase(address user), add another function which just updates the necessary parameters.

Devs Response:
With the previous formula, explained in High Risk Issue 1, it needs to be done in that way.

Update (Aug 4th, 2021):
RebaseEngine smart contract is being refactored.

3. Changing Owner should be in two steps

Files: Any file that is derived from Openzeppelin’s Ownable.sol.

Ownable files should implement two step ownership transfer. This eliminates the risk if the owner is mistakenly set to some address, which doesn’t have access to private keys.

Devs Response:
They are satisfied with the current approach and want to continue doing so.


The smart contracts provided by the client for audit purposes have been thoroughly analyzed in compliance with the global best practices till date w.r.t cybersecurity vulnerabilities and issues in smart contract code, the details of which are enclosed in this report. 

This report is not an endorsement or indictment of the project or team, and they do not in any way guarantee the security of the particular object in context. This report is not considered, and should not be interpreted as an influence, on the potential economics of the token, its sale or any other aspect of the project. 

Crypto assets/tokens are results of the emerging blockchain technology in the domain of decentralized finance and they carry with them high levels of technical risk and uncertainty. No report provides any warranty or representation to any third-Party in any respect, including regarding the bug-free nature of code, the business model or proprietors of any such business model, and the legal compliance of any such business. No third-party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. 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.

Smart contracts are deployed and executed on a blockchain. The platform, its programming language, and other software related to the smart contract can have its vulnerabilities that can lead to hacks. The scope of our review is limited to a review of the Solidity code and only the Solidity code we note as being within the scope of our review within this report. The Solidity language itself 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 Solidity that could present security risks.

This audit cannot be considered as a sufficient assessment regarding the utility and safety of the code, bug-free status or any other statements of the contract. While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only – we recommend proceeding with several independent audits and a public bug bounty program to ensure security of smart contracts. 

Read More

Powered By