name stringlengths 5 231 | severity stringclasses 3
values | description stringlengths 107 68.2k | recommendation stringlengths 12 8.75k ⌀ | impact stringlengths 3 11.2k ⌀ | function stringlengths 15 64.6k |
|---|---|---|---|---|---|
On liquidation, if netPnLE36 <= 0, the premium paid by the liquidator is locked in the contract. | high | When liquidating a position, the liquidator is required to pay premium to Lender, which is accumulated in sharingProfitTokenAmts together with Lender's profit and paid to Lender in `_shareProfitsAndRepayAllDebts()`.\\n```\\n (\\n netPnLE36,\\n lenderProfitUSDValueE36,\\n borrow... | Modify `shareProfitsAndRepayAllDebts()` as follows:\\n```\\n function _shareProfitsAndRepayAllDebts(\\n address _positionManager,\\n address _posOwner,\\n uint _posId,\\n int _netPnLE36,\\n ... | null | ```\\n (\\n netPnLE36,\\n lenderProfitUSDValueE36,\\n borrowTotalUSDValueE36,\\n positionOpenUSDValueE36,\\n sharingProfitTokenAmts ) = calcProfitInfo(_positionManager, _user, _posId);\\n // 2. add liquidation premium to the share... |
The liquidated person can make the liquidator lose premium by adding collateral in advance | high | When the position with debtRatioE18 >= 1e18 or startLiqTimestamp ! = 0, the position can be liquidated. On liquidation, the liquidator needs to pay premium, but the profit is related to the position's health factor and deltaTime, and when discount == 0, the liquidator loses premium.\\n```\\n uint deltaTime;\... | Consider having the liquidated person bear the premium, or at least have the liquidator use the minDiscount parameter to set the minimum acceptable discount. | null | ```\\n uint deltaTime;\\n // 1.1 check the amount of time since position is marked\\n if (pos.startLiqTimestamp > 0) {\\n deltaTime = Math.max(deltaTime, block.timestamp - pos.startLiqTimestamp);\\n }\\n // 1.2 check the amount of time since positio... |
First depositor can steal asset tokens of others | high | The first depositor can be front run by an attacker and as a result will lose a considerable part of the assets provided. When the pool has no share supply, in `_mintInternal()`, the amount of shares to be minted is equal to the assets provided. An attacker can abuse of this situation and profit of the rounding down op... | When _totalSupply == 0, send the first min liquidity LP tokens to the zero address to enable share dilution Another option is to use the ERC4626 implementation(https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol#L199C14-L208) from OZ. | null | ```\\n function _mintInternal(address _receiver, uint _balanceIncreased, uint _totalAsset\\n ) internal returns (uint mintShares) {\\n unfreezeTime[_receiver] = block.timestamp + mintFreezeInterval;\\n if (freezeBuckets.interval > 0) {\\n FreezeBuckets.addToFreezeBuc... |
The attacker can use larger dust when opening a position to perform griefing attacks | high | When opening a position, unused assets are sent to dustVault as dust, but since these dust are not subtracted from inputAmt, they are included in the calculation of positionOpenUSDValueE36, resulting in a small netPnLE36, which can be used by an attacker to perform a griefing attack.\\n```\\n uint inputTotal... | Consider subtracting dust from inputAmt when opening a position. | null | ```\\n uint inputTotalUSDValueE36;\\n for (uint i; i < openTokenInfos.length; ) {\\n inputTotalUSDValueE36 += openTokenInfos[i].inputAmt * tokenPriceE36s[i];\\n borrowTotalUSDValueE36 += openTokenInfos[i].borrowAmt * tokenPriceE36s[i];\\n un... |
An attacker can increase liquidity to the position's UniswapNFT to prevent the position from being closed | high | UniswapV3NPM allows the user to increase liquidity to any NFT.\\n```\\n function increaseLiquidity(IncreaseLiquidityParams calldata params)\\n external payable override checkDeadline(params.deadline)\\n returns (\\n uint128 liquidity, uint256 amount0, ui... | Consider decreasing the actual liquidity(using uniswapV3NPM.positions to get it) of the NFT in `_redeemPosition()`, instead of the initial liquidity | null | ```\\n function increaseLiquidity(IncreaseLiquidityParams calldata params)\\n external payable override checkDeadline(params.deadline)\\n returns (\\n uint128 liquidity, uint256 amount0, uint256 amount1)\\n {\\n Position storage pos... |
SwapHelper.getCalldata should check whitelistedRouters[_router] | medium | `SwapHelper.getCalldata()` returns data for swap based on the input, and uses whitelistedRouters to limit the _router param. The issue here is that when `setWhitelistedRouters()` sets the _routers state to false, it does not reset the data in routerTypes and swapInfos, which results in the router still being available ... | Consider checking whitelistedRouters[_router] in SwapHelper.getCalldata() | null | ```\\n for (uint i; i < _statuses.length; ) {\\n whitelistedRouters[_routers[i]] = _statuses[i];\\n if (_statuses[i]) {\\n routerTypes[_routers[i]] = _types[i];\\n emit SetRouterType(_routers[i], _types[i]);\\n }\\n emit SetWhitelistedRouter(... |
The swap when closing a position does not consider shareProfitAmts | medium | When closing a position, token swap is performed to ensure that the closer can repay the debt, for example, when operation == EXACT_IN, tokens of borrowAmt are required to be excluded from the swap, and when operation == EXACT_OUT, tokens of borrowAmt are required to be swapped. The issue here is that the closer needs ... | Consider taking shareProfitAmts into account when calculating swapAmt | null | ```\\n for (uint i; i < swapParams.length; ) {\\n // find excess amount after repay\\n uint swapAmt = swapParams[i].operation == SwapOperation.EXACT_IN\\n ? IERC20(swapParams[i].tokenIn).balanceOf(address(this)) - openTokenInfos[i].borrowAmt\\n : openTokenInfos[i].borrowAmt - I... |
The freeze mechanism reduces the borrowableAmount, which reduces Lender's yield | medium | The contract has two freeze intervals, mintFreezeInterval and freezeBuckets.interval, the former to prevent users from making flash accesses and the latter to prevent borrowers from running out of funds. Both freeze intervals are applied when a user deposits, and due to the difference in unlocking time, it significantl... | Consider making mintFreezeInterval >= 2 * freezeBuckets.interval, which makes unfreezeTime greater than the unfreeze time of freezeBuckets. | null | ```\\n function _mintInternal(address _receiver,uint _balanceIncreased, uint _totalAsset\\n ) internal returns (uint mintShares) {\\n unfreezeTime[_receiver] = block.timestamp + mintFreezeInterval;\\n if (freezeBuckets.interval > 0) {\\n FreezeBuckets.addToFreezeBuckets(free... |
A malicious operator can drain the vault funds in one transaction | high | The vault operator can swap tokens using the `trade()` function. They pass the following structure for each trade:\\n```\\n struct tradeInput { \\n address spendToken;\\n address receiveToken;\\n uint256 spendAmt;\\n uint256 receiveAmtMin;\\n ... | The contract should enforce sensible slippage parameters. | null | ```\\n struct tradeInput { \\n address spendToken;\\n address receiveToken;\\n uint256 spendAmt;\\n uint256 receiveAmtMin;\\n address routerAddress;\\n uint256 pathIndex;\\n }\\n```\\n |
A malicious operator can steal all user deposits | high | In the Orbital architecture, each Vault user has a numerator which represents their share of the vault holdings. The denominator is by design the sum of all numerators of users, an invariant kept at deposits and withdrawals. For maximum precision, the denominator should be a very large value. Intuitively, numerators co... | Consider checking that user's received deltaN is reasonable. Calculate the expected withdrawable value (deltaN / denominator * balance), and verify that is close enough to the deposited amount. | null | ```\\n if (D == 0) { //initial deposit\\n uint256 sumDenoms = 0; \\n for (uint256 i = 0; i < tkns.length; i++) {\\n sumDenoms += \\n AI.getAllowedTokenInfo(tkns[i]).initialDenominator;\\n }\\n ... |
Removing a trade path in router will cause serious data corruption | medium | The RouterInfo represents a single UniV3-compatible router which supports a list of token paths. It uses the following data structures:\\n```\\n mapping(address => mapping(address => listInfo)) private allowedPairsMap;\\n pair[] private allowedPairsList;\\n```\\n\\n```\\n struct listIn... | Update the listPosition member of the last pair in the list, before repositioning it. | null | ```\\n mapping(address => mapping(address => listInfo)) private allowedPairsMap;\\n pair[] private allowedPairsList;\\n```\\n |
Attacker can DOS deposit transactions due to strict verifications | medium | When users deposit funds to the Vault, it verifies that the proportion between the tokens inserted to the vault matches the current vault token balances.\\n```\\n uint256[] memory balances = vlt.balances();\\n //ensure deposits are in the same ratios as the vault's current balances\\n require(fun... | Loosen the restriction on deposit ratios. A DOS attack should cost an amount that the vault creditors would be happy to live with. | null | ```\\n uint256[] memory balances = vlt.balances();\\n //ensure deposits are in the same ratios as the vault's current balances\\n require(functions.ratiosMatch(balances, amts), "ratios don't match");\\n```\\n |
User deposits can fail despite using the correct method for calculation of deposit amounts | medium | Users can use the `getAmtsNeededForDeposit()` function to get the amount of tokens that maintain the desired proportion for vault deposits. It will perform a calculation very similar to the one in `ratiosMatch()`, which will verify the deposit.\\n```\\n for (uint256 i = 0; i < balances.length; i++) {\\n ... | Calculation amounts needed using the ratio between largest balance and the deposit amount. This would line up the numbers as verification would expect. | null | ```\\n for (uint256 i = 0; i < balances.length; i++) {\\n if (i == indexOfReferenceToken) {\\n amtsNeeded[i] = amtIn;\\n } else {\\n // amtsNeeded[i] = (amtIn * balances[i]) / \\n balances[indexOfReferenceToken];\\n amtsNeeded[i] ... |
Several popular ERC20 tokens are incompatible with the vault due to MAX approve | low | There are several instances where the vault approves use of funds to the manager or a trade router. It will set approval to MAX_UINT256.\\n```\\n for (uint i = 0; i < tokens.length; i++) {\\n //allow vault manager to withdraw tokens\\n IERC20(tokens[i]).safeIncreaseAllowance(ownerIn, \... | Consider setting allowance to UINT_96. Whenever the allowance is consumed, perform re-approval up to UINT_96. | null | ```\\n for (uint i = 0; i < tokens.length; i++) {\\n //allow vault manager to withdraw tokens\\n IERC20(tokens[i]).safeIncreaseAllowance(ownerIn, \\n type(uint256).max); \\n }\\n```\\n |
Attacker can freeze deposits and withdrawals indefinitely by submitting a bad withdrawal | high | Users request to queue a withdrawal using the function below in Vault.\\n```\\n function addWithdrawRequest(uint256 _amountMLP, address _token) external {\\n require(isAcceptingToken(_token), "ERROR: Invalid token");\\n require(_amountMLP != 0, "ERROR: Invalid amount");\\n \\n ... | Vault should take custody of user's LP tokens when they request withdrawals. If the entire withdrawal cannot be satisfied, it can refund some tokens back to the user. | null | ```\\n function addWithdrawRequest(uint256 _amountMLP, address _token) external {\\n require(isAcceptingToken(_token), "ERROR: Invalid token");\\n require(_amountMLP != 0, "ERROR: Invalid amount");\\n \\n address _withdrawer = msg.sender;\\n // Get the pending buffe... |
Removal of Multisig members will corrupt data structures | medium | The Mozaic Multisig (the senate) can remove council members using the TYPE_DEL_OWNER operation:\\n```\\n if(proposals[_proposalId].actionType == TYPE_DEL_OWNER) {\\n (address _owner) = abi.decode(proposals[_proposalId].payload, (address));\\n require(contains(_owner) != 0, "Invalid owner ad... | Fix the `contains()` function to return the correct index of _owner | null | ```\\n if(proposals[_proposalId].actionType == TYPE_DEL_OWNER) {\\n (address _owner) = abi.decode(proposals[_proposalId].payload, (address));\\n require(contains(_owner) != 0, "Invalid owner address");\\n uint index = contains(_owner);\\n for (uint256 i = index; i ... |
Attacker could abuse victim's vote to pass their own proposal | medium | Proposals are created using submitProposal():\\n```\\n function submitProposal(uint8 _actionType, bytes memory _payload) public onlyCouncil {\\n uint256 proposalId = proposalCount;\\n proposals[proposalId] = Proposal(msg.sender,_actionType, \\n _payload, 0, false);... | Calculate proposalId as a hash of the proposal properties. This way, votes cannot be misdirected. | null | ```\\n function submitProposal(uint8 _actionType, bytes memory _payload) public onlyCouncil {\\n uint256 proposalId = proposalCount;\\n proposals[proposalId] = Proposal(msg.sender,_actionType, \\n _payload, 0, false);\\n proposalCount += 1;\\n ... |
MozToken will have a much larger fixed supply than intended. | medium | MozToken is planned to be deployed on all supported chains. Its total supply will be 1B. However, its constructor will mint 1B tokens on each deployment.\\n```\\n constructor( address _layerZeroEndpoint, uint8 _sharedDecimals\\n ) OFTV2("Mozaic Token", "MOZ", _sharedDecimals, _layerZeroEndpoint) {\\n ... | Pass the minted supply as a parameter. Only on the main chain, mint 1B tokens. | null | ```\\n constructor( address _layerZeroEndpoint, uint8 _sharedDecimals\\n ) OFTV2("Mozaic Token", "MOZ", _sharedDecimals, _layerZeroEndpoint) {\\n _mint(msg.sender, 1000000000 * 10 ** _sharedDecimals);\\n isAdmin[msg.sender] = true;\\n }\\n```\\n |
Theoretical reentrancy attack when TYPE_MINT_BURN proposals are executed | low | The senate can pass a proposal to mint or burn tokens.\\n```\\n if(proposals[_proposalId].actionType == TYPE_MINT_BURN) {\\n (address _token, address _to, uint256 _amount, bool _flag) = \\n abi.decode(proposals[_proposalId].payload, (address, address, uint256, bool));\\n if(_flag) {\... | Follow the Check-Effects-Interactions design pattern, mark the function as executed at the start. | null | ```\\n if(proposals[_proposalId].actionType == TYPE_MINT_BURN) {\\n (address _token, address _to, uint256 _amount, bool _flag) = \\n abi.decode(proposals[_proposalId].payload, (address, address, uint256, bool));\\n if(_flag) {\\n IXMozToken(_token).mint(_amount, _to);\\n ... |
XMozToken permits transfers from non-whitelisted addresses | low | The XMozToken is documented to forbid transfers except from whitelisted addresses or mints.\\n```\\n /**\\n * @dev Hook override to forbid transfers except from whitelisted \\n addresses and minting\\n */\\n function _beforeTokenTransfer(address from, address to, uint256 \\n /*... | Remove the additional check in `_beforeTokenTransfer()`, or update the documentation accordingly. | null | ```\\n /**\\n * @dev Hook override to forbid transfers except from whitelisted \\n addresses and minting\\n */\\n function _beforeTokenTransfer(address from, address to, uint256 \\n /*amount*/) internal view override {\\n require(from == address(0) || _transferWh... |
XMozToken cannot be added to its own whitelist | low | By design, XMozToken should always be in the whitelist. However, `updateTransferWhitelist()` implementation forbids both removal and insertion of XMozToken to the whitelist.\\n```\\n function updateTransferWhitelist(address account, bool add) external onlyMultiSigAdmin {\\n require(accoun... | Move the require statement into the else clause. | null | ```\\n function updateTransferWhitelist(address account, bool add) external onlyMultiSigAdmin {\\n require(account != address(this), "updateTransferWhitelist: \\n Cannot remove xMoz from whitelist");\\n if(add) _transferWhitelist.add(account);\\... |
User fee token balance can be drained in a single operation by a malicious bot | high | In `_buildFeeExecutable()`, BrahRouter calculates the total fee charged to the wallet. It uses tx. gas price to get the gas price specified by the bot.\\n```\\n if (feeToken == ETH) \\n {uint256 totalFee = (gasUsed + GAS_OVERHEAD_NATIVE) * tx.gasprice;\\n totalFee = _applyMultiplier(totalFee);\\n return (t... | Use a gas oracle or a capped priority fee to ensure an inflated gas price down not harm the user. | null | ```\\n if (feeToken == ETH) \\n {uint256 totalFee = (gasUsed + GAS_OVERHEAD_NATIVE) * tx.gasprice;\\n totalFee = _applyMultiplier(totalFee);\\n return (totalFee, recipient, TokenTransfer._nativeTransferExec(recipient, totalFee));\\n } else {uint256 totalFee = (gasUsed + GAS_OVERHEAD_ERC20) * tx.... |
Users can drain Gelato deposit at little cost | high | In Console automation, fees are collected via the `claimExecutionFees()` modifier:\\n```\\n modifier claimExecutionFees(address _wallet) {\\n uint256 startGas = gasleft();\\n _;\\n if (feeMultiplier > 0) {\\n address feeToken = FeePayer._feeToken(_wallet);\\n uint256 gasUsed = startGas -gasleft();\\n ... | When calculating fees in buildFeeExecutable(), there are assumptions about the gas cost of an ERC20 transfer and a native transfer.\\n```\\n // Keeper network overhead -150k\\n uint256 internal constant GAS_OVERHEAD_NATIVE = 150_000 + 40_000;\\n uint256 internal constant GAS_OVERHEAD_ERC20 = 150_000 + 90... | null | ```\\n modifier claimExecutionFees(address _wallet) {\\n uint256 startGas = gasleft();\\n _;\\n if (feeMultiplier > 0) {\\n address feeToken = FeePayer._feeToken(_wallet);\\n uint256 gasUsed = startGas -gasleft();\\n (uint256 feeAmount, address recipient, Types.Executable memory feeTransferTxn)=Fee... |
Attackers can drain users over time by donating negligible ERC20 amount | high | In the Console automation model, a strategy shall keep executing until its trigger check fails. For DCA strategies, the swapping trigger is defined as:\\n```\\n function canInitSwap(address subAccount, address inputToken, uint256 interval, uint256 lastSwap)\\n external view returns (bool)\\n {\\n ... | Define a DUST_AMOUNT, below that amount exit is allowed, while above that amount swap execution is allowed. User should only stand to gain from another party donating ERC20 tokens to their account. | null | ```\\n function canInitSwap(address subAccount, address inputToken, uint256 interval, uint256 lastSwap)\\n external view returns (bool)\\n {\\n if (hasZeroBalance(subAccount, inputToken)) \\n { return false;\\n }\\n return ((lastSwap + interval) < block.timestamp);\\n ... |
When FeePayer is subsidizing, users can steal gas | medium | ```\\nThe feeMultiplier enables the admin to subsidize or upcharge for the automation service.\\n/**\\n⦁ @notice feeMultiplier represents the total fee to be charged on the transaction\\n⦁ Is set to 100% by default\\n⦁ @dev In case feeMultiplier is less than BASE_BPS, fees charged will be less than 100%,\\n⦁ subsidizin... | The root cause is that the gasUsed amount is subsidized as well as GAS_OVERHEAD_NATIVE, which is the gas reserved for the delivery from Gelato executors. By subsidizing only the Gelato gas portion, users will not gain from gas minting attacks, while the intention of improving user experience is maintained. | null | ```\\nThe feeMultiplier enables the admin to subsidize or upcharge for the automation service.\\n/**\\n⦁ @notice feeMultiplier represents the total fee to be charged on the transaction\\n⦁ Is set to 100% by default\\n⦁ @dev In case feeMultiplier is less than BASE_BPS, fees charged will be less than 100%,\\n⦁ subsidizin... |
Strategy actions could be executed out of order due to lack of reentrancy guard | medium | The Execute module performs automation of the fetched Executable array on wallet subaccounts.\\n```\\n function _executeAutomation( address _wallet, address _subAccount, address _strategy,\\n Types.Executable[] memory _actionExecs ) internal {\\n uint256 actionLen = _actionExecs.length;\\n if (action... | Add a reentrancy guard for `executeAutomationViaBot()` and `executeTrustedAutomation()`. | null | ```\\n function _executeAutomation( address _wallet, address _subAccount, address _strategy,\\n Types.Executable[] memory _actionExecs ) internal {\\n uint256 actionLen = _actionExecs.length;\\n if (actionLen == 0) {\\n revert InvalidActions();\\n } else {\\n uint256 idx = 0;\\n... |
Anyone can make creating strategies extremely expensive for the user | medium | In Console architecture, users can deploy spare subaccounts (Gnosis Safes) so that when they will subscribe to a strategy most of the gas spending would have been spent at a low-gas phase.\\n```\\n function deploySpareSubAccount(address _wallet) external { address subAccount =\\n SafeDeployer(addressProvider.... | Limit the amount of spare subaccount to something reasonable, like 10 Team Response: Removing the spare subaccount deployment Mitigation review: Attack surface has been removed. | null | ```\\n function deploySpareSubAccount(address _wallet) external { address subAccount =\\n SafeDeployer(addressProvider.safeDeployer()).deploySubAccount(_wallet);\\n subAccountToWalletMap[subAccount] = _wallet; walletToSubAccountMap[_wallet].push(subAccount);\\n // No need to update subAc... |
DCA Strategies build orders that may not be executable, wasting fees | medium | In `_buildInitiateSwapExecutable()`, DCA strategies determine the swap parameters for the CoW Swap. The code has recently been refactored so that there may be more than one active order simultaneously. The issue is that the function assumes the user's entire ERC20 balance to be available for the order being built.\\n``... | Ensure only one swap can be in-flight at a time, or deduct the in-flight swap amounts from the current balance. | null | ```\\n // Check if enough balance present to swap, else swap entire balance\\n uint256 amountIn = (inputTokenBalance < params.amountToSwap) ? \\n inputTokenBalance : params.amountToSwap;\\n```\\n |
User will lose all Console functionality when upgrading their wallet and an upgrade target has not been set up | medium | Console supports upgrading of the manager wallet using the `upgradeWalletType()` function.\\n```\\n function upgradeWalletType() external {\\n if (!isWallet(msg.sender)) \\n revert WalletDoesntExist(msg.sender); uint8 fromWalletType = _walletDataMap[msg.sender].walletType;\\n _setWalletType(msg.sender, _upg... | When settings a new wallet type, make sure the new type is not zero. | null | ```\\n function upgradeWalletType() external {\\n if (!isWallet(msg.sender)) \\n revert WalletDoesntExist(msg.sender); uint8 fromWalletType = _walletDataMap[msg.sender].walletType;\\n _setWalletType(msg.sender, _upgradablePaths[fromWalletType]);\\n emit WalletUpgraded(msg.sender, fromWalletType,\\n _u... |
Rounding error causes an additional iteration of DCA strategies | low | Both CoW strategies receive an interval and total amountIn of tokens to swap. They calculate the amount per iteration as below:\\n```\\n Types.TokenRequest[] memory tokens = new Types.TokenRequest[](1); \\n tokens[0] = Types.TokenRequest({token: inputToken, amount: amountIn});\\n amountIn = amountIn / itera... | Change the amount requested from the management wallet to amountIn / iterations * iterations. | null | ```\\n Types.TokenRequest[] memory tokens = new Types.TokenRequest[](1); \\n tokens[0] = Types.TokenRequest({token: inputToken, amount: amountIn});\\n amountIn = amountIn / iterations;\\n StrategyParams memory params = StrategyParams({ tokenIn: inputToken,\\n tokenOut: outputToken, amountToSwap: amountI... |
Fee mismatch between contracts can make strategies unusable | low | In CoW Swap strategies, fee is set in the strategy contracts and then passed to `initiateSwap()`. It is built in _buildInitiateSwapExecutable():\\n```\\n // Generate executable to initiate swap on DCACoWAutomation return Types.Executable({\\n callType: Types.CallType.DELEGATECALL, target: dcaCoWAutomation,\\n ... | Enforce the same constraints on the fee percentage in both contracts, or remove the check from one of them as part of a simplified security model. | null | ```\\n // Generate executable to initiate swap on DCACoWAutomation return Types.Executable({\\n callType: Types.CallType.DELEGATECALL, target: dcaCoWAutomation,\\n value: 0,\\n data: abi.encodeCall( DCACoWAutomation.initiateSwap,\\n (params.tokenIn, params.tokenOut, swapRecipient, amountIn, minAmoun... |
Reentrancy protection can likely be bypassed | high | The KeyManager offers reentrancy protection for interactions with the associated account. Through the LSP20 callbacks or through the `execute()` calls, it will call `_nonReentrantBefore()` before execution, and `_nonReentrantAfter()` post-execution. The latter will always reset the flag signaling entry.\\n```\\n fun... | In `_nonReentrantAfter()`, the flag should be returned to the original value before reentry, rather than always setting it to false. | null | ```\\n function _nonReentrantAfter() internal virtual {\\n // By storing the original value once again, a refund is triggered \\n (see // https://eips.ethereum.org/EIPS/eip-2200)\\n _reentrancyStatus = false;\\n }\\n```\\n |
LSP20 verification library deviates from spec and will accept fail values | medium | The functions `lsp20VerifyCall()` and `lsp20VerifyCallResult()` are called to validate the owner accepts some account interaction. The specification states they must return a specific 4 byte magic value. However, the implementation will accept any byte array that starts with the required magic value.\\n```\\n functi... | Verify that the return data length is 32 bytes (the 4 bytes are extended by the compiler), and that all other bytes are zero. | null | ```\\n function _verifyCall(address logicVerifier) internal virtual returns (bool verifyAfter) {\\n (bool success, bytes memory returnedData) = logicVerifier.call(\\n abi.encodeWithSelector(ILSP20.lsp20VerifyCall.selector, msg.sender, msg.value, msg.data)\\n );\\n if (!success) _revert(false,... |
Deviation from spec will result in dislocation of receiver delegate | medium | The LSP0 `universalReceiver()` function looks up the receiver delegate by crafting a mapping key type.\\n```\\n bytes32 lsp1typeIdDelegateKey = LSP2Utils.generateMappingKey(\\n _LSP1_UNIVERSAL_RECEIVER_DELEGATE_PREFIX, bytes20(typeId));\\n```\\n\\nMapping keys are constructed of a 10-byte prefix, 2 zero bytes and a 2... | Document the trimming action in the LSP0 specification. | null | ```\\n bytes32 lsp1typeIdDelegateKey = LSP2Utils.generateMappingKey(\\n _LSP1_UNIVERSAL_RECEIVER_DELEGATE_PREFIX, bytes20(typeId));\\n```\\n |
KeyManager ERC165 does not support LSP20 | medium | LSP6KeyManager supports LSP20 call verification. However, in `supportInterface()` it does not return the LSP20 interfaceId.\\n```\\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n return\\n interfaceId == _INTERFACEID_LSP6 || interfaceId == _INTERFACEID_ERC1271 ... | Insert another supported interfaceId under `supportsInterface()`. | null | ```\\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n return\\n interfaceId == _INTERFACEID_LSP6 || interfaceId == _INTERFACEID_ERC1271 ||\\n super.supportsInterface(interfaceId);\\n }\\n```\\n |
LSP0 ownership functions deviate from specification and reject native tokens | low | The LSP specifications define the following functions for LSP0:\\n```\\n function transferOwnership(address newPendingOwner) external payable;\\n function renounceOwnership() external payable;\\n```\\n\\nHowever, their implementations are not payable.\\n```\\n function transferOwnership(address newOwner) publi... | Remove the payable keyword in the specification for the above functions, or make the implementations payable | null | ```\\n function transferOwnership(address newPendingOwner) external payable;\\n function renounceOwnership() external payable;\\n```\\n |
Transfers of vaults from an invalid source are not treated correctly by receiver delegate | low | In the universalReceiver() function, if the notifying contract does not support LSP9, yet the typeID corresponds to an LSP9 transfer, the function will return instead of reverting.\\n```\\n if (\\n mapPrefix == _LSP10_VAULTS_MAP_KEY_PREFIX && notifier.code.length > 0 &&\\n !notifier.supportsERC165Interf... | Revert when dealing with transfers that cannot be valid. | null | ```\\n if (\\n mapPrefix == _LSP10_VAULTS_MAP_KEY_PREFIX && notifier.code.length > 0 &&\\n !notifier.supportsERC165InterfaceUnchecked(_INTERFACEID_LSP9)\\n ) {\\n return "LSP1: not an LSP9Vault ownership transfer";\\n }\\n```\\n |
Relayer can choose amount of gas for delivery of message | low | LSP6 supports relaying of calls using a supplied signature. The encoded message is defined as:\\n```\\n bytes memory encodedMessage = abi.encodePacked( LSP6_VERSION,\\n block.chainid,\\n nonce,\\n msgValue,\\n payload\\n );\\n```\\n\\nThe message doesn't include a g... | Signed message should include the gas amount passed. Care should be taken to verify there is enough gas in the current state for the gas amount not to be truncated due to the 63/64 rule. | null | ```\\n bytes memory encodedMessage = abi.encodePacked( LSP6_VERSION,\\n block.chainid,\\n nonce,\\n msgValue,\\n payload\\n );\\n```\\n |
_calculateClaim() does not distribute boost emissions correctly | high | The function `_calculateClaim()` is responsible for the calculations of the amount of emissions a specific veSatin is entitled to claim. The idea is to distribute emissions only to veSatin tokens locked for more than minLockDurationForReward and only for the extra time the veSatin is locked for on top of minLockDuratio... | The variable weekCursor should be used instead of oldUserPoint.ts in the if condition:\\n```\\n if ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\\n```\\n | null | ```\\n if ((lockEndTime - oldUserPoint.ts) > (minLockDurationForReward)) {\\n toDistribute +=\\n (balanceOf * tokensPerWeek[weekCursor]) / veSupply[weekCursor];\\n weekCursor += WEEK;\\n }\\n```\\n |
Users will be unable to claim emissions from veSatin tokens if they withdraw it or merge it | high | The function `_calculateClaim()` uses the variable lockEndTime when checking if a veSatin is entitled to emissions for a particular week (code with mitigation from TRST-H-1):\\n```\\n if ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\\n toDistribute +=\\n (balanceOf * tokensPerW... | In the `withdraw()` and `merge()` functions, call `claim()` in VeDist.sol to claim emissions before setting the lock end timestamp to 0. In `merge()` this is only necessary for the veSatin passed as _from | null | ```\\n if ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\\n toDistribute +=\\n (balanceOf * tokensPerWeek[weekCursor]) / veSupply[weekCursor];\\n weekCursor += WEEK;\\n }\\n```\\n |
It's never possible to vote for new pools until setMaxVotesForPool() is called | high | The function `_vote()` allows voting on a pool only when the current amount of votes plus the new votes is lower or equal to the value returned by _calculateMaxVotePossible():\\n```\\n require(_poolWeights <= _calculateMaxVotePossible(_pool), "Max votes exceeded");\\n```\\n\\nHowever, `_calculateMaxVotePossible(... | In `createGauge()` and `createGauge4Pool()` set maxVotesForPool for the pool the gauge is being created for to 100. | null | ```\\n require(_poolWeights <= _calculateMaxVotePossible(_pool), "Max votes exceeded");\\n```\\n |
The protocol might transfer extra SATIN emissions to veSatin holders potentially making SatinVoter.sol insolvent | high | The function `_distribute()` in SatinVoter.sol is generally responsible for distributing weekly emissions to a gauge based on the percentage of total votes the associated pool received. In particular, it's called by `updatePeriod()` (as per fix TRST-H-4) on the gauge associated with the Satin / $CASH pool. The variable... | Adjust claimable[gauge] after calculating veShare and calculate veShare only if the msg.sender is SatinMinter.sol to prevent potential attackers from manipulating the value by repeatedly calling _distribute():\\n```\\n if (SATIN_CASH_LP_GAUGE == _gauge && msg.sender == minter) {\\n veShare = calculateSatinCas... | null | ```\\n uint _claimable = claimable[_gauge];\\n if (SATIN_CASH_LP_GAUGE == _gauge) {\\n veShare = calculateSatinCashLPVeShare(_claimable);\\n _claimable -= veShare;\\n }\\n if (_claimable > IMultiRewardsPool(_gauge).left(token) && _claimable / DURATION > 0) {\\n claimable[_ga... |
It's possible to drain all the funds from ExternalBribe | high | The function `earned()` is used to calculate the amount rewards owed to a tokenId, to do so it performs a series operations over a loop and then it always executes:\\n```\\n Checkpoint memory cp = checkpoints[tokenId][_endIndex];\\n uint _lastEpochStart = _bribeStart(cp.timestamp);\\n uint _lastEpochEnd ... | The function `earned()` is taken from the Velodrome protocol and is known to have issues. Because it uses the convoluted logic of looping over votes to calculate the rewards per epoch instead of looping over epochs, we recommend using the Velodrome fixed implementation, which we reviewed:\\n```\\n function earned(... | null | ```\\n Checkpoint memory cp = checkpoints[tokenId][_endIndex];\\n uint _lastEpochStart = _bribeStart(cp.timestamp);\\n uint _lastEpochEnd = _lastEpochStart + DURATION;\\n if (block.timestamp > _lastEpochEnd) {\\n reward += (cp.balanceOf * \\n tokenRewardsPerEpoch[token][_lastEpochSt... |
Division by 0 can freeze emissions claims for veSatin holders | medium | The function `_calculateClaim()` is responsible for the calculations of the amount of emissions a specific veSatin is entitled to claim. In doing so, this code is executed (code with mitigation from TRST-H-1):\\n```\\n if ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\\n toDistribute +=\\n ... | Ensure veSupply[weekCursor] is not 0 when performing the division. | null | ```\\n if ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\\n toDistribute +=\\n (balanceOf * tokensPerWeek[weekCursor]) / veSupply[weekCursor];\\n weekCursor += WEEK;\\n }\\n```\\n |
BaseV1Pair could break because of overflow | medium | In the function _update(), called internally by `mint()`, `burn()` and `swap()`, the following code is executed:\\n```\\n uint256 timeElapsed = blockTimestamp - blockTimestampLast;\\n // overflow is desired\\n if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {\\n reserve0CumulativeLast += _reserv... | Wrap the operation around an unchecked{} block so that when the variable overflows it loops back to 0 instead of reverting. | null | ```\\n uint256 timeElapsed = blockTimestamp - blockTimestampLast;\\n // overflow is desired\\n if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {\\n reserve0CumulativeLast += _reserve0 * timeElapsed;\\n reserve1CumulativeLast += _reserve1 * timeElapsed;\\n }\\n```\\n |
createGauge4Pool() lacks proper checks and/or access control | medium | The function createGauge4Pool() can be called by anybody at any time and is used to create a Gauge for a special pool, the 4pool. It takes 5 parameters as inputs:\\n```\\n function createGauge4pool(\\n address _4pool,\\n address _dai,\\n address _usdc,\\n address _usdt,\\n ... | Make the function only callable by an admin, and if it can be called multiple times, turn the variable FOUR_POOL_GAUGE_ADDRESS to a mapping from address to boolean to support multiple 4 pools. | null | ```\\n function createGauge4pool(\\n address _4pool,\\n address _dai,\\n address _usdc,\\n address _usdt,\\n address _cash\\n ) external returns (address) {\\n```\\n |
The logic in _calculateClaim() can leave some tokens locked and waste gas | low | The function `_calculateClaim()` is responsible for the calculations of the amount of emissions a specific veSatin is entitled to claim. To do so, this code is executed in a loop for each week from the current timestamp to the last claim (code with mitigation from TRST-H-1):\\n```\\n if ((lockEndTime - weekCursor) >... | When the if condition is not met burn the tokens that were supposed to be distributed and exit the loop. Since the non-distributed tokens would stay locked it's not strictly necessary to burn them. | null | ```\\n if ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\\n toDistribute +=\\n (balanceOf * tokensPerWeek[weekCursor]) / veSupply[weekCursor];\\n weekCursor += WEEK;\\n }\\n```\\n |
More than one hat of the same hatId can be assigned to a user | high | Hats are minted internally using `_mintHat()`.\\n```\\n /// @notice Internal call to mint a Hat token to a wearer\\n /// @dev Unsafe if called when `_wearer` has a non-zero balance of `_hatId`\\n /// @param _wearer The wearer of the Hat and the recipient of the newly minted token\\n /// @pa... | Instead of checking if user currently wears the hat, check if its balance is over 0. | null | ```\\n /// @notice Internal call to mint a Hat token to a wearer\\n /// @dev Unsafe if called when `_wearer` has a non-zero balance of `_hatId`\\n /// @param _wearer The wearer of the Hat and the recipient of the newly minted token\\n /// @param _hatId The id of the Hat to mint\\n fu... |
TXs can be executed by less than the minimum required signatures | high | In HatsSignerGateBase, `checkTransaction()` is the function called by the Gnosis safe to approve the transaction. Several checks are in place.\\n```\\n uint256 safeOwnerCount = safe.getOwners().length;\\n if (safeOwnerCount < minThreshold) {\\n revert BelowMinThreshold(minThreshold, s... | Add another check in `checkTransaction()`, which states that validSigCount >= minThreshold. | null | ```\\n uint256 safeOwnerCount = safe.getOwners().length;\\n if (safeOwnerCount < minThreshold) {\\n revert BelowMinThreshold(minThreshold, safeOwnerCount);\\n }\\n```\\n |
Target signature threshold can be bypassed leading to minority TXs | high | `checkTransaction()` is the enforcer of the HSG logic, making sure signers are wearers of hats and so on. The check below makes sure sufficient hat wearers signed the TX:\\n```\\n uint256 validSigCount = countValidSignatures(txHash, signatures, signatures.length / 65);\\n // revert if there aren't... | Call `reconcileSignerCount()` before the validation code in `checkTransaction()`. | null | ```\\n uint256 validSigCount = countValidSignatures(txHash, signatures, signatures.length / 65);\\n // revert if there aren't enough valid signatures\\n if (validSigCount < safe.getThreshold()) {\\n revert InvalidSigners();\\n }\\n```\\n |
maxSigners can be bypassed | high | maxSigners is specified when creating an HSG and is left constant. It is enforced in two ways -targetThreshold may never be set above it, and new signers cannot register to the HSG when the signer count reached maxSigners. Below is the implementation code in HatsSignerGate.\\n```\\n function claimSigner() public... | The root cause is that users which registered but lose their hat are still stored in the safe's owners array, meaning they can always get re-introduced and bump the signerCount. Instead of checking the signerCount, a better idea would be to compare with the list of owners saved on the safe. If there are owners that are... | null | ```\\n function claimSigner() public virtual {\\n if (signerCount == maxSigners) {\\n revert MaxSignersReached();\\n }\\n if (safe.isOwner(msg.sender)) {\\n revert SignerAlreadyClaimed(msg.sender);\\n }\\n if (!isValidSigner(msg.sender)) {... |
Attacker can DOS minting of new top hats in low-fee chains | medium | In Hats protocol, anyone can be assigned a top hat via the `mintTopHat()` function. The top hats are structured with top 32 bits acting as a domain ID, and the lower 224 bits are cleared. There are therefore up to 2^32 = ~ 4 billion top hats. Once they are all consumed, `mintTopHat()` will always fail:\\n```\\n ... | Require a non-refundable deposit fee (paid in native token) when minting a top hat. Price it so that consuming the 32-bit space will be impossible. This can also serve as a revenue stream for the Hats project. | null | ```\\n // uint32 lastTopHatId will overflow in brackets\\n topHatId = uint256(++lastTopHatId) << 224;\\n```\\n |
Linking of hat trees can freeze hat operations | medium | Hats support tree-linking, where hats from one node link to the first level of a different domain. This way, the amount of levels for the linked-to tree increases by the linked-from level count. This is generally fine, however lack of checking of the new total level introduces severe risks.\\n```\\n /// @notice ... | It is recommended to add a check in `_linkTopHatToTree()`, that the new accumulated level can fit in uint8. Another option would be to change the maximum level type to uint32. | null | ```\\n /// @notice Identifies the level a given hat in its hat tree\\n /// @param _hatId the id of the hat in question\\n /// @return level (0 to type(uint8).max)\\n function getHatLevel(uint256 _hatId) public view returns (uint8) {\\n```\\n |
Attacker can make a signer gate creation fail | medium | DAOs can deploy a HSG using `deployHatsSignerGateAndSafe()` or deployMultiHatsSignerGateAndSafe().The parameters are encoded and passed to moduleProxyFactory.deployModule():\\n```\\n bytes memory initializeParams = abi.encode(_ownerHatId, _signersHatId, _safe, hatsAddress, _minThreshold, \\n _targetThreshold, _ma... | Use an ever-increasing nonce counter to guarantee unique contract addresses. | null | ```\\n bytes memory initializeParams = abi.encode(_ownerHatId, _signersHatId, _safe, hatsAddress, _minThreshold, \\n _targetThreshold, _maxSigners, version );\\n hsg = moduleProxyFactory.deployModule(hatsSignerGateSingleton, abi.encodeWithSignature("setUp(bytes)", \\n initializeParams), _saltNonce );\\n... |
Signers can backdoor the safe to execute any transaction in the future without consensus | medium | The function `checkAfterExecution()` is called by the safe after signer's request TX was executed (and authorized). It mainly checks that the linkage between the safe and the HSG has not been compromised.\\n```\\n function checkAfterExecution(bytes32, bool) external override {\\n if (abi.decode(Storag... | Check that no new modules have been introduced to the safe, using the `getModulesPaginated()` utility. | null | ```\\n function checkAfterExecution(bytes32, bool) external override {\\n if (abi.decode(StorageAccessible(address(safe)).getStorageAt(uint256(GUARD_STORAGE_SLOT), 1), (address))\\n != address(this)) \\n {\\n revert CannotDisableThisGuard(address(th... |
createHat does not detect MAX_LEVEL admin correctly | low | In `createHat()`, the contract checks user is not minting hats for the lowest hat tier:\\n```\\n function createHat( uint256 _admin, string memory _details, uint32 _maxSupply, address _eligibility,\\n address _toggle, bool _mutable, string memory _imageURI) \\n public returns (u... | Change the conversion to uint16. | null | ```\\n function createHat( uint256 _admin, string memory _details, uint32 _maxSupply, address _eligibility,\\n address _toggle, bool _mutable, string memory _imageURI) \\n public returns (uint256 newHatId) {\\n if (uint8(_admin) > 0) {\\n revert MaxLeve... |
Incorrect imageURI is returned for hats in certain cases | low | Function `getImageURIForHat()` should return the most relevant imageURI for the requested hatId. It will iterate backwards from the current level down to level 0, and return an image if it exists for that level.\\n```\\n function getImageURIForHat(uint256 _hatId) public view returns (string memory) {\\n ... | Before returning the baseImageURI, check if level 0 admin has a registered image. | null | ```\\n function getImageURIForHat(uint256 _hatId) public view returns (string memory) {\\n // check _hatId first to potentially avoid the `getHatLevel` call\\n Hat memory hat = _hats[_hatId];\\n string memory imageURI = hat.imageURI; // save 1 SLOAD\... |
Fetching of hat status may fail due to lack of input sanitization | low | The functions `_isActive()` and `_isEligible()` are used by `balanceOf()` and other functions, so they should not ever revert. However, they perform ABI decoding from external inputs.\\n```\\n function _isActive(Hat memory _hat, uint256 _hatId) internal view returns (bool) {\\n bytes memory data = \\n ... | Wrap the decoding operation for both affected functions in a try/catch statement. Fall back to the `_getHatStatus()` result if necessary. Checking that returndata size is correct is not enough as bool encoding must be 64-bit encoded 0 or 1. | null | ```\\n function _isActive(Hat memory _hat, uint256 _hatId) internal view returns (bool) {\\n bytes memory data = \\n abi.encodeWithSignature("getHatStatus(uint256)", _hatId);\\n (bool success, bytes memory returndata) = \\n _hat.toggle.staticcall(data);\\n if (suc... |
Attacker can take over GMXAdapter implementation contract | low | GMXAdapter inherits from BaseExchangeAdapter. It is an implementation contract for a transparent proxy and has the following initializer:\\n```\\n function initialize() external initializer {\\n __Ownable_init();\\n }\\n```\\n\\nTherefore, an attacker can call initialize() on the implementation cont... | The standard approach is to call from the constructor the _disableInitializers() from Open Zeppelin's Initializable module | null | ```\\n function initialize() external initializer {\\n __Ownable_init();\\n }\\n```\\n |
disordered fee calculated causes collateral changes to be inaccurate | high | `_increasePosition()` changes the Hedger's GMX position by sizeDelta amount and collateralDelta collateral. There are two collateralDelta corrections - one for swap fees and one for position fees. Since the swap fee depends on up-to-date collateralDelta, it's important to calculate it after the position fee, contrary t... | Flip the order of `getSwapFeeBP()` and `_getPositionFee()`. | null | ```\\n if (isLong) {\\n uint swapFeeBP = getSwapFeeBP(isLong, true, collateralDelta);\\n collateralDelta = (collateralDelta * (BASIS_POINTS_DIVISOR + swapFeeBP)) / BASIS_POINTS_DIVISOR;\\n }\\n // add margin fee\\n // when we increase position, fee always got deducted from collate... |
small LP providers may be unable to withdraw their deposits | medium | In LiquidityPool's initiateWithdraw(), it's required that withdrawn value is above a minimum parameter, or that withdrawn tokens is above the minimum parameter.\\n```\\n if (withdrawalValue < lpParams.minDepositWithdraw && \\n amountLiquidityToken < lpParams.minDepositWithdraw) {\\n revert MinimumWit... | Consider calculating an average exchange rate at which users have minted and use it to verify withdrawal amount is satisfactory. | null | ```\\n if (withdrawalValue < lpParams.minDepositWithdraw && \\n amountLiquidityToken < lpParams.minDepositWithdraw) {\\n revert MinimumWithdrawNotMet(address(this), withdrawalValue, lpParams.minDepositWithdraw);\\n }\\n```\\n |
base to quote swaps trust GMX-provided minPrice and maxPrice to be correct, which may be manipulated | medium | exchangeFromExactBase() in GMXAdapter converts an amount of base to quote. It implements slippage protection by using the GMX vault's getMinPrice() and getMaxPrice() utilities. However, such protection is insufficient because GMX prices may be manipulated. Indeed, GMX supports “AMM pricing” mode where quotes are calcul... | Verify `getMinPrice()`, `getMinPrice()` outputs are close to Chainlink-provided prices as done in `getSpotPriceForMarket()`. | null | ```\\n uint tokenInPrice = _getMinPrice(address(baseAsset));\\n uint tokenOutPrice = _getMaxPrice(address(quoteAsset));\\n // rest of code\\n uint minOut = tokenInPrice\\n .multiplyDecimal(marketPricingParams[_optionMarket].minReturnPercent)\\n .multiplyDecimal(_amountBase)\\n .divi... |
recoverFunds() does not handle popular ERC20 tokens like BNB | medium | recoverFunds() is used for recovery in case of mistakenly-sent tokens. However, it uses unsafe transfer to send tokens back, which will not support 100s of non-compatible ERC20 tokens. Therefore it is likely unsupported tokens will be unrecoverable.\\n```\\n if (token == quoteAsset || token == baseAsset || token == we... | Use Open Zeppelin's SafeERC20 encapsulation of ERC20 transfer functions. | null | ```\\n if (token == quoteAsset || token == baseAsset || token == weth) {\\n revert CannotRecoverRestrictedToken(address(this));\\n }\\n token.transfer(recipient, token.balanceOf(address(this)));\\n```\\n |
setPositionRouter leaks approval to previous positionRouter | low | positionRouter is used to change GMX positions in GMXFuturesPoolHedger. It can be replaced by a new router if GMX redeploys, for example if a bug is found or the previous one is hacked. The new positionRouter receives approval from the contract. However, approval to the previous positionRouter is not revoked.\\n```\\n ... | Use router.denyPlugin() to remove privileges from the previous positionRouter. | null | ```\\n function setPositionRouter(IPositionRouter _positionRouter) external onlyOwner {\\n positionRouter = _positionRouter;\\n router.approvePlugin(address(positionRouter));\\n emit PositionRouterSet(_positionRouter);\\n }\\n```\\n |
PoolHedger can receive ETH directly from anyone | low | A `receive()` function has been added to GMXFuturesPoolHedger, so that it is able to receive ETH from GMX as request refunds. However, it is not advisable to have an open `receive()` function if it is not necessary. Users may wrongly send ETH directly to PoolHedger and lose it forever.\\n```\\n receive() exte... | Add a msg.sender check in the receive() function, and make sure sender is positionRouter. | null | ```\\n receive() external payable {}\\n```\\n |
Attacker can freeze profit withdrawals from V3 vaults | high | Users of Ninja can use Vault's `withdrawProfit()` to withdraw profits. It starts with the following check:\\n```\\n if (block.timestamp <= lastProfitTime) {\\n revert NYProfitTakingVault__ProfitTimeOutOfBounds();\\n }\\n```\\n\\nIf attacker can front-run user's `withdrawProfit()` TX and set lastProfitTime t... | Do not prevent profit withdrawals during lastProfitTime block. | null | ```\\n if (block.timestamp <= lastProfitTime) {\\n revert NYProfitTakingVault__ProfitTimeOutOfBounds();\\n }\\n```\\n |
Lack of child rewarder reserves could lead to freeze of funds | high | In ComplexRewarder.sol, `onReward()` is used to distribute rewards for previous time period, using the complex rewarder and any child rewarders. If the complex rewarder does not have enough tokens to hand out the reward, it correctly stores the rewards owed in storage. However, child rewarded will attempt to hand out t... | Introduce sufficient exception handling in the CompexRewarder.sol contract, so that `onReward()` would never fail. | null | ```\\n function onReward(uint _pid, address _user, address _to, uint, uint _amt) external override onlyParent nonReentrant {\\n PoolInfo memory pool = updatePool(_pid);\\n if (pool.lastRewardTime == 0) return;\\n UserInfo storage user = userInfo[_pid][_user];\\n uint pending;\\n ... |
Wrong accounting of user's holdings allows theft of reward | high | In `deposit()`, `withdraw()` and `withdrawProfit()`, `rewarder.onReward()` is called for reward bookkeeping. It will transfer previous eligible rewards and update the current amount user has:\\n```\\n user.amount = _amt;\\n user.rewardDebt = (_amt * pool.accRewardPerShare) / ACC_TOKEN_PRECISION;\\n user.... | Move the `onReward()` call to after user.amount is updated. | null | ```\\n user.amount = _amt;\\n user.rewardDebt = (_amt * pool.accRewardPerShare) / ACC_TOKEN_PRECISION;\\n user.rewardsOwed = rewardsOwed;\\n```\\n |
Unsafe transferFrom breaks compatibility with 100s of ERC20 tokens | medium | In Ninja vaults, the delegated strategy sends profit tokens to the vault using `depositProfitTokenForUsers()`. The vault transfers the tokens in using:\\n```\\n // Now pull in the tokens (Should have permission)\\n // We only want to pull the tokens with accounting\\n profitToken.transfe... | Use `safeTransferFrom()` from SafeERC20.sol | null | ```\\n // Now pull in the tokens (Should have permission)\\n // We only want to pull the tokens with accounting\\n profitToken.transferFrom(strategy, address(this), _amount);\\n emit ProfitReceivedFromStrategy(_amount);\\n```\\n |
Attacker can force partial withdrawals to fail | medium | In Ninja vaults, users call `withdraw()` to take back their deposited tokens. There is bookkeeping on remaining amount:\\n```\\n uint256 userAmount = balanceOf(msg.sender);\\n // - Underlying (Frontend ONLY)\\n if (userAmount == 0) {\\n user.amount = 0;\\n } else {\\n ... | Redesign user structure, taking into account that balance of underlying can be externally manipulated | null | ```\\n uint256 userAmount = balanceOf(msg.sender);\\n // - Underlying (Frontend ONLY)\\n if (userAmount == 0) {\\n user.amount = 0;\\n } else {\\n user.amount -= r;\\n }\\n```\\n |
Rewards may be stuck due to unchangeable slippage parameter | medium | In NyPtvFantomWftmBooSpookyV2StrategyToUsdc.sol, MAX_SLIPPAGE is used to limit slippage in trades of BOO tokens to USDC, for yield:\\n```\\n function _swapFarmEmissionTokens() internal { IERC20Upgradeable boo = IERC20Upgradeable(BOO);\\n uint256 booBalance = boo.balanceOf(address(this));\\n if (boo... | Allow admin to set slippage after some timelock period. | null | ```\\n function _swapFarmEmissionTokens() internal { IERC20Upgradeable boo = IERC20Upgradeable(BOO);\\n uint256 booBalance = boo.balanceOf(address(this));\\n if (booToUsdcPath.length < 2 || booBalance == 0) {\\n return;\\n }\\n boo.safeIncreaseAllowance(SPOOKY_ROUTER, booBalanc... |
potential overflow in reward accumulator may freeze functionality | medium | Note the above description of `updatePool()` functionality. We can see that accRewardPerShare is only allocated 128 bits in PoolInfo:\\n```\\n struct PoolInfo {\\n uint128 accRewardPerShare;\\n uint64 lastRewardTime;\\n uint64 allocPoint;\\n```\\n\\nTherefore, even if truncation i... | Steal 32 bits from lastRewardTime and 32 bits from allocPoint to make the accumulator have 192 bits, which should be enough for safe calculations. | null | ```\\n struct PoolInfo {\\n uint128 accRewardPerShare;\\n uint64 lastRewardTime;\\n uint64 allocPoint;\\n```\\n |
when using fee-on-transfer tokens in VaultV3, capacity is limited below underlyingCap | low | Vault V3 documentation states it accounts properly for fee-on-transfer tokens. It calculates actual transferred amount as below:\\n```\\n uint256 _pool = balance();\\n if (_pool + _amount > underlyingCap) {\\n revert NYProfitTakingVault__UnderlyingCapReached(underlyingCap);\\n }\\n u... | Move the underlyingCap check to below the effective _amount calculation | null | ```\\n uint256 _pool = balance();\\n if (_pool + _amount > underlyingCap) {\\n revert NYProfitTakingVault__UnderlyingCapReached(underlyingCap);\\n }\\n uint256 _before = underlying.balanceOf(address(this));\\n underlying.safeTransferFrom(msg.sender, address(this), _amount)... |
Redundant checks in Vault V3 | low | `depositProfitTokenForUsers()` and `withdrawProfit()` contain the following check:\\n```\\n if (block.timestamp <= lastProfitTime) {\\n revert NYProfitTakingVault__ProfitTimeOutOfBounds();\\n }\\n```\\n\\nHowever, lastProfitTime is only ever set to block.timestamp. Therefore, it can never be larger th... | It would be best in terms of gas costs and logical clarity to change the comparison to != | null | ```\\n if (block.timestamp <= lastProfitTime) {\\n revert NYProfitTakingVault__ProfitTimeOutOfBounds();\\n }\\n```\\n |
createUniswapRangeOrder() charges manager instead of pool | high | _createUniswapRangeOrder() can be called either from manager flow, with createUniswapRangeOrder(), or pool-induced from hedgeDelta(). The issue is that the function assumes the sender is the parentLiquidityPool, for example:\\n```\\n if (inversed && balance < amountDesired) {\\n // collat = 0\\n ... | Ensure safeTransfer from uses parentLiquidityPool as source. | null | ```\\n if (inversed && balance < amountDesired) {\\n // collat = 0\\n uint256 transferAmount = amountDesired - balance;\\n uint256 parentPoolBalance = \\n ILiquidityPool(parentLiquidityPool).getBalance(address(token0));\\n if (parentPoolBalance < transferAmount) { re... |
hedgeDelta() priceToUse is calculated wrong, which causes bad hedges | high | When _delta parameter is negative for `hedgeDelta()`, priceToUse will be the minimum between quotePrice and underlyingPrice.\\n```\\n // buy wETH\\n // lowest price is best price when buying\\n uint256 priceToUse = quotePrice < underlyingPrice ? quotePrice : \\n underlyingPrice;\\n RangeOrder... | Verify the calculated priceToUse is on the same side as pool-calculated tick price. | null | ```\\n // buy wETH\\n // lowest price is best price when buying\\n uint256 priceToUse = quotePrice < underlyingPrice ? quotePrice : \\n underlyingPrice;\\n RangeOrderDirection direction = inversed ? RangeOrderDirection.ABOVE \\n : RangeOrderDirection.BELOW;\\n RangeOrderParams memor... |
multiplication overflow in getPoolPrice() likely | medium | `getPoolPrice()` is used in hedgeDelta to get the price directly from Uniswap v3 pool:\\n```\\n function getPoolPrice() public view returns (uint256 price, uint256 \\n inversed){\\n (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();\\n uint256 p = uint256(sqrtPriceX96) * uint256(sqrtPriceX9... | Consider converting the sqrtPrice to a 60x18 format and performing arithmetic operations using the PRBMathUD60x18 library. | null | ```\\n function getPoolPrice() public view returns (uint256 price, uint256 \\n inversed){\\n (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();\\n uint256 p = uint256(sqrtPriceX96) * uint256(sqrtPriceX96) * (10 \\n ** token0.decimals());\\n // token0/token1 in 1e18 format\\n ... |
Hedging won't work if token1.decimals() < token0.decimals() | medium | `tickToToken0PriceInverted()` performs some arithmetic calculations. It's called by `_getTicksAndMeanPriceFromWei()`, which is called by `hedgeDelta()`. This line can overflow:\\n```\\n uint256 intermediate = inWei.div(10**(token1.decimals() -\\n token0.decimals()));\\n```\\n\\nAlso, this line would revert e... | Refactor the calculation to support different decimals combinations. Additionally, add more comprehensive tests to detect similar issues in the future. | null | ```\\n uint256 intermediate = inWei.div(10**(token1.decimals() -\\n token0.decimals()));\\n```\\n |
Overflow danger in _sqrtPriceX96ToUint | medium | _sqrtPriceX96ToUint will only work when the non-fractional component of sqrtPriceX96 takes up to 32 bits. This represents a price ratio of 18446744073709551616. With different token digits it is not unlikely that this ratio will be crossed which will make hedgeDelta() revert.\\n```\\n function _sqrtPriceX96ToUint(ui... | Perform the multiplication after converting the numbers to 60x18 variables | null | ```\\n function _sqrtPriceX96ToUint(uint160 sqrtPriceX96) private pure returns (uint256)\\n {\\n uint256 numerator1 = uint256(sqrtPriceX96) * \\n uint256(sqrtPriceX96);\\n return FullMath.mulDiv(numerator1, 1, 1 << 192);\\n }\\n```\\n |
Insufficient dust checks | low | In `hedgeDelta()`, there is a dust check in the case of sell wETH order:\\n```\\n // sell wETH\\n uint256 wethBalance = inversed ? amount1Current : amount0Current;\\n if (wethBalance < minAmount) return 0;\\n```\\n\\nHowever, the actual used amount is _delta\\n```\\n uint256 deltaT... | Correct current dust checks and add them also in the if clause. | null | ```\\n // sell wETH\\n uint256 wethBalance = inversed ? amount1Current : amount0Current;\\n if (wethBalance < minAmount) return 0;\\n```\\n |
Linear vesting users may not receive vested amount | high | TokenTransmuter supports two types of transmutations, linear and instant. In linear, allocated amount is released across time until fully vested, while in instant the entire amount is released immediately. transmuteLinear() checks that there is enough output tokens left in the contract before accepting transfer of inpu... | In transmuteInstant, add a check similar to the one in transmuteLinear. It will ensure allocations are kept faithfully. | null | ```\\n require(IERC20(outputTokenAddress).balanceOf(address(this)) >= \\n (totalAllocatedOutputToken - totalReleasedOutputToken), \\n "INSUFFICIENT_OUTPUT_TOKEN");\\n IERC20(inputTokenAddress).transferFrom(msg.sender, address(0), \\n _inputTokenAmount);\\n```\\n |
Multiplier implementation causes limited functionality | low | linearMultiplier and instantMultiplier are used to calculate output token amount from input token amount in transmute functions.\\n```\\n uint256 allocation = (_inputTokenAmount * linearMultiplier) / \\n tokenDecimalDivider;\\n …\\n uint256 allocation = (_inputTokenAmount * instantMultiplier) / \\n ... | Add a boolean state variable which will describe whether to multiply or divide by the multiplier. | null | ```\\n uint256 allocation = (_inputTokenAmount * linearMultiplier) / \\n tokenDecimalDivider;\\n …\\n uint256 allocation = (_inputTokenAmount * instantMultiplier) / \\n tokenDecimalDivider;\\n```\\n |
Empty orders do not request from oracle and during settlement they use an invalid oracle version with `price=0` which messes up a lot of fees and funding accounting leading to loss of funds for the makers | high | When `market.update` which doesn't change user's position is called, a new (current) global order is created, but the oracle version is not requested due to empty order. This means that during the order settlement, it will use non-existant invalid oracle version with `price = 0`. This price is then used to accumulate a... | Keep the price from the previous valid oracle version and use it instead of oracle version's one if oracle version's price == 0. | All fees and funding are incorrectly calculated as 0 during any period when there are no non-empty orders (which will be substantially more than 50% of the time, more like 90% of the time). Since most fees and funding are received by makers as a compensation for their price risk, this means makers will lose all these u... | ```\\n// request version\\nif (!newOrder.isEmpty()) oracle.request(IMarket(this), account);\\n```\\n |
Vault global shares and assets change will mismatch local shares and assets change during settlement due to incorrect `_withoutSettlementFeeGlobal` formula | high | Every vault update, which involves change of position in the underlying markets, `settlementFee` is charged by the Market. Since many users can deposit and redeem during the same oracle version, this `settlementFee` is shared equally between all users of the same oracle version. However, there is an issue in that `sett... | Calculate total orders to deposit and total orders to redeem (in addition to total orders overall). Then `settlementFee` should be multiplied by `deposit/orders` for `toGlobalShares` and by `redeems/orders` for `toGlobalAssets`. This weightening of `settlementFee` will make it in-line with local order weights. | Any time there are both deposits and redeems in the same oracle version, the users receive more (local) shares and assets than overall vault shares and assets increase (global). This mismatch causes:\\nSystematic increase of (sum of user shares - global shares), which can lead to bank run since the last users who try t... | ```\\nfunction update(\\n Account memory self,\\n uint256 currentId,\\n UFixed6 assets,\\n UFixed6 shares,\\n UFixed6 deposit,\\n UFixed6 redemption\\n) internal pure {\\n self.current = currentId;\\n // @audit global account will have less assets and shares than sum of local accounts\\n (sel... |
Requested oracle versions, which have expired, must return this oracle version as invalid, but they return it as a normal version with previous version's price instead | high | Each market action requests a new oracle version which must be commited by the keepers. However, if keepers are unable to commit requested version's price (for example, no price is available at the time interval, network or keepers are down), then after a certain timeout this oracle version will be commited as invalid,... | Add validity map along with the price map to `KeeperOracle` when recording commited price. | Market uses invalid (expired) oracle versions as if they're valid, keeping the orders (instead of invalidating them), which is a broken core functionality and a security risk for the protocol. | ```\\nfunction _commitRequested(OracleVersion memory version) private returns (bool) {\\n if (block.timestamp <= (next() + timeout)) {\\n if (!version.valid) revert KeeperOracleInvalidPriceError();\\n _prices[version.timestamp] = version.price;\\n } else {\\n // @audit previous valid version'... |
When vault's market weight is set to 0 to remove the market from the vault, vault's leverage in this market is immediately set to max leverage risking position liquidation | medium | If any market has to be removed from the vault, the only way to do this is via setting this market's weight to 0. The problem is that the first vault rebalance will immediately withdraw max possible collateral from this market, leaving vault's leverage at max possible leverage, risking the vault's position liquidation.... | Ensure that the market's collateral is based on leverage even if `weight = 0` | Market removed from the vault (weight set to 0) is put at max leverage and has a high risk of being liquidated, thus losing vault depositors funds. | ```\\n marketCollateral = marketContext.margin\\n .add(collateral.sub(totalMargin).mul(marketContext.registration.weight));\\n\\n UFixed6 marketAssets = assets\\n .mul(marketContext.registration.weight)\\n .min(marketCollateral.mul(LEVERAGE_BUFFER));\\n```\\n |
Makers can lose funds from price movement even when no long and short positions are opened, due to incorrect distribution of adiabatic fees exposure between makers | medium | Adiabatic fees introduced in this new update of the protocol (v2.3) were introduced to solve the problem of adiabatic fees netting out to 0 in market token's rather than in USD terms. With the new versions, this problem is solved and adiabatic fees now net out to 0 in USD terms. However, they net out to 0 only for the ... | Split the total maker exposure by individual maker's exposure rather than by their position size. To do this:\\nAdd another accumulator to track total `exposure`\\nAdd individual maker `exposure` to user's `Local` storage\\nWhen accumulating local storage in the checkpoint, account global accumulator `exposure` weighte... | Individual makers bear an additional undocumented price risk due to adiabatic fees, which is quite significant (can be several percentages of the notional). | ```\\nit('adiabatic fee', async () => {\\n function setupOracle(price: string, timestamp : number, nextTimestamp : number) {\\n const oracleVersion = {\\n price: parse6decimal(price),\\n timestamp: timestamp,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(orac... |
All transactions to claim assets from the vault will revert in some situations due to double subtraction of the claimed assets in market position allocations calculation. | medium | When `assets` are claimed from the vault (Vault.update(0,0,x) called), the vault rebalances its collateral. There is an issue with market positions allocation calculations: the `assets` ("total position") subtract claimed amount twice. This leads to revert in case this incorrect `assets` amount is less than `minAssets`... | Remove `add(withdrawal)` from `_ineligable` calculation in the vault. | In certain situations (redeem not possible from the vault due to high skew in some underlying market) claiming assets from the vault will revert for all users, temporarily (and sometimes permanently) locking user funds in the contract. | ```\\n_manage(context, depositAssets, claimAmount, !depositAssets.isZero() || !redeemShares.isZero());\\n```\\n |
If referral or liquidator is the same address as the account, then liquidation/referral fees will be lost due to local storage being overwritten after the `claimable` amount is credited to liquidator or referral | medium | Any user (address) can be liquidator and/or referral, including account's own address (the user can self-liquidate or self-refer). During the market settlement, liquidator and referral fees are credited to liquidator/referral's `local.claimable` storage. The issue is that the account's local storage is held in the memo... | Modify `Market._credit` function to increase `context.local.claimable` if account to be credited matches account which is being updated. | If user self-liquidates or self-refers, the liquidation and referral fees are lost by the user (and are stuck in the contract, because they're still subtracted from the user's collateral). | ```\\n// rest of code\\n _credit(liquidators[account][newOrderId], accumulationResult.liquidationFee);\\n _credit(referrers[account][newOrderId], accumulationResult.subtractiveFee);\\n// rest of code\\nfunction _credit(address account, UFixed6 amount) private {\\n if (amount.isZero()) return;\\n\\n Local me... |
_loadContext() uses the wrong pendingGlobal. | medium | `StrategyLib._loadContext()` is using the incorrect `pendingGlobal`, causing `currentPosition`, `minPosition`, and `maxPosition` to be incorrect, leading to incorrect rebalance operation.\\nIn `StrategyLib._loadContext()`, there is a need to compute `currentPosition`, `minPosition`, and `maxPosition`. The code as follo... | ```\\n function _loadContext(\\n Registration memory registration\\n ) private view returns (MarketStrategyContext memory marketContext) {\\n// rest of code\\n // current position\\n// Remove the line below\\n Order memory pendingGlobal = registration.market.pendings(address(this));\\n// Add t... | Since `pendingGlobal` is wrong, `currentPosition`, `minPosition` and `maxPosition` are all wrong. affects subsequent rebalance calculations, such as `target.position` etc. rebalance does not work properly | ```\\n function _loadContext(\\n Registration memory registration\\n ) private view returns (MarketStrategyContext memory marketContext) {\\n// rest of code\\n // current position\\n Order memory pendingGlobal = registration.market.pendings(address(this));\\n marketContext.currentPositio... |
Liquidator can set up referrals for other users | medium | If a user has met the liquidation criteria and currently has no referrer then a malicious liquidator can specify a referrer in the liquidation order. making it impossible for subsequent users to set up the referrer they want.\\nCurrently, there are 2 conditions to set up a referrer\\nthe order cannot be empty (Non-empt... | Restrictions on Liquidation Orders Cannot Set a referrer\\n```\\n function _processReferrer(\\n UpdateContext memory updateContext,\\n Order memory newOrder,\\n address referrer\\n ) private pure {\\n// Add the line below\\n if (newOrder.protected() && referrer != address(0)) revert Mar... | If a user is set up as a referrer by a liquidated order in advance, the user cannot be set up as anyone else. | ```\\n function _loadUpdateContext(\\n Context memory context,\\n address account,\\n address referrer\\n ) private view returns (UpdateContext memory updateContext) {\\n// rest of code\\n updateContext.referrer = referrers[account][context.local.currentId];\\n updateContext.ref... |
Vault and oracle keepers DoS in some situations due to `market.update(account,max,max,max,0,false)` | medium | When user's market account is updated without position and collateral change (by calling market.update(account,max,max,max,0,false)), this serves as some kind of "settling" the account (which was the only way to settle the account before v2.3). However, this action still reverts if the account is below margin requireme... | Depending on intended functionality:\\nIgnore the margin requirement for empty orders and collateral change which is >= 0. AND/OR\\nUse `Market.settle` instead of `Market.update` to `settle` accounts, specifically in `KeeperOracle._settle` and in `Vault._updateUnderlying`. There doesn't seem to be any reason or issue t... | Keepers are unable to settle market accounts for the commited oracle version until all accounts are above margin. The oracle fees are still taken from all accounts, but the keepers are blocked from receiving it.\\nIf any Vault's market weight is set to 0 (or if vault's position in any market goes below margin for whate... | ```\\nif (\\n !PositionLib.margined(\\n context.latestPosition.local.magnitude().add(context.pending.local.pos()),\\n context.latestOracleVersion,\\n context.riskParameter,\\n context.local.collateral\\n )\\n) revert IMarket.MarketInsufficientMarginError();\\n```\\n |
Vault checkpoints slightly incorrect conversion from assets to shares leads to slow loss of funds for long-time vault depositors | medium | When vault checkpoints convert assets to shares (specifically used to calculate user's shares for their deposit), it uses the following formula: `shares = (assets[before fee] - settlementFee) * checkpoint.shares/checkpoint.assets * (deposit + redeem - tradeFee) / (deposit + redeem)`\\n`settlementFee` in this formula is... | Re-work the assets to shares conversion in vault checkpoint to use the correct formula: `shares = (assets[before fee] - settlementFee - tradeFee * assets / (deposit + redeem)) * checkpoint.shares/checkpoint.assets` | Any vault deposit reduces the vault assets by `settlementFee * tradeFeePct`. While this amount is not very large (in the order of $0.1 - $0.001 per deposit transaction), this is amount lost with each deposit, and given that an active vault can easily have 1000s of transactions daily, this will be a loss of $1-$100/day,... | ```\\nfunction toSharesGlobal(Checkpoint memory self, UFixed6 assets) internal pure returns (UFixed6) {\\n // vault is fresh, use par value\\n if (self.shares.isZero()) return assets;\\n\\n // if vault is insolvent, default to par value\\n return self.assets.lte(Fixed6Lib.ZERO) ? assets : _toShares(self, _... |
ChainlinkFactory will pay non-requested versions keeper fees | medium | Protocol definition: `Requested versions will pay out a keeper fee, non-requested versions will not.` But ChainlinkFactory ignores `numRequested`, which pays for both.\\nProtocol definition: `Requested versions will pay out a keeper fee, non-requested versions will not.`\\n```\\n /// @notice Commits the price to spe... | It is recommended that only `Requested versions` keeper fees'\\n```\\n// Remove the line below\\n function _applicableValue(uint256 , bytes memory data) internal view override returns (uint256) {\\n// Add the line below\\n function _applicableValue(uint256 numRequested, bytes memory data) internal view override ret... | If `non-requested versions` will pay as well, it is easy to maliciously submit `non-requested` maliciously consume `ChainlinkFactory` fees balance (Note that needs at least one numRequested to call `_handleKeeperFee()` ) | ```\\n /// @notice Commits the price to specified version\\n /// @dev Accepts both requested and non-requested versions.\\n /// Requested versions will pay out a keeper fee, non-requested versions will not.\\n /// Accepts any publish time in the underlying price message, as long as it is within th... |
Liquidity provider fees can be stolen from any pair | high | An attacker can steal the liquidiy providers fees by transfering liquidity tokens to the pair and then withdrawing fees on behalf of the pair itself.\\nThis is possible because of two reasons:\\nTransfering liquidity tokens to the pair itself doesn't update the fee tracking variables:\\n```\\nif (to != address(this)) {... | In withdrawFees(pair) add a require statement to prevent fees being withdrawn on behalf of the pool.\\n```\\nrequire(to != address(this));\\n```\\n | Liquidity provider fees can be stolen from any pair. | ```\\nif (to != address(this)) {\\n _updateFeeRewards(to);\\n}\\n```\\n |
Some unusual problems arise in the use of the `GoatV1Factory.sol#createPair()` function. | medium | If you create a new pool for tokens and add liquidity using the `GoatRouterV1.sol#addLiquidity()` function, the bootstrap function of the protocol is broken. Therefore, an attacker can perform the front running attack on the `GoatRouterV1.sol#addLiquidity()` function by front calling `GoatV1Factory.sol#createPair()`.\\... | It is recommended that the `GoatV1Factory.sol#.createPair()` function be called only from the `GoatRouterV1` contract. | The bootstrap function of the protocol is broken and the initial LP must pay an amount of WETH equivalent to bootstrapEth. | ```\\n function _addLiquidity(\\n address token,\\n uint256 tokenDesired,\\n uint256 wethDesired,\\n uint256 tokenMin,\\n uint256 wethMin,\\n GoatTypes.InitParams memory initParams\\n ) internal returns (uint256, uint256, bool) {\\n GoatTypes.LocalVariables_AddLiqu... |
No check for `initialEth` in `GoatV1Pair.takeOverPool()`. | medium | GoatV1Pair.takeOverPool() only checks the amount of `token` for initialization, not `initialETH`.\\n```\\n function takeOverPool(GoatTypes.InitParams memory initParams) external {\\n if (_vestingUntil != _MAX_UINT32) {\\n revert GoatErrors.ActionNotAllowed();\\n }\\n\\n GoatTypes.Init... | There should be a check for `initParams.initialEth`. | A pool could be unfairly taken over because the former initial provider's `initialEth` does not have any effect in preventing takeovers. | ```\\n function takeOverPool(GoatTypes.InitParams memory initParams) external {\\n if (_vestingUntil != _MAX_UINT32) {\\n revert GoatErrors.ActionNotAllowed();\\n }\\n\\n GoatTypes.InitialLPInfo memory initialLpInfo = _initialLPInfo;\\n\\n GoatTypes.LocalVariables_TakeOverPool ... |
Legitimate pools can be taken over and the penalty is not fair. | medium | In GoatV1Pair.takeOverPool(), a malicious user can take over pool from a legitimate user, because the mechanism for identifying is incorrect. And the penalty mechanism is not fair.\\nGoatV1Pair.takeOverPool() function exists to avoid grief, because only one pool can be created for each token. Doc says "They can then lo... | I think that the mechanism for identifying should be improved. | Legitimate pools can be taken over unfairly. | ```\\n function takeOverPool(GoatTypes.InitParams memory initParams) external {\\n if (_vestingUntil != _MAX_UINT32) {\\n revert GoatErrors.ActionNotAllowed();\\n }\\n\\n GoatTypes.InitialLPInfo memory initialLpInfo = _initialLPInfo;\\n\\n GoatTypes.LocalVariables_TakeOverPool ... |
The router is not compatible with fee on transfers tokens | medium | The router is not compatible with fee on transfers tokens.\\nLet's take as example the removeLiquidity function:\\n```\\naddress pair = GoatV1Factory(FACTORY).getPool(token);\\n\\nIERC20(pair).safeTransferFrom(msg.sender, pair, liquidity); //-> 1. Transfers liquidity tokens to the pair\\n(amountWeth, amountToken) = Goa... | Add functionality to the router to support fee on transfer tokens, a good example of where this is correctly implememented is the Uniswap Router02. | The router is not compatible with fee on transfers tokens. | ```\\naddress pair = GoatV1Factory(FACTORY).getPool(token);\\n\\nIERC20(pair).safeTransferFrom(msg.sender, pair, liquidity); //-> 1. Transfers liquidity tokens to the pair\\n(amountWeth, amountToken) = GoatV1Pair(pair).burn(to); //-> 2. Burns the liquidity tokens and sends WETH and TOKEN to the recipient\\nif (amountWe... |
It's possible to create pairs that cannot be taken over | medium | It's possible to create pairs that cannot be taken over and DOS a pair forever.\\nA pair is created by calling createPair() which takes the initial parameters of the pair as inputs but the initial parameters are never verified, which makes it possible for an attacker to create a token pair that's impossible to recover ... | Validate a pair initial parameters and mint liquidity on pool creation. | Creation of new pairs can be DOSed forever. | ```\\nuint112 virtualEth = type(uint112).max;\\nuint112 bootstrapEth = type(uint112).max;\\nuint112 initialEth = type(uint112).max;\\nuint112 initialTokenMatch = type(uint112).max;\\n```\\n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.