Code4rena Audit
Last updated
Last updated
is an open organization consisting of security researchers, auditors, developers, and individuals with domain expertise in smart contracts.
A C4 audit contest is an event in which community participants, referred to as Wardens, review, audit, or analyze smart contract logic in exchange for a bounty provided by sponsoring projects.
During the audit contest outlined in this document, C4 conducted an analysis of the GoGoPool smart contract system written in Solidity. The audit contest took place between December 15—January 3 2023.
Following the C4 audit contest, 3 wardens (, RaymondFam, and ) reviewed the mitigations for all identified issues; the mitigation review report is appended below the audit contest report.
114 Wardens contributed reports to the GoGoPool contest:
0xLad
0xbepresent
0xc0ffEE
0xhunter
0xmint
Arbor-Finance (namaskar and bookland)
Atarpara
Bnke0x0
Breeje
HE1M
HollaDieWaldfee
IllIllI
Josiah
KmanOfficial
Lirios
Matin
NoamYakov
PaludoX0
RaymondFam
Rolezn
SEVEN
Saintcode_
SmartSek (0xDjango and hake)
V_B (Barichek and vlad_bochok)
WatchDogs
__141345__
ak1
ast3ros
brgltd
btk
caventa
cccz
chaduke
ck
clems4ever
cozzetti
cryptonue
cryptostellar5
datapunk
dic0de
eierina
enckrish
fs0c
gz627
hihen
imare
immeas
jadezti
kaliberpoziomka8552
kartkhira
koxuan
latt1ce
lukris02
mert_eren
minhtrng
mookimgo
nameruse
neumo
peanuts
peritoflores
rvierdiiev
sces60107
shark
simon135
sk8erboy
slowmoses
tonisives
unforgiven
wagmi
wallstreetvilkas
yixxas
yongskiws
The C4 analysis yielded an aggregated total of 28 unique vulnerabilities. Of these vulnerabilities, 6 received a risk rating in the category of HIGH severity and 22 received a risk rating in the category of MEDIUM severity.
Additionally, C4 analysis included 15 reports detailing issues with a risk rating of LOW severity or non-critical. There were also 12 reports recommending gas optimizations.
All of the issues presented here are linked back to their original finding.
C4 assesses the severity of disclosed vulnerabilities based on three primary risk categories: high, medium, and low/non-critical.
High-level considerations for vulnerabilities span the following key areas when conducting assessments:
Malicious Input Handling
Escalation of privileges
Arithmetic
Gas use
Node operators can manipulate the assigned high water to be higher than the actual.
The protocol rewards node operators according to the AVAXAssignedHighWater
that is the maximum amount assigned to the specific staker during the reward cycle.
In the function MinipoolManager.recordStakingStart()
, the AVAXAssignedHighWater
is updated as below.
In the line #373, if the current assigned AVAX is greater than the owner's AVAXAssignedHighWater
, it is increased by avaxLiquidStakerAmt
. But this is supposed to be updated to staking.getAVAXAssigned(owner)
rather than being increased by the amount.
Example: The node operator creates a minipool with 1000AVAX via createMinipool(nodeID, 2 weeks, delegationFee, 1000*1e18)
.
On creation, the assigned AVAX for the operator will be 1000AVAX.
If the Rialtor calls recordStakingStart()
, AVAXAssignedHighWater
will be updated to 1000AVAX. After the validation finishes, the operator creates another minipool with 1500AVAX this time. Then on recordStakingStart()
, AVAXAssignedHighWater
will be updated to 2500AVAX by increasing 1500AVAX because the current assigned AVAX is 1500AVAX which is higher than the current AVAXAssignedHighWater=1000AVAX
.
This is wrong because the actual highest assigned amount is 1500AVAX.
Note that AVAXAssignedHighWater
is reset only through the function calculateAndDistributeRewards
which can be called after RewardsCycleSeconds=28 days
.
Call staking.resetAVAXAssignedHighWater(owner)
instead of calling increaseAVAXAssignedHighWater()
.
Can we take some extra considerations here please? Discussed with @0xju1ie (GoGoPool) about this specific issue, and this was the answer:
(it is AVAXAssignedHighWater)
Their example in the proof of concept section is correct, and we have decided that this is not the ideal behavior and thus this is a bug. However, their recommended mitigation steps would create other issues, as highlighted by what @Franfran said. We intend to solve this issue differently than what they suggested.
The Warden has shown a flaw in the way
increaseAVAXAssignedHighWater
is used, which can be used to:
Inflate the amount of AVAX
With the goal of extracting more rewards than intended
I believe that the finding highlights both a way to extract further rewards as well as broken accounting.
For this reason I agree with High Severity.
ProtocolDAO implementation does not have a method to take out GGP. So it can't handle ggp unless it updates ProtocolDAO.
recordStakingEnd() will pass the rewards of this reward. "If the validator is failing at their duties, their GGP will be slashed and used to compensate the loss to our Liquid Stakers"
At this point slashGGP() will be executed and the GGP will be transferred to "ProtocolDAO"
staking.slashGGP():
But the current ProtocolDAO implementation does not have a method to take out GGP. So it can't handle ggp unless it updates ProtocolDAO
1.transfer GGP to ClaimProtocolDAO or 2.Similar to ClaimProtocolDAO, add spend method to retrieve GGP
The Warden has shown how, due to a lack of
sweep
the default contract for fee handling will be unable to retrieve tokens sent to it.While the issue definitely would have been discovered fairly early in Prod, the in-scope system makes it clear that the funds would have been sent to ProtocolDAO.sol and would have been lost indefinitely.
For this reason, I believe the finding to be of High Severity.
Acknowledged.
Thanks for the report. This is something we're aware of and are not going to fix at the moment.
The funds are transferred to the Vault and the ProtocolDAO contract is upgradeable. Therefore in the future we can upgrade the contract to spend the Vault GGP tokens to return funds to Liquid Stakers.
We expect slashing to be a rare event and might have some manual steps involved in the early days of the protocol to do this process if it occurs.
A node operator sends in the amount of duration they want to stake for. Behind the scenes Rialto will stake in 14 day cycles and then distribute rewards.
If a node operator doesn't have high enough availability and doesn't get any rewards, the protocol will slash their staked GGP
. For calculating the expected rewards that are missed however, the full duration is used:
This is unfair to the node operator because the expected rewards is from a 14 day cycle.
Also, If they were to be unavailable again, in a later cycle, they would get slashed for the full duration once again.
A node operator staking for a long time is getting slashed for an unfairly large amount if they aren't available during a 14 day period.
Team Comment:
This can only be taken advantage of when signing up for 2-4 week validation periods. Our protocol is incentivizing nodes to sign up for 3-12 month validation periods. If the team notices this mechanic being abused, Rialto may update its GGP reward calculation to disincentive this behavior.
This slashing amount calculation incentives the node operator to sign up for the shortest period possible and restake themselves to minimize possible losses.
Test in MinipoolManager.t.sol
:
Slashed amount for a 365 days
duration is 100 eth
(10%). However, where they to stake for the minimum time, 14 days
the slashed amount would be only ~3.8 eth
.
vs code, forge
Either hard code the duration to 14 days for calculating expected rewards or calculate the actual duration using startTime
and endTime
.
The Warden has shown an incorrect formula that uses the
duration
of the pool for slashing.The resulting loss can be up to 26 times the yield that should be made up for.
Because the:
Math is incorrect
Based on intended usage
Impact is more than an order of magnitude off
Principal is impacted (not just loss of yield)
I believe the most appropriate severity to be High.
A malicious actor can hijack a minipool of any node operator that finished the validation period or had an error.
The impacts:
Node operators staked funds will be lost (Loss of funds)
Hacker can hijack the minipool and retrieve rewards without hosting a node. (Theft of yield)
2.1 See scenario #2 comment for dependencies
Background description
The protocol created a state machine that validates transitions between minipool states. For this exploit it is important to understand three states:
Prelaunch
- This state is the initial state when a minipool is created. The created minipool will have a status of Prelaunch
until liquid stakers funds are matched and rialto
stakes 2000 AVAX into Avalanche.
Withdrawable
- This state is set when the 14 days validation period is over. In this state:
2.1. rialto
returned 1000 AVAX to the liquid stakers and handled reward distribution.
2.2. Node operators can withdraw their staked funds and rewards.
2.3. If the node operator signed up for a duration longer than 14 days rialto
will recreate the minipool and stake it for another 14 days.
Error
- This state is set when rialto
has an issue to stake the funds in Avalanche
In the above restrictions, we can see that the following transitions are allowed:
From Withdrawable
state to Prelaunch
state. This transition enables rialto
to call recreateMinipool
From Finished
state to Prelaunch
state. This transition allows a node operator to re-use their nodeID to stake again in the protocol.
From Error
state to Prelaunch
state. This transition allows a node operator to re-use their nodeID to stake again in the protocol after an error.
#2 is a needed capability, therefore createMinipool
allows overriding a minipool record if: nodeID
already exists and transition to Prelaunch
is permitted
THE BUG: createMinipool
can be called by Anyone with the nodeID
of any node operator.
If createMinipool
is called at the Withdrawable
state or Error
state:
The transaction will be allowed
The owner of the minipool will be switched to the caller.
Therefore, the minipool is hijacked and the node operator will not be able to withdraw their funds.
Exploit scenarios
As shown above, an attacker can always hijack the minipool and lock the node operators funds.
Cancel the minipool
Earn rewards on behalf of original NodeOp
Scenario #1 - Cancel the minipool
A hacker can hijack the minipool and immediately cancel the pool after a 14 day period is finished or an error state. Results:
Node operator will lose all his staked AVAX 1.1. This can be done by a malicious actor to ALL GoGoPool stakers to lose their funds in a period of 14 days.
Hacker will not lose anything and not gain anything.
Consider the following steps:
Hacker creates a node and creates a minipool node-1337
.
NodeOp registers a nodeID node-123
and finished the 14 days stake period. State is Withdrawable
.
Hacker calls createMinipool
with node-123
and deposits 1000 AVAX. Hacker is now owner of the minipool
Hacker calls cancelMinipool
of node-123
and receives his staked 1000 AVAX.
NodeOp cannot withdraw his staked AVAX as NodeOp is no longer the owner.
Hacker can withdraw staked AVAX for both node-1337
and node-123
The above step #1 is not necessary but allow the hacker to immediately cancel the minipool without waiting 5 days. (See other submitted bug #211: "Anti griefing mechanism can be bypassed")
Scenario #2 - Use node of node operator
In this scenario the NodeOp registers for a duration longer then 14 days. The hacker will hijack the minipool after 14 days and earn rewards on behalf of the node operators node for the rest of the duration. As the NodeOp registers for a longer period of time, it is likely he will not notice he is not the owner of the minipool and continue to use his node to validate Avalanche.
Results:
Node operator will lose all his staked AVAX
Hacker will gain rewards for staking without hosting a node
Important to note:
This scenario is only possible if recordStakingEnd
and recreateMinipool
are not called in the same transaction by rialto
.
During the research the sponsor has elaborated that they plan to perform the calls in the same transaction.
The sponsor requested to submit issues related to recordStakingEnd
and recreateMinipool
single/multi transactions for information and clarity anyway.
Consider the following steps:
Hacker creates a node and creates a minipool node-1337
.
NodeOp registers a nodeID node-123
for 28 days duration and finished the 14 days stake period. State is Withdrawable
.
Hacker calls createMinipool
with node-1234
and deposits 1000 AVAX. Hacker is now owner of minipool
Rialto calls recreateMinipool
to restake the minipool in Avalanche. (This time: the owner is the hacker, the hardware is NodeOp)
14 days have passed, hacker can withdraw the rewards and 1000 staked AVAX
NodeOps cannot withdraw staked AVAX.
Foundry POC
The POC will demonstrate scenario #1.
To run the POC, execute:
Expected output:
VS Code, Foundry
Fortunately, the fix is very simple.
The reason createMinipool
is called with an existing nodeID
is to re-use the nodeID
again with the protocol. GoGoPool can validate that the owner is the same address as the calling address. GoGoPool have already implemented a function that does this: onlyOwner(index)
.
The Warden has shown how, due to a lax check for State Transition, a Pool ID can be hijacked, causing the loss of the original deposit
Because the attack is contingent on a logic flaw and can cause a complete loss of Principal, I agree with High Severity.
Inflation of ggAVAX
share price can be done by depositing as soon as the vault is created.
Impact:
Early depositor will be able steal other depositors funds
Exchange rate is inflated. As a result depositors are not able to deposit small funds.
If ggAVAX
is not seeded as soon as it is created, a malicious depositor can deposit 1 WEI of AVAX to receive 1 share.
The depositor can donate WAVAX to the vault and call syncRewards
. This will start inflating the price.
When the attacker front-runs the creation of the vault, the attacker:
Calls depositAVAX
to receive 1 share
Transfers WAVAX
to ggAVAX
Calls syncRewards
to inflate exchange rate
The issue exists because the exchange rate is calculated as the ratio between the totalSupply
of shares and the totalAssets()
.
When the attacker transfers WAVAX
and calls syncRewards()
, the totalAssets()
increases gradually and therefore the exchange rate also increases.
Its important to note that while it is true that cycle length is 14 days, in practice time between cycles can very between 0-14 days. This is because syncRewards validates that the next reward cycle is evenly divided by the length (14 days).
Therefore:
The closer the call to syncRewards
is to the next evenly divisible value of rewardsCycleLength
, the closer the next rewardsCycleEnd
will be.
The closer the delta between syncRewards
calls is, the higher revenue the attacker will get.
Edge case example:
syncRewards
is called with the timestamp 1672876799, syncRewards
will be able to be called again 1 second later. (1672876799 + 14 days) / 14 days) * 14 days) = 1672876800
Additionally, the price inflation causes a revert for users who want to deposit less then the donation (WAVAX transfer) amount, due to precision rounding when depositing.
Foundry POC
The POC will demonstrate the below scenario:
Bob front-runs the vault creation.
Bob deposits 1 WEI of AVAX to the vault.
Bob transfers 1000 WAVAX to the vault.
Bob calls syncRewards
when block.timestamp = 1672876799
.
Bob waits 1 second.
Bob calls syncRewards
again. Share price fully inflated.
Alice deposits 2000 AVAX to vault.
Bob withdraws 1500 AVAX (steals 500 AVAX from Alice).
Alice share earns her 1500 AVAX (although she deposited 2000).
Additionally, the POC will show that depositors trying to deposit less then the donation amount will revert.
To run the POC, execute:
Expected output:
VS Code, Foundry
When creating the vault add initial funds in order to make it harder to inflate the price. Best practice would add initial funds as part of the initialization of the contract (to prevent front-running).
The Warden has shown how, by performing a small deposit, followed by a transfer, shares can be rebased, causing a grief in the best case, and complete fund loss in the worst case for every subsequent depositor.
While the finding is fairly known, it's impact should not be understated, and because of this I agree with High Severity.
I recommend watching this presentation by Riley Holterhus which shows possible mitigations for the attack: https://youtu.be/_pO2jDgL0XE?t=601
If the avaxTotalRewardAmt
has the value zero, the MinipoolManager
will slash the node operator's GGP.
The issue is that the amount to slash can be greater than the GGP balance the node operator has staked.
This will cause the call to MinipoolManager.recordStakingEnd
to revert because an underflow is detected.
This means a node operator can create a minipool that cannot be slashed.
A node operator must provide at least 10% of avaxAssigned
as collateral by staking GGP.
It is assumed that a node operator earns AVAX at a rate of 10% per year.
So if a Minipool is created with a duration of > 365 days
, the 10% collateral is not sufficient to pay the expected rewards.
This causes the function call to revert.
Another cause of the revert can be that the GGP price in AVAX changes. Specifically if the GGP price falls, there needs to be slashed more GGP.
Therefore if the GGP price drops enough it can cause the call to slash to revert.
I think it is important to say that with any collateralization ratio this can happen. The price of GGP must just drop enough or one must use a long enough duration.
The exact impact of this also depends on how the Rialto multisig handles failed calls to MinipoolManager.recordStakingEnd
.
This allows the node operator to withdraw his GGP stake.
So in summary a node operator can create a Minipool that cannot be slashed and probably remove his GGP stake when it should have been slashed.
You can add the following foundry test to MinipoolManager.t.sol
:
See that it runs successfully with duration = 365 days
and fails with duration = 366 days
.
The similar issue occurs when the GGP price drops. I chose to implement the test with duration
as the cause for the underflow because your tests use a fixed AVAX/GGP price.
VSCode, Foundry
You should check if the amount to be slashed is greater than the node operator's GGP balance. If this is the case, the amount to be slashed should be set to the node operator's GGP balance.
I believe this check can be implemented within the MinipoolManager.slash
function without breaking any of the existing accounting logic.
This is a combination of two other issues from other wardens
Slash amount shouldn't depend on duration: https://github.com/code-423n4/2022-12-gogopool-findings/issues/694
GGP Slash shouldn't revert: https://github.com/code-423n4/2022-12-gogopool-findings/issues/743
This finding combines 2 issues:
If price drops Slash can revert -> Medium
Attacker can set Duration to too high to cause a revert -> High
Am going to dedupe this and the rest, but ultimately I think these are different findings, that should have been filed separately.
The Warden has shown how a malicious staker could bypass slashing, by inputting a duration that is beyond the intended amount.
Other reports have shown how to sidestep the slash or reduce it, however, this report shows how the bypass can be enacted maliciously to break the protocol functionality, to the attacker's potential gain.
Because slashing is sidestepped in it's entirety, I believe this finding to be of High Severity.
When the contract is paused , allowing startRewardsCycle would inflate the token value which might not be safe.
Rewards should not be claimed by anyone when all other operations are paused.
I saw that the witdrawGGP
has this WhenNotPaused
modifier.
Inflate should not consider the paused duration.
Let's say, when the contract is paused for the duration of 2 months, then the dao, protocol, and node validator would enjoy the rewards. This is not good for a healthy protocol.
startRewardsCycle does not have the WhenNotPaused modifier.
We suggest to use WhenNotPaused
modifier.
The Warden has shown an inconsistency as to how Pausing is used.
While other aspects of the code are pausable and under the control of the
guardian
, a call tostartRewardsCycle
can be performed by anyone, and in the case of a system-wide pause may create unfair gains or lost rewards.For this reason I agree with Medium Severity.
Function ProtocolDAO.upgradeExistingContract
handles contract upgrading. However, there are multiple implicaitons of the coding logic in the function, which render the contract upgrading impractical.
Implication 1:
The above function upgradeExistingContract
registers the upgraded contract first, then unregisters the existing contract. This leads to the requirement that the upgraded contract name must be different from the existing contract name. Otherwise the updated contract address returned by Storage.getAddress(keccak256(abi.encodePacked("contract.address", contractName)))
will be address(0)
(please refer to the below POC Testcase 1). This is because if the upgraded contract uses the original name (i.e. the contract name is not changed), function call unregisterContract(existingAddr)
in the upgradeExistingContract
will override the registered contract address in Storage
to address(0) due to the use of the same contract name.
Since using the same name after upgrading will run into trouble with current coding logic, a safeguard should be in place to make sure two names are really different. For example, put this statement in the upgradeExistingContract
function:
require(newName != existingName, "Name not changed");
, where existingName
can be obtained using:
string memory existingName = store.getString(keccak256(abi.encodePacked("contract.name", existingAddr)));
.
Implication 2:
If we really want a different name for an upgraded contract, we then get into more serious troubles: We have to upgrade other contracts that reference the upgraded contract since contract names are referenced mostly hardcoded (for security considerations). This may lead to a very complicated issue because contracts are cross-referenced.
For example, contract ClaimNodeOp
references contracts RewardsPool
, ProtocolDAO
and Staking
. At the same time, contract ClaimNodeOp
is referenced by contracts RewardsPool
and Staking
. This means that:
If contract ClaimNodeOp
was upgraded, which means the contract name ClaimNodeOp
was changed;
This requires contracts RewardsPool
and Staking
to be upgraded (with new names) in order to correctly reference to newly named ClaimNodeOp
contract;
This further requires those contracts that reference RewardsPool
or Staking
to be upgraded in order to correctly reference them;
and this further requires those contracts that reference the above upgraded contracts to be upgraded ...
This may lead to complicated code management issue and expose new vulnerabilites due to possible incomplete code adaptation.
This may render the contracts upgrading impractical.
I rate this issue as high severity due to the fact that:
Contract upgradability is one of the main features of the whole system design (all other contracts are designed upgradable except for TokenGGP
, Storage
and Vault
). However, the current upgradeExistingContract
function's coding logic requires the upgraded contract must change its name (refer to the below Testcase 1). This inturn requires to upgrade all relevant cross-referenced contracts (refer to the below Testcase 2). Thus leading to a quite serous code management issue while upgrading contracts, and renders upgrading contracts impractical.
Testcase 1:
This testcase demonstrates that current coding logic of upgrading contracts requires: the upgraded contract must change its name. Otherwise contract upgrading will run into issue. Put the below test case in file ProtocolDAO.t.sol
. The test case demonstrates that ProtocolDAO.upgradeExistingContract
does not function properly if the upgraded contract does not change the name. That is: the upgraded contract address returned by Storage.getAddress(keccak256(abi.encodePacked("contract.address", contractName)))
will be address(0)
if its name unchanged.
Testcase 2:
This testcase demonstrates that current coding logic of upgrading contracts requires: in order to upgrade a single contract, all cross-referenced contracts have to be upgraded and change their names. Otherwise, other contracts will run into issues.
If the upgraded contract does change its name, contract upgrading will succeed. However, other contracts' functions that reference the upgraded contract will fail due to referencing hardcoded contract name.
The below testcase upgrades contract ClaimNodeOp
to ClaimNodeOpV2
. Then, contract Staking
calls increaseGGPRewards
which references hardcoded contract name ClaimNodeOp
in its modifier. The call is failed.
Test steps:
Copy contract file ClaimNodeOp.sol
to ClaimNodeOpV2.sol
, and rename the contract name from ClaimNodeOp
to ClaimNodeOpV2
in file ClaimNodeOpV2.sol
;
Put the below test file UpgradeContractIssue.t.sol
under folder test/unit/
;
Run the test.
Note: In order to test actual function call after upgrading contract, this testcase upgrades a real contract ClaimNodeOp
. This is different from the above Testcase 1 which uses a random address to simulate a contract.
Upgrading contract does not have to change contranct names especially in such a complicated system wherein contracts are cross-referenced in a hardcoded way. I would suggest not to change contract names when upgrading contracts.
In function upgradeExistingContract
definition, swap fucnction call sequence between registerContract()
and unregisterContract()
so that contract names can keep unchanged after upgrading. That is, the modified function would be:
POC of Mitigation:
After the above recommended mitigation, the below Testcase verifies that after upgrading contracts, other contract's functions, which reference the hardcoded contract name, can still opetate correctly.
Make the above recommended mitigation in function ProtocolDAO.upgradeExistingContract
;
Put the below test file UpgradeContractImproved.t.sol
under folder test/unit/
;
Run the test.
Note: Since we don't change the upgraded contract name, for testing purpose, we just need to create a new contract instance (so that the contract instance address is changed) to simulate the contract upgrading.
Not sure if this is considered a high since there isn't a direct loss of funds?
Medium: Assets not at direct risk, but the function of the protocol or its availability could be impacted, or leak value with a hypothetical attack path with stated assumptions, but external requirements.
In spite of the lack of risk for Principal, a core functionality of the protocol is impaired.
This has to be countered versus the requirement of the names being the same, which intuitively seems to be the intended use case, as changing the name would also break balances / other integrations such as the modifier
onlySpecificRegisteredContract
.The other side of the argument is that the mistake is still fixable by the same actor within a reasonable time frame.
I believe the finding is meaningful and well written, but ultimately the damage can be undone with a follow-up call to
registerContract
.Because of this am downgrading to Medium Severity.
If the Multisig accidentally/intentionally calls recordStakingError()
then finishFailedMinipoolByMultisig()
the NodeOp funds may be trapped in the protocol.
The finishFailedMinipoolByMultisig()
has the next comment: Multisig can move a minipool from the error state to the finished state after a human review of the error but the NodeOp should be able to withdraw his funds after a finished minipool.
I created a test for this situation in MinipoolManager.t.sol
. At the end you can observe that the withdrawMinipoolFunds()
reverts with InvalidStateTransition
error:
NodeOp creates the minipool
Rialto calls claimAndInitiateStaking
Something goes wrong and Rialto calls recordStakingError()
Rialto accidentally/intentionally calls finishFailedMinipoolByMultisig() in order to finish the NodeOp's minipool
The NodeOp can not withdraw his funds. The withdraw function reverts with InvalidStateTransition() error
Foundry/Vscode
I think this should be the primary for the
finishFailedMinipoolByMultisig()
problem.Medium feels like a more appropriate severity. This issue depends on rialto multisig improperly functioning but we do intend to fix the finishFailedMinipoolByMultisig method to not lock users out of their funds.
The Warden has shown a potential issues with the FSM of the system, per the Audit Scope, the transition should not happen on the deployed system, however, the Warden has shown an issue with the state transition check and has detailed the consequences of it.
For this reason, I agree with Medium Severity.
For every created minipool a multisig address is set to continue validator interactions.
Every minipool multisig address get assigned by calling requireNextActiveMultisig
.
This function always return the first enabled multisig address.
In case the specific address is disabled all created minipools will be stuck with this address which increase the probability of also funds being stuck.
Probability of funds being stuck increases if requireNextActiveMultisig
always return the same address.
Something like this :
Without a mechanism for funds to become stuck, I don't think this warrants a medium severity.
I do agree with the principle that if we have multiple multisigs, some system to distribute minipools between them seems reasonable.
While the finding will not be awarded as Admin Privilege, I believe that ultimately the Warden has shown an incorrect implementation of the function
requireNextActiveMultisig
which would ideally either offer:
Round Robin
Provable Random Selection
For those reasons I think the finding is still notable, in that the function doesn't work as intended, and believe it should be judged Medium Severity.
I will be consulting with an additional Judge to ensure that the logic above is acceptable given the custom scope for this contest.
Acknowledged.
We're not going to fix this in the first iteration of our protocol, we're expecting to only have one active multisig. We will definitely implement some system to distribute minipools between multisigs when we have more.
The whenNotPaused
modifier is used to pause minipool creation and staking/withdrawing GGP. However, there are several cases this modifier could be bypassed, which breaks the intended admin control function and special mode.
stake()
In paused mode, no more stakeGGP()
is allowed,
However, restakeGGP()
is still available, which potentially violate the purpose of pause mode.
withdraw()
In paused mode, no more withdrawGGP()
is allowed,
However, claimAndRestake()
is still available, which can withdraw from the vault.
The function spend()
can also ignore the pause mode to withdraw from the vault. But this is a guardian function. It could be intended behavior.
add the whenNotPaused
modifier to restakeGGP()
and claimAndRestake()
maybe also for guardian function spend()
.
The warden has shown an inconsistency within similar functions regarding how they behave during a pause. Because the finding pertains to an inconsistent functionality, without a loss of principal, I agree with Medium Severity.
When doing inflation, function getInflationAmt()
calculated number of intervals elapsed by dividing the duration with interval length.
As we can noticed that, this calculation is rounding down, it means if block.timestamp - startTime = 1.99 intervals
, it only account for 1 interval
.
However, when updating start time after inflating, it still update to current timestamp while it should only increased by intervalLength * intervalsElapsed
instead.
Since default value of inflation interval = 1 days and reward cycle length = 14 days, so the impact is reduced. However, these configs can be changed in the future.
Consider the scenario:
Assume last inflation time is InflationIntervalStartTime = 100
. InflationIntervalSeconds = 50
.
At timestamp = 199
, function getInflationAmt()
will calculate
And then in inflate()
function, InflationIntervalStartTime
is still updated to current timestamp, so InflationIntervalStartTime = 199
.
If this sequence of actions are repeatedly used, we can easily see
While at timestamp = 595
, inflated times should be (595 - 100) / 50 = 9
instead.
Consider only increasing InflationIntervalStartTime
by the amount of intervals time interval length.
I have considered a Higher Severity, due to logical flaws.
However, I believe that the finding
Relies on the Condition of being called less than intended
Causes an incorrect amount of emissions (logically close to loss of Yield)
For those reasons, I believe Medium Severity to be the most appropriate
Acknowledged, not fixing in this first version of the protocol.
We can and will have rialto call startRewardsCycle if needed, and think it's unlikely to become delayed.
A malicious node operator may create a minipool that cannot be cancelled.
The following PoC demonstrates how calls to cancelMinipoolByMultisig
can be blocked:
The warden has shown how the checked return value from call can be used as a grief to prevent canceling of a minipool.
The finding can have different severities based on the context, in this case, the cancelling can be denied, however, other state transitions are still possible.
For this reason (functionality is denied), I agree with Medium Severity.
Acknowledged.
We'll make a note of this in our documentation, but not fixing immediately.
After recreation, minipools will receive more AVAX than the sum of their owners' current stake and the rewards that they generated.
As a result, the avaxLiquidStakerAmt
set in the recreateMinipool
function will always be bigger than the actual amount since it equals to the compounded node operator amount, which includes node operator rewards.
As a result, the amount of AVAX borrowed from liquid stakers by the minipool will be increased by the minipool node commission fee, the increased amount will be sent to the validator, and it will be required to end the validation period.
The following PoC demonstrates the wrong calculation:
When compounding rewards in the recreateMinipool
function, consider using an average reward so that node operator's and liquid stakers' deposits are increased equally and the entire reward amount is used:
Also, consider sending equal amounts of rewards to the vault and the ggAVAX token in the recordStakingEnd
function.
I need to do a bit more digging on my end, but this might be working as designed. Will come back to it.
I think this is valid - don't think it is high though as there isn't really a loss of funds.
Talked to the rest of the team and this is not valid - it is working as designed. We are matching 1:1 with what the node operators are earning/staking.
Will flag to triage but I agree with the sponsor.
The math is as follows: -> Principal Deposited -> Earned Rewards (both for Operator and Stakers) -> Re-assing all -> Assigned amount has grown "too much" but in reality it's the correct value -> When withdrawing, the operator only get's their portion of AVAX, meaning that the assigned as grown more, but they don't get an anomalous amount of rewards
@Alex the Entreprenerd & @0xju1ie - Could you please expand on why it's okay? There are multiple issues arising from this:
This function may return false while there is the correct amount of AVAX as
avaxLiquidStakerAmt
(in extreme cases)This is going to pull too much funds from the
Manager
: https://github.com/code-423n4/2022-12-gogopool/blob/1c30b320b7105e57c92232408bc795b6d2dfa208/contracts/contract/MinipoolManager.sol#L329This will fake the "high water" value: https://github.com/code-423n4/2022-12-gogopool/blob/1c30b320b7105e57c92232408bc795b6d2dfa208/contracts/contract/MinipoolManager.sol#L371
As there is a strict equality and that not all rewards may be sent by Rialto (only those really yielded by the validation), the staking end may never be triggered: https://github.com/code-423n4/2022-12-gogopool/blob/1c30b320b7105e57c92232408bc795b6d2dfa208/contracts/contract/MinipoolManager.sol#L399-L403, same for the
recordStakingError
@Franfran - I can chime in here.
When recreating a minipool, we intend to allow Node Operators to compound their staking rewards for the next cycle.
Say that a minipool with 2000 AVAX was running. After one cycle the minipool was rewarded 20 AVAX. 15 AVAX goes to Node Operators and 5 AVAX to Liquid Stakers (in this example).
When we recreate the minipool we want to allow the Node Operator to run a minipool with 1015 AVAX. Right now we require a 1:1 match of Node Operator to Liquid Staker funds, so that means we'll withdraw 1015 AVAX from the Liquid Staking pool. That's 10 AVAX more than we deposited from this one minipool. We are relying on there being 10 free floating AVAX in the Liquid Staking fund to recreate this minipool.
The Warden says "The function assumes that a node operator and liquid stakers earned an equal reward amount". We're were not assuming that, but we are assuming that there will be some free AVAX in the Liquid Staker pool to withdraw more than we've just deposited from rewards.
All that being said, we do not like this assumption and will change to use
avaxLiquidStakerAmt
instead ofavaxNodeOpAmt
for both. Ensuring that we will always have enough Liquid Staker AVAX to recreate the minipool and we will maintain the one-to-one match.
The warden has shown a potential risk when it comes to accounting, fees and the requirement on liquid funds, more specifically the accounting in storage will use the values earned by the validator, however when recreating new funds will need to be pulled.
The discrepancy may cause issues.
I believe this report has shown a potential risk, but I also think the Warden should have spent more time explaining it in depth vs stopping at the potential invariant being broken.
I'm flagging this out of caution after considering scrapping it / inviting the Wardens to follow up in mitigation review.
@emersoncloud -
The Warden says "The function assumes that a node operator and liquid stakers earned an equal reward amount". We're were not assuming that
As can be seen from the linked code snippet (the comments, specifically):
The assumption is that the 1:1 funds ratio is preserved after rewards have been accounted. This can only be true when the reward amounts are equal, which is violated due to the fees applied to
avaxLiquidStakerRewardAmt
.@Alex the Entreprenerd - I'm sorry for not providing more details on how this can affect the entire system. Yes, my assumption was that extra staker funds would be required to recreate a pool, and there might be not enough funds staked (and deeper accounting may be affected, as pointed out by @Franfran), while the earned rewards + the previous staked amounts would be enough to recreate a pool.
Thus, the mitigation that uses
avaxLiquidStakerAmt
for both amounts looks good to me, since, out of the two amounts, the smaller one will always be picked, which won't require pulling extra funds from stakers. The difference between this mitigation and the mitigation suggested in the report, is that the latter uses the full reward amount in a recreated pool, while usingavaxLiquidStakerAmt
for both amounts leaves a portion of the reward idle.I also agree with the medium severity, the High Risk label was probably a misclick.
This issue is related to state transition of Minipools. According to the implementation, the possible states and transitions are as below.
The Rialto may call recreateMinipool
when the minipool is in states of Withdrawable, Finished, Error, Canceled
.
The problem is that these four states are not the same in the sense of holding the node operator's AVAX.
If the state flow has followed Prelaunch->Launched->Staking->Error
, all the AVAX are still in the vault.
If the state flow has followed Prelaunch->Launched->Staking->Error->Finished
(last transition by withdrawMinipoolFunds
), all the AVAX are sent back to the node operator.
So if the Rialto calls recreateMinipool
for the second case, there are no AVAX deposited from the node operator at that point but there can be AVAX from other mini pools in the state of Prelaunch.
Because there are AVAX in the vault (and these are not managed per staker base), recreatePool
results in a new mini pool in Prelaunch
state and it is further possible to go through the normal flow Prelaunch->Launched->Staking->Withdrawable->Finished
.
And the other minipool that was waiting for launch will not be able to launch because the vault is lack of AVAX.
Below is a test case written to show an example.
Manual Review, Foundry
Make sure to keep the node operator's deposit status the same for all states that can lead to the same state.
For example, for all states that can transition to Prelaunch, make sure to send the AVAX back to the user and get them back on the call recreateMiniPool()
.
The Warden has shown an issue with the FSM, Pools are allowed to perform the following transition >
Prelaunch->Launched->Staking->Error->Finished->Prelaunch
which allows to spin up the pool without funds.This could only happen if Rialto performs a mistake, so the finding is limited to highlighting the issue with the State Transition.
For this reason, I believe Medium to be the most appropriate severity.
The value of RewardsStartTime
shows when node runner started the minipool and validation rewards are generated by node runner. it is used to see if node runners are eligible for ggp rewards or not and node runners should run their node for minimum amount of time during the rewarding cycle to be eligible for rewards. but right now node runner can create a mimipool and cancel it (after waiting time) and even so the minipool generated no rewards and cancelled the value of RewardsStartTime
won't get reset for node runner and in the end of the cycle node runner would be eligible for rewards (node runner can create another minipool near the end of cycle). so this issue would cause wrong reward distribution between node runners and code doesn't correctly track RewardsStartTime
for node runners and malicious node runners can use this issue and receive rewards without running validation nodes for the minimum amount of required time.
This is cancelMinipool()
and _cancelMinipoolAndReturnFunds()
code:
As you can see there is no check that user's minipool count is zero and if it is to reset the value of RewardsStartTime
for user so if a user creates a minipool in the start of the cycle and then cancel it after 5 days and wait for end of the cycle and start another minipool and increase his staking AVAX he would be eligible for ggp rewards (ClaimNodeOp.isEligible()
would return true
for that user even so the user didn't run node for the required amount of time in the cycle). these are the steps to exploit this:
node runner would create a minipool near start time of the ggp rewarding cycle and the value of RewardsStartTime
would set for node runner.
after 5 days that node runner's minipool has not been launched by multisig (for any reason) node runner would call cancelMinipool()
and code would cancel his minipool but won't reset RewardsStartTime
for node runner.
after 20 days and near end of the gpp reward cycle node runner would create another minipool and start running node.
in the end even so node runner only start running node and earning reward near end of the reward cycle but code would count node runner as eligible for rewards because RewardsStartTime
for node runner shows wrong value.
This bug would cause rewards to be distributed wrongly between node runners and malicious node runners can bypass required time for running nodes during reward cycle to be eligible for rewards.
VIM
Set the value of RewardsStartTime
based on successfully finished minipools or when minipool is launched and user can't cancel minipool.
The Warden has shown how, due to
cancelMinipool
not resettingrewardsStartTime
a pool owner could receive rewards for time in which they did not have any activePool.Because this is contingent on the Multisig not cancelling the pool and because it would limit the attack to rewards, I believe Medium Severity to be the most appropriate.
When more than 10 mulitsig, it is impossible to modify or delete the old ones, making it impossible to create new valid ones.
MultisigManager limits the number of Multisig to 10, which cannot be deleted or replaced after they have been disabled. This will have a problem, if the subsequent use of 10, all 10 for some reason, be disabled. Then it is impossible to add new ones and replace the old ones, so you have to continue using the old Multisig at risk.
Add replace old mulitsig method
I'd argue Low since its unlikely.
I disagree @0xju1ie. I think it's an oversight not to have a way to delete old multisigs with the limit in place rather than a quality assurance issue.
Which was: "Count only the validated/enabled multisigs in order to control the limit."
The Warden has shown how, due to a logic flaw, the system can only ever add up to 10 multi sigs, even after disabling all, no more multi sigs could be added.
Because this shows how an external condition can break the functionality of the MultisigManager, I agree with Medium Severity.
Acknowledged.
Not fixing right now, we don't foresee having many multisigs at launch, and will upgrade as necessary to support more.
When canceling a minipool that was canceled before, it may skip MinipoolCancelMoratoriumSeconds
checking and allow the user to cancel the minipool immediately.
A user may create a minipool.
and after 5 days, the user cancels the minipool
Then, the user recreates the minipool again by calling the same createMinipool function. Then, the user cancels the minipool immediately. The user should not be allowed to cancel the minpool immediately and he should wait for 5 more days.
Added a test unit to MinipoolManager.t.sol
Manual and added a test unit
Change the createMinipool function. Always setRewardsStartTime everytime the minipool is recreated.
This solution would mess up other aspects of the protocol. In cancel minipool, we should really just check the minipoolStartTime against the cancelMoratoriumSeconds.
The warden has shown a logic flaw in the Finite State Machine, as shown in the POC, cancelling a second miniPool can be done before
MinipoolCancelMoratoriumSeconds
.Because the exploit doesn't demonstrate a reliable way to extra value or funds from the protocol, I agree with Medium Severity.
When creating a minipool the node operator is required to put up a collateral in GGP
, the protocol token. The amount of GGP
collateral needed is currently calculated to be 10% of the AVAX
staked. This is calculated using the price of GGP - AVAX
.
If the node operator doesn't have high enough availability and doesn't get any rewards the protocol will slash their GGP
collateral to reward liquid stakers. This is also calculated using the price of GGP - AVAX
:
This is then subtracted from their staked amount:
The issue is that the current staked amount is never checked so the subUint
can fail due to underflow if the price has changed since the minipool was created/recreated.
If a node operator doesn't have enough collateral, possibly caused by price changes in GGP
during slashing they evade slashing all together.
It's even possible for the node operator to foresee this and manipulate the price of GGP
just prior to the period ending if they know that they are going to be slashed.
PoC test in MinipoolManager.t.sol
:
The only thing the protocol can do now is to call recordStakingError
for the minipool, since no other state changes are allowed. This will return the staked funds but it will not slash the GGP
amount for the node operator. Hence the node operator has evaded the slashing.
vs code, forge
If the amount to be slashed is greater than what the node operator has staked, slash all their stake.
The Warden has shown a risk to the protocol, in cases in which the price of GPP drops too low, slashing could not be performed.
In contrast to other reports, this is a finding that shows an issue with the system and it's consequences, more so than an economic attack.
For this reason I believe Medium to be the most appropriate severity.
When a node operator creates a minipool they pass which duration they want to stake for. There is no validation for this field so they can pass any field:
Later when staking is done. if the node op was slashed, duration
is used to calculate the slashing amount:
The node operator cannot pass in 0
because that reverts due to zero transfer check in Vault. However the node operator can pass in 1
to guarantee the lowest slash amount possible.
Rialto might fail this, but there is little information about how Rialto uses the duration
passed. According to this comment they might default to 14 days
in which this finding is valid:
JohnnyGault — 12/30/2022 3:22 PM
To clarify duration for everyone -- a nodeOp can choose a duration they want, from 14 days to 365 days. But behind the scenes, Rialto will only create a validator for 14 days. ...
The node operator can send in a very low duration
to get minimize slashing amounts. It depends on the implementation in Rialto, which we cannot see. Hence submitting this.
PoC test in MinipoolManager.t.sol
:
vs code, forge
Regardless if Rialto will fail this or not, I recommend that the duration
passed is validated to be within 14 days
and 365 days
.
The Warden has shown how, due to a lack of check, a duration below 14 days can be set, this could also be used to reduce the slash penalty.
I believe that in reality, such a pool will be closed via
recordStakingError
, however, this enables a grief that could impact the Protocol in a non-trivial manner.For this reason, I believe the most appropriate severity to be Medium.
Function syncRewards()
distributes rewards to TokenggAVAX holders, it linearly distribute cycle's rewards from block.timestamp
to the cycle end time which is next multiple of the rewardsCycleLength
(the end time of the cycle is defined and the real duration of the cycle changes). when a cycle ends syncRewards()
should be called so the next cycle starts but if syncRewards()
doesn't get called fast, then users depositing or withdrawing funds before call to syncRewards()
would lose their rewards and those rewards would go to users who deposited funds after syncRewards()
call. contract should try to start the next cycle whenever deposit or withdraw happens to make sure rewards are distributed fairly between users.
This is syncRewards()
code:
As you can see whenever this function is called it starts the new cycle and sets the end of the cycle to the next multiple of the rewardsCycleLength
and it release the rewards linearly between current timestamp and cycle end time. So if syncRewards()
get called near to multiple of the rewardsCycleLength
then rewards would be distributed with higher speed in less time. The problem is that users depositing funds before call syncRewards()
won't receive new cycles rewards and early depositing won't get considered in reward distribution if deposits happen before syncRewards()
call and if a user withdraws his funds before the syncRewards()
call then he receives no rewards.
Imagine this scenario:
rewardsCycleLength
is 10 days and the rewards for the next cycle is 100
AVAX.
the last cycle has been ended and user1 has 10000
AVAX deposited and has 50% of the pool shares.
syncRewards()
don't get called for 8 days.
users1 withdraws his funds receive 10000
AVAX even so he deposits for 8 days in the current cycle.
users2 deposit 1000
AVAX and get 10% of pool shares and the user2 would call syncRewards()
and contract would start distributing 100
avax as reward.
after 2 days cycle would finish and user2 would receive 100 * 10% = 10
AVAX as rewards for his 1000
AVAX deposit for 2 days but user1 had 10000
AVAX for 8 days and would receive 0 rewards.
So rewards won't distribute fairly between depositors across the time and any user interacting with contract before the syncRewards()
call can lose his rewards. Contract won't consider deposit amounts and duration before syncRewards()
call and it won't make sure that syncRewards()
logic would be executed as early as possible with deposit or withdraw calls when a cycle ends.
VIM
One way to solve this is to call syncRewards()
logic in each deposit or withdraw and make sure that cycles start as early as possible (the revert "SyncError()" in the syncRewards()
should be removed for this).
I think that medium severity is more appropriate. User funds aren't drained or lost, but liquid staking rewards may be unfairly calculated.
Good find. I think there is something we could do to either incentivize the
syncRewards
call or call it on deposit and withdraw.But I disagree with the concept that the user who staked for 8 days is entitled to rewards for staking. Rewards depend on properly running minipools. Reward amounts can fluctuate depending on the utilization of liquid staking funds by minipools.
After some more discussion, this is working as designed. And Rialto will call
syncRewards
at the start of each reward cycle, so the possible loss to the user who withdraws beforesyncRewards
was supposed to be called is mitigated.
The Warden has shown a potential risk for end-users that withdraw before
syncRewards
is called.Because the finding pertains to a loss of yield, I believe the finding to be of Medium Severity.
While Rialto may call this as a perfect actor, we cannot guarantee that a end user could forfeit some amount of yield, due to external conditions.
I believe this finding to potentially be a nofix, as long as all participants are aware of the mechanic.
Acknowledged.
Not fixing but will add a note in our docs.
Functions maxWithdraw()
and maxRedeem()
returns max amount of assets or shares owner would be able to withdraw taking into account liquidity in the TokenggAVAX contract, but logics don't consider that when user withdraws the withdrawal amounts subtracted from totalReleasedAssets
(in beforeWithdraw()
function) so the maximum amounts that can user withdraws should always be lower than totalReleasedAssets
(which shows all the deposits and withdraws) but because functions maxWithdraw()
and maxRedeem()
uses totalAssets()
to calculate available AVAX which includes deposits and current cycle rewards so those functions would return wrong value (whenever the return value is bigger than totalReleaseAssets
then it would be wrong).
This is beforeWithdraw()
code:
This is beforeWithdraw()
code which is called whenever users withdraws their funds and as you can see the amount of withdrawal assets subtracted from totalReleaseAssets
so withdrawal amounts can never be bigger than totalReleaseAssets
. This is maxWithdraw()
code:
As you can see to calculate available AVAX in the contract address code uses totalAssets() - stakingTotalAssets
and totalAssets()
shows deposits + current cycle rewards so totalAssets()
is bigger than totalReleaseAssets
and the value of the totalAssets() - stakingTotalAssets
can be bigger than totalReleaseAssets
and if code returns avail
as answer then the return value would be wrong.
Imagine this scenario:
totalReleaseAssets
is 10000
AVAX.
stakingTotalAssets
is 1000
AVAX.
current cycle rewards is 4000
AVAX and block.timestamp
is currently in the middle of the cycle so current rewards is 2000
AVAX.
totalAssets()
is totalReleaseAssets + current rewards = 10000 + 2000 = 12000
.
contract balance is 10000 + 4000 - 1000 = 13000
AVAX.
user1 has 90% contract shares and calls maxWithdraw()
and code would calculate user assets as 10800
AVAX and available AVAX in contract as totalAssets() - stakingTotalAssets = 12000 - 1000 = 11000
and code would return 10800
as answer.
now if user1 withdraws 10800
AVAX code would revert in the function beforeWithdraw()
because code would try to execute totalReleaseAssets = totalReleaseAssets - amount = 10000 - 10800
and it would revert because of the underflow. so in reality user1 couldn't withdraw 10800
AVAX which was the return value of the maxWithdraw()
for user1.
The root cause of the bug is that the withdrawal amount is subtracted from totalReleaseAssets
and so max withdrawal can never be totalReleaseAssets
and function maxWithdraw()
should never return value bigger than totalReleaseAssets
. (the bug in function maxRedeem()
is similar)
This bug would cause other contract or front end calls to fail, for example if the logic is something like this:
According the function definitions this code should work bug because of the the issue there are situations that this would revert and other contracts and UI can't work properly with the protocol.
VIM
Consider totalReleaseAssets
in max withdrawal amount too.
The Warden has shown an inconsistency between the view functions and the actual behaviour of
TokenggAVAX
. This breaks ERC4626, as well as offering subpar experience for end-users.For this reason I agree with Medium Severity.
Acknowledged.
I've added some tests to explore this more, but it's a known issue with how we've implemented the streaming of rewards in our 4626. Some more context here https://github.com/fei-protocol/ERC4626/issues/24.
It's most prevalent with low liquidity in ggAVAX.
We're not going to fix in the first iteration of protocol.
When the Rialto calls recordStakingError()
function the AssignedHighWater
is not reseted. So the malicious NodeOp (staker) can create pools which will have an error in the registration and get rewards from the protocol.
I created a test in ClaimNodeOp.t.sol
:
NodeOp1 creates minipool
Rialto calls claimAndInitiateStaking, recordStakingStart and recordStakingError()
NodeOp1 withdraw his funds from minipool
NodeOp1 can get rewards even if there was an error with the node registration as validator.
Foundry/VsCode
The MinipoolManager.sol::recordStakingError()
function should reset the Assigned high water staking.resetAVAXAssignedHighWater(stakerAddr);
so the user can not claim rewards for a minipool with errors.
Good find. This is unique in terms of calling out
avaxAssignedHighWater
but I'm going to link other issues dealing withrecordStakingError
https://github.com/code-423n4/2022-12-gogopool-findings/issues/819
Since this is not a leak of funds in the protocol but GGP rewards instead, I think a medium designation is more appropriate
So the warden is incorrect about the order of events that should happen, the correct order is the following:
NodeOp1 creates minipool
Rialto calls
claimAndInitiateStaking()
Rialto calls
recordStakingStart()
if the staking with avalanche was successful. If it was not, Rialto will callrecordStakingError()
. So Rialto will never be calling both of these functions, it is one or the other.
avaxAssignedHighWater
is only changed inrecordStakingStart()
, so not sure we would want to reset it inrecordStakingError()
.Questioning the validity of the issue.
The key issue is that a minipool won't ever go from
Staking
toError
state. It's currently allowed in our state machine but it's not a situation that can happen on the Avalanche network and something we'll fix. In that way it depends on Rialto making a mistake to transition the minipool from staking to error.I think pointing out the issue in our state machine is valid and QA level.
The Warden has highlighted an issue with the FSM of the system.
While Rialto is assumed as a perfect actor, the code allows calling
recordStakingStart
and thenrecordStakingError
.This state transition is legal, however will cause issues, such as setting
avaxAssignedHighWater
to a higher value than intended, which could allow the staker to be entitled to rewards.Because the State Transition will not happen in reality (per the Scope Requirements), am downgrading the finding to Medium Severity and believe the State Transition Check should be added to offer operators and end users a higher degree of on-chain guarantees.
The ggAvax holder can not redeem his funds until the rewardsCycleEnd
.
I did the next test:
Create minipool (2000 avax)
Deposit rewards to the minipool (200 AVAX rewards)
Sync the rewards before the cycle ends
Redeem function will revert
Redeem will be available after the cycle end
Output:
Foundry/VsCode
Consider redeem the max available amount for the shares owner instead of revert. The maxRedeem()
function amount is not the same as the previewRedeem()
amount.
This is a known issue that we don't intend to fix. The issue is most likely to present itself at the very start of the ggAVAX and not during typical operation. There's a bit more explanation here: https://github.com/fei-protocol/ERC4626/issues/24
I don't believe redeeming max available is an appropriate solution because the spec for redeem reads
MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc).
The Warden has shown a scenario in which
maxRedeem
can revert.While this can be attributed to rounding errors, it ultimately is possible for certain depositors to lose marginal amounts of their rewards or principal.
Because of the reduced impact, I agree with Medium Severity.
This is a hedge case that has been argued to have happened very rarely, and for this reason, I maintain that the severity is Medium, but can agree with a nofix, as the worst case will require the Sponsor to offer a small amount of additional token, to allow the last withdrawer to maxRedeem.
This means that if a staker has a minipool that encounters an error, his minipoolCount
can never go to zero again.
Since the minipoolCount
cannot go to zero, the rewardsStartTime
will never be reset.
To conclude, failing to decrease the minipoolCount
allows the staker to earn higher rewards because he is eligible for staking right after he creates a new minipool and does not have to wait again.
I have created the following test that you can add to the MinipoolManager.t.sol
file that logs the minipoolCount
in the Staking
, Error
and Finished
state.
The minipoolCount
is always 1
although it should decrease to 0
when recordStakingError
is called.
VSCode
You need to simply add the line staking.decreaseMinipoolCount(owner);
to the MinipoolManager.recordStakingError
function.
The Warden has shown how, calling
recordStakingError
will not decrease theminipoolCount
.This will not only impact view functions but also impact Yield calculations.
For this reason, I agree with Medium Severity.
Thereby any calls to functions that deposit or withdraw funds revert.
There are two functions (maxWithdraw
and maxRedeem
) that calculate the max amount that can be withdrawn or redeemed respectively.
Both functions return 0
if the TokenggAVAX
contract is paused.
Thereby these two functions return a value that cannot actually be deposited or minted.
This can cause any components that rely on any of these functions to return a correct value to malfunction.
So maxDeposit
and maxMint
should return the value 0
when TokenggAVAX
is paused.
VSCode
So add these two functions to the TokenggAVAX
contract:
Looks off, the modifiers will revert on pause, not return 0.
I'd say Low:
(e.g. assets are not at risk: state handling, function incorrect as to spec, issues with comments). Excludes Gas optimizations, which are submitted and judged separately.
Good catch, I think we should override those for consistency at least but there's no way to exploit to lose assets. Agreed that QA makes sense.
By definition, the finding is Informational in Nature.
Because of the relevancy, I'm awarding it QA - Low
I had a change of heart on this issue, because this pertains to a standard that is being implemented.
For that reason am going to award Medium Severity, because the function breaks the standard, and historically we have awarded similar findings (e..g broken ERC20, broken ERC721 standard), with Medium.
The Warden has shown an inconsistency between the ERC-4626 Spec and the implementation done by the sponsor, while technically this is an informational finding, the fact that a standard was broken warrants a higher severity, leading me to believe that Medium is a more appropriate Severity.
Am making this decision because the Sponsor is following the standard, and the implementation of these functions is not consistent with it.
A user needs to call the function startRewardsCycle in RewardsPool.sol
which calls:
We need to pay special attention to the code block below:
which calls:
The code distributes the reward to all multisig evenly.
However, if the enabledCount is 0, meaning no multisig wallet is enabled, the transactions revert in division by zero error and revert the startRewardsCycle transaction.
As shown in POC.
In RewardsPool.t.sol,
we change the name from testStartRewardsCycle to testStartRewardsCycle_POC
we add the code to disable all multisig wallet. before calling rewardsPool.startRewardsCycle
Then we run the test
the transaction revert in division by zero error, which block the startRewardsCycle
We recommend the project handle the case when the number of enabled multisig is 0 gracefully to not block the startRewardCycle transaction.
The Warden has shown a scenario that could cause the call to
startRewardsCycle
to revert.When all multisigs are disabled (or no multisig is added), the division by zero will cause reverts.
While Admin Privilege is out of scope for this contest, the Warden has identified how a lack of zero-check can cause an open function to revert.
For this reason, I agree with Medium Severity.
The validation rewards can be inaccurately displayed to user and the slahsed amount can be wrong when slashing happens.
Note the function below:
As outlined in the comment section, the function is intended to calculate how much AVAX should be earned via validation rewards.
Besides displaying the reward, this function is also used in the function slash.
Note the code:
The slashedGGPAmt is calculated based on the AVAX reward amount.
However, the estimation of the validation rewards is not accurate.
According to the doc:
Running a validator and staking with Avalanche provides extremely competitive rewards of between 9.69% and 11.54% depending on the length you stake for.
This implies that the staking length affect staking rewards, but this is kind of vague. What is the exact implementation of the reward calculation?
The implementation is linked below:
Note the reward calculation formula:
However, in the current ExpectedRewardAVA, the implementation is just:
AVAX reward rate * avax amount * duration / 365 days.
Clearly, the implementation of the avalanche side is more sophisticated and accurate than the implemented ExpectedRewardAVA.
We recommend the project make the ExpectedRewardAVA implementation match the implement.
Rialto is going to report the correct rewards rate to the DAO from Avalanche. Not sure if it's a medium.
We felt comfortable with a static setting number because we are (initally) staking minipools for 2 week increments with 2000 AVAX, making the variability in rewards rates minimal.
We will develop a more complex calculation as the protocol starts handling a wider range of funds and durations.
The Warden has shown an incorrect implementation of the formula to estimate rewards.
The math would cause the slash value to be incorrect, causing improper yield to be distributed, for this reason I agree with Medium Severity.
Acknowledged. See comments above!
[L‑01]
Inflation not locked for four years
1
[L‑02]
Contract will stop functioning in the year 2106
1
[L‑03]
Lower-level initializations should come first
1
[L‑04]
Incorrect percentage conversion
1
[L‑05]
Loss of precision
2
[L‑06]
Signatures vulnerable to malleability attacks
1
[L‑07]
require()
should be used instead of assert()
1
Total: 8 instances over 7 issues
[N‑01]
Common code should be refactored
1
[N‑02]
String constants used in multiple places should be defined as constants
1
[N‑03]
Constants in comparisons should appear on the left side
1
[N‑04]
Inconsistent address separator in storage names
1
[N‑05]
Confusing function name
1
[N‑06]
Misplaced punctuation
1
[N‑07]
Upgradeable contract is missing a __gap[50]
storage variable to allow for new storage variables in later versions
1
[N‑08]
Import declarations should import specific identifiers, rather than the whole file
13
[N‑09]
Missing initializer
modifier on constructor
1
[N‑10]
The nonReentrant
modifier
should occur before all other modifiers
2
[N‑11]
override
function arguments that are unused should have the variable name removed or commented out to avoid compiler warnings
1
[N‑12]
constant
s should be defined rather than using magic numbers
2
[N‑13]
Missing event and or timelock for critical parameter change
1
[N‑14]
Events that mark critical parameter changes should contain both the old and the new value
2
[N‑15]
Use a more recent version of solidity
1
[N‑16]
Use a more recent version of solidity
1
[N‑17]
Constant redefined elsewhere
2
[N‑18]
Lines are too long
1
[N‑19]
Variable names that consist of all capital letters should be reserved for constant
/immutable
variables
2
[N‑20]
Using >
/>=
without specifying an upper bound is unsafe
2
[N‑21]
Typos
3
[N‑22]
File is missing NatSpec
3
[N‑23]
NatSpec is incomplete
27
[N‑24]
Not using the named return variables anywhere in the function is confusing
1
[N‑25]
Contracts should have full test coverage
1
[N‑26]
Large or complicated code bases should implement fuzzing tests
1
[N‑27]
Function ordering does not follow the Solidity style guide
15
[N‑28]
Contract does not follow the Solidity style guide's suggested layout ordering
9
[N‑29]
Open TODOs
1
Total: 99 instances over 29 issues
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/ProtocolDAO.sol#L39-L41
Limiting the timestamp to fit in a uint32
will cause the call below to start reverting in 2106.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/TokenggAVAX.sol#L89
There may not be an issue now, but if ERC4626
changes to rely on some of the functions BaseUpgradeable
provides, things will break.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/TokenggAVAX.sol#L72-L74
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/MinipoolManager.sol#L194
Division by large numbers may result in the result being zero, due to solidity not supporting fractions. Consider requiring a minimum amount for the numerator to ensure that it is always larger than the denominator.
There are 2 instances of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/RewardsPool.sol#L60
ecrecover()
accepts as valid, two versions of signatures, meaning an attacker can use the same signature twice. Consider adding checks for signature malleability, or using OpenZeppelin's ECDSA
library to perform the extra checks necessary in order to prevent this attack.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/upgradeable/ERC20Upgradeable.sol#L132-L152
require()
should be used instead of assert()
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/TokenggAVAX.sol#L83
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/MultisigManager.sol#L110
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/MultisigManager.sol#L110
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/ClaimNodeOp.sol#L92
Most addresses in storage names don't separate the prefix from the address with a period, but this one has one.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/ProtocolDAO.sol#L102-L109
Consider changing the name to stakeGGPAs
or stakeGGPFor
.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/Staking.sol#L328
There's an extra comma - it looks like a find-and-replace error.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/Vault.sol#L154-L160
__gap[50]
storage variable to allow for new storage variables in later versionsThere is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/TokenggAVAX.sol#L24
Using import declarations of the form import {<identifier_name>} from "some/file.sol"
avoids polluting the symbol namespace making flattened files smaller, and speeds up compilation.
initializer
modifier on constructorThere is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/BaseUpgradeable.sol#L9
nonReentrant
modifier
should occur before all other modifiersThis is a best-practice to protect against reentrancy in other modifiers.
There are 2 instances of this issue.
override
function arguments that are unused should have the variable name removed or commented out to avoid compiler warningsThere is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/TokenggAVAX.sol#L255
constant
s should be defined rather than using magic numbersThere are 2 instances of this issue.
Events help non-contract tools to track changes, and events prevent users from being surprised by changes.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/Storage.sol#L41-L48
This should especially be done if the new value is not required to be different from the old value.
There are 2 instances of this issue.
Use a solidity version of at least 0.8.13 to get the ability to use using for
with a list of free functions.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/upgradeable/ERC4626Upgradeable.sol#L2
Use a solidity version of at least 0.8.4 to get bytes.concat()
instead of abi.encodePacked(<bytes>,<bytes>)
.
Use a solidity version of at least 0.8.12 to get string.concat()
instead of abi.encodePacked(<str>,<str>)
.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/tokens/upgradeable/ERC20Upgradeable.sol#L2
There are 2 instances of this issue.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/ProtocolDAO.sol#L41
constant
/immutable
variablesThere are 2 instances of this issue.
>
/>=
without specifying an upper bound is unsafeThere will be breaking changes in future versions of solidity, and at that point your code will no longer be compatable. While you may have the specific version to use in a configuration file, others that include your source files may not.
There are 2 instances of this issue.
There are 3 instances of this issue.
There are 3 instances of this issue.
There are 27 instances of this issue.
Consider changing the variable to be an unnamed one.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/MinipoolManager.sol#L572
While 100% code coverage does not guarantee that there are no bugs, it often will catch easy-to-find bugs, and will ensure that there are fewer regressions when the code invariably has to be modified. Furthermore, in order to get full coverage, code authors will often have to re-organize their code so that it is more modular, so that each component can be tested separately, which reduces interdependencies between modules and layers, and makes for code that is easier to reason about and audit.
There is 1 instance of this issue:
There is 1 instance of this issue:
There are 15 instances of this issue.
There are 9 instances of this issue.
Code architecture, incentives, and error handling/reporting questions/issues should be resolved before deployment.
There is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/MinipoolManager.sol#L412
These findings are excluded from awards calculations because there are publicly-available automated tools that find them. The valid ones appear here for completeness.
[L‑08]
Missing checks for address(0x0)
when assigning values to address
state variables
1
[L‑09]
abi.encodePacked()
should not be used with dynamic types when passing the result to a hash function such as keccak256()
155
Total: 156 instances over 2 issues
[N‑30]
Return values of approve()
not checked
2
[N‑31]
public
functions not called by the contract should be declared external
instead
54
[N‑32]
Event is missing indexed
fields
26
Total: 82 instances over 3 issues
address(0x0)
when assigning values to address
state variablesThere is 1 instance of this issue:
https://github.com/code-423n4/2022-12-gogopool/blob/aec9928d8bdce8a5a4efe45f54c39d4fc7313731/contracts/contract/Storage.sol#L47
abi.encodePacked()
should not be used with dynamic types when passing the result to a hash function such as keccak256()
If all arguments are strings and or bytes, bytes.concat()
should be used instead.
There are 155 instances of this issue.
approve()
not checkedNot all IERC20
implementations revert()
when there's a failure in approve()
. The function signature has a boolean
return value and they indicate errors that way instead. By not checking the return value, operations that should have marked as failed, may potentially go through without actually approving anything.
There are 2 instances of this issue.
public
functions not called by the contract should be declared external
insteadThere are 54 instances of this issue.
indexed
fieldsThere are 26 instances of this issue.
[L‑01] Inflation not locked for four years Refactor. Code as is will revert after 4 years, so it's enforced via config.
[L‑02] Contract will stop functioning in the year 2106 Low
[L‑03] Lower-level initializations should come first Refactor in lack of specific risk
[L‑04] Incorrect percentage conversion Low
[L‑05] Loss of precision Low
[L‑06] Signatures vulnerable to malleability attacks Low
[L‑07] require() should be used instead of assert() Refactor
[N‑01] Common code should be refactored Refactor
[N‑02] String constants used in multiple places should be defined as constants Refactor
[N‑03] Constants in comparisons should appear on the left side Refactor
[N‑04] Inconsistent address separator in storage names Non-Critical
[N‑05] Confusing function name Non-Critical
[N‑06] Misplaced punctuation Non-Critical
[N‑07] Upgradeable contract is missing a
__gap[50]
storage variable to allow for new storage variables in later versions Disputing for TokenAvax as it's the child contract[N‑08] Import declarations should import specific identifiers, rather than the whole file Non-Critical
[N‑09] Missing initializer modifier on constructor Refactor
[N‑10] The nonReentrant modifier should occur before all other modifiers Refactor
[N‑11] override function arguments that are unused should have the variable name removed or commented out to avoid compiler warnings Non-Critical
[N‑12] constants should be defined rather than using magic numbers Refactor
[N‑13] Missing event and or timelock for critical parameter change Non-Critical
[N‑14] Events that mark critical parameter changes should contain both the old and the new value Non-Critical
[N‑15] Use a more recent version of solidity Non-Critical
[N‑16] Use a more recent version of solidity See N-15
[N‑17] Constant redefined elsewhere Refactor
[N‑18] Lines are too long Non-Critical
[N‑19] Variable names that consist of all capital letters should be reserved for constant/immutable variables Refactor
[N‑20] Using >/>= without specifying an upper bound is unsafe Refactor
[N‑21] Typos Non-Critical
[N‑22] File is missing NatSpec Non-Critical
[N‑23] NatSpec is incomplete Non-Critical
[N‑24] Not using the named return variables anywhere in the function is confusing Refactor
[N‑25] Contracts should have full test coverage Refactor
[N‑26] Large or complicated code bases should implement fuzzing tests Refactor
[N‑27] Function ordering does not follow the Solidity style guide Non-Critical
[N‑28] Contract does not follow the Solidity style guide's suggested layout ordering Non-Critical
[N-29] Open TODOs Non-Critical
Best report by far, so far I thought the second best was the best (this one scores above 100%).
Well played.
[G‑01]
State variables can be packed into fewer storage slots
1
-
[G‑02]
Use a more recent version of solidity
2
-
[G‑03]
++i
/i++
should be unchecked{++i}
/unchecked{i++}
when it is not possible for them to overflow, as is the case when used in for
- and while
-loops
10
600
[G‑04]
internal
functions only called once can be inlined to save gas
4
80
[G‑05]
Functions guaranteed to revert when called by normal users can be marked payable
62
1302
[G‑06]
Optimize names to save gas
13
286
[G‑07]
Use custom errors rather than revert()
/require()
strings to save gas
4
200
[G‑08]
Add unchecked {}
for subtractions where the operands cannot underflow because of a previous require()
or if
-statement
7
595
[G‑09]
Multiple accesses of a mapping/array should use a local variable cache
4
168
[G‑10]
State variables should be cached in stack variables rather than re-reading them from storage
11
1067
[G‑11]
Modification of getX()
, setX()
, deleteX()
, addX()
and subX()
in BaseAbstract.sol
increases gas savings in [G‑10]
116
11252
[G‑12]
<x> += <y>
costs more gas than <x> = <x> + <y>
for state variables (-=
too)
12
1356
[G‑13]
Division by two should use bit shifting
1
20
[G‑14]
The result of function calls should be cached rather than re-calling the function
2
200
[G‑15]
Don't compare boolean expressions to boolean literals
3
27
[G‑16]
Splitting require()
statements that use &&
saves gas
1
3
[G‑17]
Stack variable used as a cheaper cache for a state variable is only used once
3
9
Total: 256 instances over 17 issues with 17165 gas saved.
Gas totals use lower bounds of ranges and count two iterations of each for
-loop. All values above are runtime, not deployment, values; deployment values are listed in the individual issue descriptions.
If variables occupying the same slot are both written by the same function or by the constructor, avoids a separate Gsset (20000 gas). Reads of the variables can also be cheaper.
There is 1 instance of this issue:
Use a solidity version of at least 0.8.2 to get simple compiler automatic inlining.
Use a solidity version of at least 0.8.3 to get better struct packing and cheaper multiple storage reads.
Use a solidity version of at least 0.8.4 to get custom errors, which are cheaper at deployment than revert()/require()
strings.
Use a solidity version of at least 0.8.10 to have external calls skip contract existence checks if the external call has a return value.
++i
/i++
should be unchecked{++i}
/unchecked{i++}
when it is not possible for them to overflow, as is the case when used in for
- and while
-loopsThere are 10 instances of this issue.
internal
functions only called once can be inlined to save gasNot inlining costs 20 to 40 gas because of two extra JUMP
instructions and additional stack operations needed for function calls.
There are 4 instances of this issue.
payable
If a function modifier such as onlyOwner
is used, the function will revert if a normal user tries to pay the function. Marking the function as payable
will lower the gas cost for legitimate callers because the compiler will not include checks for whether a payment was provided. The extra opcodes avoided are CALLVALUE
(2), DUP1
(3), ISZERO
(3), PUSH2
(3), JUMPI
(10), PUSH1
(3), DUP1
(3), REVERT
(0), JUMPDEST
(1), POP
(2), which costs an average of about 21 gas per call to the function, in addition to the extra deployment cost.
There are 62 instances of this issue.
There are 13 instances of this issue.
revert()
/require()
strings to save gasThere are 4 instances of this issue.
unchecked {}
for subtractions where the operands cannot underflow because of a previous require()
or if
-statementrequire(a <= b); x = b - a
=> require(a <= b); unchecked { x = b - a }
.
There are 7 instances of this issue.
There are 4 instances of this issue.
The instances below point to the second+ access of a state variable within a function. Caching of a state variable replaces each Gwarmaccess (100 gas) with a much cheaper stack read. Other less obvious fixes/optimizations include having local memory caches of state variable structs, or having local caches of state variable contracts/addresses.
There are 11 instances of this issue.
getX()
, setX()
, deleteX()
, addX()
and subX()
in BaseAbstract.sol
increases gas savings in [G‑10]Modify the getX()
, setX()
, deleteX()
, addX()
and subX()
functions in BaseAbstract.sol
to receive the address of the Storage
contract as an argument. This modification will create dozens more fixable instances of [G‑10].
There are 116 instances of this issue.
<x> += <y>
costs more gas than <x> = <x> + <y>
for state variables (-=
too)There are 12 instances of this issue.
There is 1 instance of this issue:
The instances below point to the second+ call of the function within a single function. Every external call made to a contract incurs at least 100 gas of overhead.
There are 2 instances of this issue.
if (<x> == true)
=> if (<x>)
, if (<x> == false)
=> if (!<x>)
.
There are 3 instances of this issue.
require()
statements that use &&
saves gasThere is 1 instance of this issue:
If the variable is only accessed once, it's cheaper to use the state variable directly that one time, and save the 3 gas the extra stack assignment would spend.
There are 3 instances of this issue.
[G‑01] State variables can be packed into fewer storage slots Not awarding as it will only save gas at deploy time
[G‑02] Use a more recent version of solidity Skipping as missing further info
[G‑03]
++i
/i++
should beunchecked{++i}
/unchecked{i++}
when it is not possible for them to overflow, as is the case when used in for- and while-loops 25 * 7[G‑04] internal functions only called once can be inlined to save gas 16 per instance 4 * 16
[G‑05] Functions guaranteed to revert when called by normal users can be marked payable Ignoring
[G‑06] Optimize names to save gas Ignoring
[G‑07] Use custom errors rather than
revert()
/require()
strings to save gas Ignoring for lack of proven benchmarks[G‑08] Add unchecked {} for subtractions where the operands cannot underflow because of a previous
require()
or if-statement 7 * 20[G‑09] Multiple accesses of a mapping/array should use a local variable cache 2 are "normal" to avoid the -= or += the other 2 are valid 2 * 100
[G‑10] State variables should be cached in stack variables rather than re-reading them from storage 11 * 100
[G‑11] Modification of
getX()
,setX()
,deleteX()
,addX()
andsubX()
in BaseAbstract.sol increases gas savings in [G‑10] Am understanding this as the idea of inlining the call rather than using a function. 16 * 1161856
[G‑12]
<x> += <y>
costs more gas than<x> = <x> + <y>
for state variables (-= too) Out of scope[G‑13] Division by two should use bit shifting Equivalent to using unchecked
20
[G‑14] The result of function calls should be cached rather than re-calling the function 340 * 2
680
[G‑15] Don't compare boolean expressions to boolean literals 27
[G‑16] Splitting require() statements that use && saves gas Marginal
[G‑17] Stack variable used as a cheaper cache for a state variable is only used once Marginal
Total: 4262
[G‑11] Modification of
getX()
,setX()
,deleteX()
,addX()
andsubX()
in BaseAbstract.sol increases gas savings in [G‑10] Am understanding this as the idea of inlining the call rather than using a function 16 * 116This wasn't what I meant. I meant that each of these functions accesses the
gogoStorage
state variable (SLOAD). Therefore, when there's more than one call to this group of functions (for example,setUint()
followed by anothersetUint()
, orsetUint()
followed bygetAddress()
), it would me much cheaper to cache that state variable (gogoStorage
) and pass it to the these functions. This way, there will be only one SLOAD.In my gas report, I flagged the second+ calls to this group of functions as instances, since this optimization can spare an SLOAD in each of these calls. There are 116 instances, each saves 100 gas (like in G-10) - meaning a total saving of 11600 gas.
[G‑12]
<x> += <y>
costs more gas than<x> = <x> + <y>
for state variables (-= too) Out of scopeWhy is that out-of-scope? The
TokenggAVAX.sol
andERC20Upgradeable.sol
contracts are in scope, and this optimization wasn't included in the C4audit output.Overall, My gas report saves an additional amount of 12956 gas. So the total gas savings are 17218 gas. Therefore, I believe my gas report should be the one selected for the report.
@NoamYakov - Thank you for the comment, to clarify regarding G-11, are you saying to cache the address of Storage or to make it Immutable as to avoid the extra SLOAD?
The += is a knee jerk reaction I have in judging and have judged it as OOS for all reports. My own benchmarks show that's it's a very marginal saving, especially because it will not save gas when used in combination with
unchecked
, either way it would raise / lower the majority of reports so it will not matter as much.Lmk about G-11 please.
I'm saying to cache the address of Storage in order to avoid the extra SLOAD.
I agree with the suggested refactoring, I believe there's fair ground to cap the value of the refactoring to a certain value (e.g 5k gas saved). That said, after factoring that in, the refactoring would save the most gas.
Technically a better solution would be to just use
immutable
which would avoid all SLOADs.
Summary from the Sponsor:
Here's our biggest changes to look out for:
Minipool State Machine - We've tightened up the allowed state transitions including a new recreate minipool method that's atomic and doesn't allow node ops to withdraw funds or hijack a minipool.
Tracking AVAX High Water - Our previous system forced some tradeoffs to which AVAX is calculated in HighWater. We added a new variable
AVAXValidating
which tracks amount of AVAX actually validating on the P-Chain, and High Water is simply the highest validating amount during the period.TokenGGP - Changed how tokens are inflated to actually mint rather than track tokens in the ProtocolDAO
Contract Upgrades - We're now able to upgrade as expected, to a contract with the same name as the existing contract
Upgradeable Tokens - ERC20Upgradeable takes a variable version for it's domain separator and we added storage gaps across the board
https://github.com/multisig-labs/gogopool/pull/25
H-01
New variable to track validating avax
Not fixing
H-02
N/A
https://github.com/multisig-labs/gogopool/pull/41
H-03
Base slash on validation period not full duration
https://github.com/multisig-labs/gogopool/pull/23
H-04
Atomically recreate minipool to now allow hijack
https://github.com/multisig-labs/gogopool/pull/49
H-05
Initialize ggAVAX with a deposit
https://github.com/multisig-labs/gogopool/pull/41
H-06
If staked GGP doesn't cover slash amount, slash it all
https://github.com/multisig-labs/gogopool/pull/22
M-01
Pause startRewardsCycle when protocol is paused
https://github.com/multisig-labs/gogopool/pull/32
M-02
Fix upgrade to work when a contract has the same name
https://github.com/multisig-labs/gogopool/pull/20
M-03
Remove method that trapped Node Operator's funds
Not fixing
M-04
N/A
https://github.com/multisig-labs/gogopool/pull/22
M-05
Pause claimAndRestake as well
Not fixing
M-06
N/A
Not fixing
M-07
N/A
https://github.com/multisig-labs/gogopool/pull/43
M-08
Use liquid staker avax amount instead of node op amount
https://github.com/multisig-labs/gogopool/pull/23
M-09
Atomically recreate minipool so a node operator can't withdraw inbetween
https://github.com/multisig-labs/gogopool/pull/51
M-10
Reset rewards start time in cancel minipool
Not fixing
M-11
N/A
https://github.com/multisig-labs/gogopool/pull/40
M-12
Base cancelMinipool delay on minipool creation time not rewards start time
https://github.com/multisig-labs/gogopool/pull/41
M-13
If staked GGP doesn't cover slash amount, slash it all
https://github.com/multisig-labs/gogopool/pull/38
M-14
Added bounds for duration passed by Node Operator
Not fixing in this version of the protocol
M-15
N/A
https://github.com/multisig-labs/gogopool/pull/50
M-16
ggAVAX max redeem incorrect, not fixing, but made test to illustrate.
https://github.com/multisig-labs/gogopool/pull/28
M-17
Remove the state transition from Staking to Error.
Not fixing in this version of the protocol
M-18
N/A
https://github.com/multisig-labs/gogopool/pull/42
M-19
We removed minipool count entirely.
https://github.com/multisig-labs/gogopool/pull/33
M-20
Return correct value from maxMint and maxDeposit when the contract is paused.
https://github.com/multisig-labs/gogopool/pull/37
M-21
Prevents division by zero error blocking startRewardCycle().
Not fixing in this version of the protocol
M-22
N/A
Of the mitigations reviewed, 13 have been confirmed as well as 2 confirmed with comments:
The 4 remaining mitigations have either not been confirmed and/or introduced new issues. See full details below.
(Note: mitigation reviews below are referenced as MR:S-N
, MitigationReview:NewIssueSeverity-NewIssueNumber
)
Submitted by hansfriese
In the original implementation, the protocol had some unnecessary state transitions and it was possible for node operators to interfere the recreation process.
The main problem was the recordStakingEnd()
and recreateMiniPool()
were separate external functions and the operator could frontrun the recreateMiniPool()
and call withdrawMinipoolFunds()
.
The node operators are likely to be slashed in an unfair way
https://github.com/multisig-labs/gogopool/blob/4bcef8b1d4e595c9ba41a091b2ebf1b45858f022/contracts/contract/MinipoolManager.sol#L464
In the previous implementation, I assumed rialtos are smart enough to recreate minipools only when it's necessary.
But now, the recreation process is included as an optional way in the recordStakingEndThenMaybeCycle()
, so as long as the check initialStartTime + duration > block.timestamp
at L#464 passes, recreation will be processed.
It is possible that the initialStartTime + duration <= block.timestamp
. In this case, the protocol will not start the next cycle. And the node validation was done for two cycles different to the initial plan.
If initialStartTime + duration > block.timestamp
, the protocol will start the third cycle. But on the end of that cycle, it is likely that the node is not eligible for reward by the Avalanche validators voting. (Imagine the node op lent a server for 42 days, then 42-14*2-12=2 days from the third cycle start the node might have stopped working and does not meet the 80% uptime condition) Then the node operator will be punished and GGP stake will be slashed. This is unfair.
The main reason of this problem is that technically there exists two timelines. And the protocol does not track the actual validation duration that the node was used accurately.
At least, the protocol should not start a new cycle if initialStartTime + duration < block.timestamp + 14 days
because it is likely that the node operator get punished at the end of that cycle.
If it is 100% guaranteed that startTime[n+1]=endTime[n]
for all cycles, I recommend starting a new cycle only if initialStartTime + duration < block.timestamp + 14 days
.
If not, I suggest adding a new state variable that will track the actual validation period (actual utilized period).
Mitigation error - created another issue for the same edge case.
https://github.com/multisig-labs/gogopool/blob/9ad393c825e6ac32f3f6c017b4926806a9383df1/contracts/contract/MinipoolManager.sol#L731-L733
If staked GGP doesn't cover slash amount, slashing it all will not be fair to the liquid stakers. Slashing is rare, and that the current 14 day validation cycle which is typically 1/26 of the minimum amount of GGP staked is unlikely to bump into this situation unless there is a nosedive of GGP price in AVAX. The deficiency should nonetheless be made up from avaxNodeOpAmt
should this unfortunate situation happen.
As can be seen from the code block above, in extreme and unforeseen cases, the difference between staking.getGGPStake(owner)
and slashGGPAmt
can be significant. Liquid stakers would typically and ultimately care about how they are going to be adequately compensated with, in AVAX preferably.
Consider having the affected if block refactored as follows:
As the warden pointed out, this event is very unlikely. I think that it is a reasonable risk for the protocol to take. Slashing does not exist in Avalanche, you simply get rewards or do not, so personally, I don't think slashing their AVAX would be a good solution as it goes against Avalanche practices. Will bring it up to the team to see what they think.
The team seems to be in consensus that this is unlikely and that we will not be changing. The proposed solution goes against how Avalanche protocol operates so we believe it would not be an appropriate fix.
The proposed solution refers to slashing of AVAX in C Chain where this measure is solely at the discretion of the protocol. But I understand the complication entailed in making fixes for incidents that will be rare to occur.
I believe the Sponsors opinion to be valid, and that the scenario may be unlikely.
However, I think the math shows that the system would be taking a loss which may be notable.
I'm thinking Medium Severity would be appropriate, but a Nofix seems acceptable given the odds (a "risk treasury" could be created to account for this scenario without needing to change the contracts).
Submitted by RaymondFam
https://github.com/multisig-labs/gogopool/blob/3b5ab1d6505ef9be6197c4056acd38d6bed4aff6/contracts/contract/tokens/TokenggAVAX.sol#L134-L146 https://github.com/multisig-labs/gogopool/blob/3b5ab1d6505ef9be6197c4056acd38d6bed4aff6/contracts/contract/MinipoolManager.sol#L497-L505
The mitigated step is implemented at the expense of economic loss to both the node operators and the liquid stakers if compoundedAvaxNodeOpAmt <= ggAVAX.amountAvailableForStaking()
.
Here is a typical scenario:
The protocol now assumes that a 1:1 nodeOp:liqStaker funds ratio is guaranteed to be met because of the atomic transaction that has also been implemented.
This is deemed an edge case that will only be optimally utilized if compoundedAvaxAmt == ggAVAX.amountAvailableForStaking()
.
Consider implementing the following check in recreateMinipool()
to get the best out of it:
I'll give it a second check before awarding, but marking as valid for now.
Here is one solution I could suggest:
https://github.com/multisig-labs/gogopool/blob/4bcef8b1d4e595c9ba41a091b2ebf1b45858f022/contracts/contract/utils/RialtoSimulator.sol
The added check ensures the atomic transaction is going to reliably recreate amidst the right pick for the validating amount I recommended earlier in this issue.
Otherwise, opting for a resolution by using
canClaimAndInitiateStaking()
is going to be tricky due to the restrictingrequireValidStateTransition()
.
The protocol provides an external function startRewardsCycle()
so that anyone can start a new reward cycle if necessary.
Before mitigation, there was an edge case where this function will revert due to division by zero. Edge case: there are no multisigs enabled. (possible when Ocyticus.disableAllMultisigs(), Ocyticus.pauseEverything()
is called)
There is no way to retrieve the rewards from the MultisigManager
and rewards are locked in the vault.
https://github.com/multisig-labs/gogopool/blob/4bcef8b1d4e595c9ba41a091b2ebf1b45858f022/contracts/contract/RewardsPool.sol#L229
There is no way to retrieve the rewards from the MultisigManager
and rewards are locked in the vault.
The rewards that were accrued in this specific edge case are locked in the MultisigManager
.
It is understood that the funds are not lost and the protocol can be upgraded with a new MultisigManager
contract with a proper function.
I evaluate the severity of the new issue as Medium because funds are locked in some specific edge cases and only withdrawable after contract upgrades.
Add a new external function in the MultisigManager
with guardianOrSpecificRegisteredContract("Ocyticus", msg.sender)
modifier and distribute the pending rewards to the active multisigs.
Mitigation error - created another issue for the same edge case.
I think this is valid. We do plan on adding a claim or withdrawal method that allows an enabled multisig to receive those funds. This can also be easily added with an upgrade once the issue occurs if we arent able to add it to this version.
Seems like
MultisigManager
doesn't offer a sweep function, which would cause tokens to be stuck.Due to the conditionality, I agree with Medium Severity.
C4 is an open organization governed by participants in the community.
C4 Contests incentivize the discovery of exploits, vulnerabilities, and bugs in smart contracts. Security researchers are rewarded at an increasing rate for finding higher-risk issues. Contest submissions are judged by a knowledgeable security researcher and solidity developer and disclosed to sponsoring developers. C4 does not conduct formal verification regarding the provided code but instead provides final verification.
C4 does not provide any guarantee or warranty regarding the security of this project. All smart contract software should be used at the sole risk and responsibility of users.
This contest was judged by .
Final report assembled by .
The code under review can be found within the , and is composed of 18 smart contracts written in the Solidity programming language and includes 2,040 lines of Solidity code.
For more information regarding the severity criteria referenced throughout the submission review process, please refer to the documentation provided on , specifically our section on .
Submitted by , also found by , , , , , and
:
:
:
:
New variable to track validating avax:
Status: Mitigation confirmed with comments. Full details in .
Submitted by , also found by , , , , , , , , and
:
:
Submitted by , also found by , , , , , , , , and
The protocol also wants node operators to stake in longer periods:
:
:
Base slash on validation period not full duration:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and
The state machine allows transitions according the requireValidStateTransition
function:
createMinipool
:
Add the following test to MinipoolManager.t.sol
:
Consider placing onlyOwner(index)
in the following area:
:
Separate note: I created . For the Finding 2 of this report, please refrain from grouping findings especially when they use different functions and relate to different issues.
:
Atomically recreate minipool to not allow hijack:
Status: Mitigation confirmed, but a new medium severity issue was found. Full details in , and also included in Mitigation Review section below.
Submitted by , also found by , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and
convertToShares
:
syncRewards
:
depositAVAX
:
previewDeposit
and convertToShares
:
Add the following test to TokenggAVAX.t.sol
:
:
:
Initialize ggAVAX with a deposit:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , and
When staking is done, a Rialto multisig calls MinipoolManager.recordStakingEnd
().
It looks like if this happens, MinipoolManager.recordStakingError
() is called.
When calling MinipoolManager.recordStakingEnd
() and the avaxTotalRewardAmt
parameter is zero, the node operator is slashed:
The MinipoolManager.slash
function () then calculates expectedAVAXRewardsAmt
and from this slashGGPAmt
:
Downstream there is then a revert due to underflow because of the following line in Staking.decreaseGGPStake
():
:
:
:
:
If staked GGP doesn't cover slash amount, slash it all:
Status: Original finding mitigated, but a medium severity economical risk is still present. Full details in reports from , and . Also included in Mitigation Review section below.
Submitted by , also found by
:
:
Pause startRewardsCycle when protocol is paused:
Status: Mitigation confirmed with comments. Full details in .
Submitted by , also found by , , , , , , , , , , , , , , , , , , , , and
:
:
:
:
Fix upgrade to work when a contract has the same name:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , , , , , , , and
The Multisig can call MinipoolManager.sol::recordStakingError()
if there is an error while registering the node as a validator. Also the Multisig can call in order to "finish" the NodeOp's minipool proccess.
The withdrawMinipoolFunds
could add another in order to allow the withdraw after the finished minipoool.
:
:
:
Remove method that trapped Node Operator's funds:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , , , , , , , , , , , , and
Use a strategy like to assign next active multisig to minipool.
:
:
:
Submitted by , also found by , , , , , , , , , , , , and
:
:
Pause claimAndRestake as well:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , , and
:
I agree with this issue, but assets can't be stolen, lost or compromised directly. Medium severity is more appropriate ()
:
:
Submitted by , also found by , , and
Rialto may cancel a minipool by calling , however the function sends AVAX to the minipool owner, and the owner may block receiving of AVAX, causing the call to cancelMinipoolByMultisig
to fail ():
Consider using the to return AVAX to owners of minipools that are canceled by Rialto.
:
:
Submitted by , also found by , , and
Multipools that successfully finished validation may be recreated by multisigs, before staked GGP and deposited AVAX have been withdrawn by minipool owners (). The function compounds deposited AVAX by adding the rewards earned during previous validation periods to the AVAX amounts deposited and requested from stakers ():
The function assumes that a node operator and liquid stakers earned an equal reward amount: compoundedAvaxNodeOpAmt
is calculated as the sum of the current AVAX deposit of the minipool owner and the node operator reward earned so far. However, liquid stakers get a smaller reward than node operators: the minipool node commission fee is applied to their share ():
Next, in the recreateMinipool
function, the assigned AVAX amount is increased by the amount borrowed from liquid stakers + the node operator amount, which is again wrong because the assigned AVAX amount can only be increased by the liquid stakers' reward share ():
:
:
:
:
:
:
:
:
:
Use liquid staker avax amount instead of node op amount:
Status: Mitigation not confirmed. Full details in , and also included in Mitigation Review section below.
Submitted by , also found by , , , , , , , , , , , , , , , , , , , , , and
:
I think might be a better primary. This one primarily depends on minipools going to staking->error which wouldn't actually happen unless Rialto made a mistake.
:
:
@Alex the Entreprenerd - Please note that the issue is not limited to Rialto doing a mistake, but it's actually possible to trick it by frontrunning the Rialto transaction as outlined in my finding: That's why the high severity was chosen initially.
:
Atomically recreate minipool so a node operator can't withdraw inbetween:
Status: Mitigation confirmed by and .
Submitted by , also found by and
:
:
Reset rewards start time in cancel minipool:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , and
:
:
:
has an interesting fix for this issue
:
:
:
Submitted by , also found by , , , , , , , , , and
:
:
:
Base cancelMinipool delay on minipool creation time not rewards start time:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , , , and
:
:
If staked GGP doesn't cover slash amount, slash it all:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , and
:
:
Added bounds for duration passed by Node Operator:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , , , , , , , , , , and
:
:
:
Per discussions had on , I don't believe that any specific MEV attack has been identified, however this finding does highlight a potential risk that a mistimed withdrawal could cause.
:
Submitted by
:
:
Submitted by , also found by , , , , and
The says that the NodeOps could be elegible for GGP rewards if they have a valid minipool. The problem is that if the MiniPool while registering the node as a validator, the NodeOp can get rewards even if the minipool had an error.
:
:
:
:
:
:
Remove the state transition from Staking to Error:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , , , , , , , , , , , and
The totalReleasedAssets
variable is updated on the function if someone calls the function before rewardsCycleEnd
the will be reverted because the totalReleasedAssets
may not include all the rewards.
:
:
Submitted by , also found by , , , , , , , , , , , , and
The MinipoolManager.recordStakingError
function () does not decrease the minipoolCount
of the staker.
This is bad because the minipoolCount
is used in ClaimNodeOp.calculateAndDistributeRewards
to determine if the rewardsStartTime
of the staker should be reset ().
This means that the staker is immediately eligible for rewards when he creates a minipool again whereas he should have to wait rewardsEligibilityMinSeconds
before he is eligible (which is 14 days at the moment) ().
:
:
We removed minipool count entirely:
Status: Mitigation confirmed by and .
Submitted by , also found by
The TokenggAVAX
contract () can be paused.
The whenTokenNotPaused
modifier is applied to the following functions ():
previewDeposit
, previewMint
, previewWithdraw
and previewRedeem
The issue is that TokenggAVAX
does not override the maxDeposit
and maxMint
functions () in the ERC4626Upgradable
contract like it does for maxWithdraw
and maxRedeem
.
The TokenggAVAX
contract is paused by calling Ocyticus.pauseEverything
()
TokenggAVAX.maxDeposit
returns type(uint256).max
()
However deposit
cannot be called with this value because it is paused (previewDeposit
reverts because of the whenTokenNotPaused
modifier) ()
The maxDeposit
and maxMint
functions should be overridden by TokenggAVAX
just like maxWithdraw
and maxRedeem
are overridden and return 0
when the contract is paused ().
:
:
:
:
:
:
Return correct value from maxMint and maxDeposit when the contract is paused:
Status: Mitigation confirmed by and .
Submitted by , also found by , , , , and
:
:
Prevents division by zero error blocking startRewardCycle():
Status: Mitigation confirmed, but a new medium severity issue was found. Full details in reports from and . Also included in Mitigation Review section below.
Submitted by , also found by
:
:
:
:
For this contest, 15 reports were submitted by wardens detailing low risk and non-critical issues. The by IllIllI received the top score from the judge.
The following wardens also submitted reports: , , , , , , , , , , , , , and .
The says that there will be no inflation for four years, but there is no code enforcing this.
0.2 ether should be 20%, not 2%. areas use 0.X as X0%.
Prior to solidity version 0.8.0, hitting an assert consumes the remainder of the transaction's available gas rather than returning it, as require()
/revert()
do. assert()
should be avoided even past solidity version 0.8.0 as its states that "The assert function creates an error of type Panic(uint256). ... Properly functioning code should never create a Panic, not even on invalid external input. If this happens, then there is a bug in your contract which you should fix".
performs similar operations, so the common code should be refactored to a function
Doing so will prevent .
See link for a description of this storage variable. While some contracts may not currently be sub-classed, adding the variable now protects against forgetting to add it in the future.
There are 13 instances of this issue. (For in-depth details on this and all further issues with multiple instances, please see the warden's .)
OpenZeppelin that the initializer
modifier be applied to constructors in order to avoid potential griefs, , or exploits. Ensure that the modifier is applied to the implementation contract. If the default constructor is currently being used, it should be changed to be an explicit one with the modifier applied.
Even can benefit from using readable constants instead of hex/numeric literals.
Consider defining in only one contract so that values cannot become out of sync when only one location is updated. A to store constants in a single location is to create an internal constant
in a library
. If the variable is a local cache of another contract's value, consider making the cache variable internal or private, which will require external users to query the contract with the source of truth, so that callers don't get out of sync.
Usually lines in source code are limited to characters. Today's screens are much larger so it's reasonable to stretch this in some cases. Since the files will most likely reside in GitHub, and GitHub starts using a scroll bar in all cases when the length is over characters, the lines below should be split when they reach that length
If the variable needs to be different based on which class it comes from, a view
/pure
function should be used instead (e.g. like ).
Large code bases, or code with lots of inline-assembly, complicated math, or complicated interactions between multiple contracts, should implement . Fuzzers such as Echidna require the test writer to come up with invariants which should not be violated under any circumstances, and the fuzzer tests various inputs and function calls to ensure that the invariants always hold. Even code with 100% code coverage can still have bugs due to the order of the operations a user performs, and fuzzers, with properly and extensively-written invariants, can close this testing gap significantly.
According to the , functions should be laid out in the following order :constructor()
, receive()
, fallback()
, external
, public
, internal
, private
, but the cases below do not follow this pattern.
The says that, within a contract, the ordering should be 1) Type declarations, 2) State variables, 3) Events, 4) Modifiers, and 5) Functions, but the contract(s) below do not follow this ordering.
Use abi.encode()
instead which will pad items to 32 bytes, which will (e.g. abi.encodePacked(0x123,0x456)
=> 0x123456
=> abi.encodePacked(0x1,0x23456)
, but abi.encode(0x123,0x456)
=> 0x0...1230...456
). "Unless there is a compelling reason, abi.encode
should be preferred". If there is only one argument to abi.encodePacked()
it can often be cast to bytes()
or bytes32()
.
Contracts to override their parents' functions and change the visibility from external
to public
.
Index event fields make the field more quickly accessible that parse events. However, note that each index field costs extra gas during emission, so it's not necessarily best to index the maximum allowed per event (three fields). Each event
should use three indexed
fields if there are three or more fields, and gas usage is not particularly of concern for the events in question. If there are fewer than three fields, all of the fields should be indexed.
:
:
6 Low, 15 Refactor, 15 Non-Critical, including downgraded findings ( & ).
For this contest, 12 reports were submitted by wardens detailing gas optimizations. The by NoamYakov received the top score from the judge.
The following wardens also submitted reports: , , , , , , , , , , and .
There are 2 instances of this issue. (For in-depth details on this and all further gas optimizations with multiple instances, please see the warden's .)
The unchecked
keyword is new in solidity version 0.8.0, so this only applies to that version or higher, which these instances are. This saves 30-40 gas .
public
/external
function names and public
member variable names can be optimized to save gas. See link for an example of how it works. Below are the interfaces/abstract contracts that can be optimized so that the most frequently-called functions use the least amount of gas possible during method lookup. Method IDs that have two leading zero bytes can save 128 gas each during deployment, and renaming functions to have lower method IDs will save 22 gas per call, .
Custom errors are available from solidity version 0.8.4. Custom errors save each time they're hit by . Not defining the strings also save deployment gas.
The instances below point to the second+ access of a value inside a mapping/array, within a function. Caching a mapping's value in a local storage
or calldata
variable when the value is accessed , saves ~42 gas per access due to not having to recalculate the key's keccak256 hash (Gkeccak256 - 30 gas) and that calculation's associated stack operations. Caching an array's struct avoids recalculating the array offsets into memory/calldata.
Using the addition operator instead of plus-equals saves . Subtructions act the same way.
<x> / 2
is the same as <x> >> 1
. While the compiler uses the SHR
opcode to accomplish both, the version that uses division incurs an overhead of due to JUMP
s to and from a compiler utility function that introduces checks which can be avoided by using unchecked {}
around the division by two.
See which describes the fact that there is a larger deployment gas cost, but with enough runtime calls, the change ends up being cheaper by 3 gas.
:
:
:
:
:
Following the C4 audit contest, 3 wardens (, RaymondFam, and ) reviewed the mitigations for all identified issues. Additional details can be found within the .
H-01: Mitigation confirmed with comments (full details in )
H-03: Mitigation confirmed by and
H-05: Mitigation confirmed by and
M-01: Mitigation confirmed with comments (full details in )
M-02: Mitigation confirmed by and
M-03: Mitigation confirmed by and
M-05: Mitigation confirmed by and
M-09: Mitigation confirmed by and
M-10: Mitigation confirmed by and
M-12: Mitigation confirmed by and
M-13: Mitigation confirmed by and
M-14: Mitigation confirmed by and
M-17: Mitigation confirmed by and
M-19: Mitigation confirmed by and
M-20: Mitigation confirmed by and
H-04:
The mitigation added a new function recordStakingEndThenMaybeCycle()
and handled recordStakingEnd()
and recreateMiniPool()
in an atomic way.
With this mitigation, the state flow is now as below and it is impossible for a node operator to interfere the recreation process.
But this mitigation created another minor issue that the node operators have risks to be slashed in an unfair way.
Now let us consider the timeline. One validation cycle in the whole sense contains several steps as below.
Let us assume it is somehow possible that startTime[1] > endTime[0]
, i.e., the multisig failed to start the next cycle at the exact the same timestamp to the previous end time. This is quite possible due to various reasons because there are external processes included. In this case the timeline will look as below.
As an extreme example, let us say the node operator created a minipool with duration of 42 days (with 3 cycles in mind) and it took 12 days to start the second cycle. When the recordStakingEndThenMaybeCycle()
(finishing the second cycle) was called, two cases are possible.
Assume it is 100% guaranteed that startTime[n+1]=endTime[n]
for all cycles.
The timeline will look as below and we can say the second case of the above scenario still exists if the node operator didn't specify the duration to be a complete multiple of 14 days. (365 days is not!)
Then the last cycle end will be later than initialStartTime + duration
and the node op can be slashed in an unfair way again.
So even assuming the perfect condition, the protocol works in kind of unfair way for node operators.
:
Per full discussion with sponsor and warden , Medium seems like the most appropriate Severity, the finding is valid though in that the FSM can behave in an unintended way due to lack of modulo math.
Submitted by RaymondFam, also found by and
H-06:
:
:
:
:
M-08:
The atomic transaction is going to fail if compoundedAvaxAmt > ggAVAX.amountAvailableForStaking()
after all due to situations like liquid stakers have been actively calling .
Under normal circumstances, is going to be adequate enough to cater for compoundedAvaxNodeOpAmt
. This should not be easily forfeited without first checking whether or not ggAVAX.amountAvailableForStaking()
is greater than compoundedAvaxNodeOpAmt
.
:
Per full discussion with sponsor and warden , I believe we can agree with the validity of the finding but we're unclear in terms of resolution.
:
Submitted by hansfriese, also found by
M-21:
If no multisig is enabled, the mitigation sends the rewards to the MultisigManager
and it makes sense.
But this created another issue. There is no way to retrieve the rewards back from the MultisigManager
.
:
: