query large_stringlengths 38 1.7k | positive large_stringlengths 18 171k | hard_negative large_stringlengths 18 171k | negative_type large_stringclasses 8
values | source large_stringclasses 9
values | severity large_stringclasses 3
values | vuln_type large_stringclasses 315
values | quality_tier int64 1 3 |
|---|---|---|---|---|---|---|---|
HIGH severity: BufferBinaryPool can permanently lock funds on early exercise. **Details**
[BufferBinaryOptions.sol#L380-L395](https://github.com/Buffer-Finance/Buffer-Protocol-v2_5/blob/84b6060b4447b2550de595202e8820c7f515988b/contracts/core/BufferBinaryOptions.sol#L380-L395)
if (option.expiration > closingTi... | uint256 transferTokenXAmount = tokenXAmount > ll.amount
? ll.amount
: tokenXAmount; | def _balanceAdapters( _target_asset_balance: uint256, pregen_info: DynArray[Bytes[4096], MAX_ADAPTERS], _withdraw_only : bool = False, _max_txs: uint8 = MAX_BALTX_DEPOSIT ):
# Make sure we have enough assets to send to _receiver.
txs: BalanceTX[MAX_ADAPTERS] = empty(BalanceTX[MAX_ADAPTERS])
blocked_adapters: address[MA... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Market direction signature can be abused if privateKeeperMode is disabled. **Details**
https://github.com/Buffer-Finance/Buffer-Protocol-v2_5/blob/84b6060b4447b2550de595202e8820c7f515988b/contracts/core/BufferRouter.sol#L233-L246
if (
!Validator.verifyMarketDirection(
... | if (
!Validator.verifyMarketDirection(
params,
queuedTrade,
optionInfo.signer
)
) {
emit FailUnlock(
params.optionId,
params.targetContract,
"Router: Wrong market direction"
);
continue;
} | function calcFunding(uint256 collateralAdded, uint256 totalShares, uint256 poolValue)
internal
pure
returns (uint256 sharesMinted)
{
if (totalShares == 0) {
// funding when LP pool is empty
sharesMinted = collateralAdded;
} else {
// mint LP tokens proportional to how much value the new investment
// brings to the pool | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: closeAnytime timestamp is never validated against current timestamp. **Details**
[BufferRouter.sol#L248-L258](https://github.com/Buffer-Finance/Buffer-Protocol-v2_5/blob/84b6060b4447b2550de595202e8820c7f515988b/contracts/core/BufferRouter.sol#L248-L258)
try
optionsContract.u... | try
optionsContract.unlock(
params.optionId,
params.closingPrice,
publisherSignInfo.timestamp,
params.isAbove
)
{} catch Error(string memory reason) {
emit FailUnlock(params.optionId, params.targetContract, reason);
continue;
} | function _debit(uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid)
internal
override
returns (uint256 amountSentLD, uint256 amountReceivedLD)
{
(amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);
uint256 shares = sharesByUsd(amountSentLD);
_burnShares(msg.sender, shares);
_setTotalUs... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Math error in Dynamo4626#\_claimable_fees_available will lead to fees or strategy lockup. **Details**
[Dynamo4626.vy#L428-L438](https://github.com/DynamoFinance/vault/blob/c331ffefadec7406829fc9f2e7f4ee7631bef6b3/contracts/Dynamo4626.vy#L428-L438)
fee_percentage: uint256 = YIELD_FEE_PERCENTAGE
... | fee_percentage: uint256 = YIELD_FEE_PERCENTAGE
if _yield == FeeType.PROPOSER:
fee_percentage = PROPOSER_FEE_PERCENTAGE
elif _yield == FeeType.BOTH:
fee_percentage += PROPOSER_FEE_PERCENTAGE
elif _yield != FeeType.YIELD:
assert False, "Invalid FeeType!" | (, uint256 feeAmount,) = IMarketMakerV1_2(market).buyFor(
buyer,
buys[i].investmentAmount,
buys[i].outcomeIndex,
buys[i].minOutcomeTokensToBuy,
extraFeeDecimal,
feeProfileId
);
totalFees += feeAmount;
}
if (totalInvestment > 0 && (data.length > 0 || affiliate != address(0x0))) {
@> emit BuyWithData(buyer, affilia... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: MarketMaker.sol is vulnerable to inflation attacks. **Details**
[FundingMath.sol#L21-L37](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/2766b47bed2cf027e29053af2afc4d35256747a5/contracts/funding/FundingMath.sol#L21-L37)
function calcFunding(uint256 collateralAdded, uint256 totalShares, u... | function calcFunding(uint256 collateralAdded, uint256 totalShares, uint256 poolValue)
internal
pure
returns (uint256 sharesMinted)
{
if (totalShares == 0) {
// funding when LP pool is empty
sharesMinted = collateralAdded;
} else {
// mint LP tokens proportional to how much value the new investment
// brings to the pool | pg: PregenInfo = empty(PregenInfo)
if len(pregen_info) > 0:
pg = _abi_decode(pregen_info, PregenInfo)
else:
#Info not provided, compute it expensively
pg.approx_params_swapExactYtForPt = self.default_approx_params()
pg.approx_params_swapExactTokenForPt = self.default_approx_params()
ytToPTL: uint256 = 0
pg.mint_returns... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: After migration, the old MarketFundingPool contract will fail to correctly distribute fees to new MarketFundingPool. **Details**
[FundingPool.sol#L135-L142](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/2766b47bed2cf027e29053af2afc4d35256747a5/contracts/funding/FundingPool.sol#L135-L142)
... | function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
if (from != address(0)) {
// LP tokens being transferred away from a funder - any fees that
// have accumulated so far due to trading activity should be given
// to the original owner for the period of time he held the LP
// tok... | uint256 vestIndexLength = vests.length;
if (vesting[msg.sender].length < vestIndexLength) {
revert InvalidLength();
} | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Precision error in \_fetchTWAP causes vesting to be free after initial lockdrop period. **Details**
[BlueberryStaking.sol#L830-L843](https://github.com/Blueberryfi/blueberry-staking/blob/efaf7fc690e38914ba475d5ac61a4d0bd3f45c0d/src/BlueberryStaking.sol#L830-L843)
// Adjust for decimals
if (BLB_... | if (blbIsToken0) {
return FullMath.mulDiv(_priceX96, 10 ** (18 + BLB_DECIMALS stableDecimals), 2 ** 96);
} else {
uint256 inversePrice = FullMath.mulDiv(_priceX96, 10 ** (18 - BLB_DECIMALS + stableDecimals), 2 ** 96);
return 10**36 / inversePrice;
} | function claim(
address to,
uint256 amount,
bytes32[] calldata proof
) external {
// Throw if address has already claimed tokens
require(!hasClaimed[to], "ALREADY_CLAIMED");
// Verify merkle proof, or revert if not in tree
bytes32 leaf = keccak256(abi.encodePacked(to, amount));
bool isValidLeaf = MerkleProof.verify(pr... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: It is impossible to complete any vest unless all vests are mature. **Details**
[BlueberryStaking.sol#L328-L331](https://github.com/Blueberryfi/blueberry-staking/blob/efaf7fc690e38914ba475d5ac61a4d0bd3f45c0d/src/BlueberryStaking.sol#L328-L331)
uint256 vestIndexLength = vests.length;
if (vestin... | uint256 vestIndexLength = vests.length;
if (vesting[msg.sender].length < vestIndexLength) {
revert InvalidLength();
} | function calcFunding(uint256 collateralAdded, uint256 totalShares, uint256 poolValue)
internal
pure
returns (uint256 sharesMinted)
{
if (totalShares == 0) {
// funding when LP pool is empty
sharesMinted = collateralAdded;
} else {
// mint LP tokens proportional to how much value the new investment
// brings to the pool | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Rewards will be permanently lost for ibToken with no deposits. **Details**
[BlueberryStaking.sol#L482-L485](https://github.com/Blueberryfi/blueberry-staking/blob/efaf7fc690e38914ba475d5ac61a4d0bd3f45c0d/src/BlueberryStaking.sol#L482-L485)
function rewardPerToken(address _ibToken) public view retu... | function rewardPerToken(address _ibToken) public view returns (uint256) {
if (totalSupply[_ibToken] == 0) {
return rewardPerTokenStored[_ibToken];
} | function _accrueInterest(MarketParams memory marketParams, Id id) internal {
uint256 elapsed = block.timestamp - market[id].lastUpdate;
if (elapsed == 0) return;
if (marketParams.irm != address(0)) {
@> uint256 borrowRate = IIrm(marketParams.irm).borrowRate(marketParams, market[id]);
@> uint256 inter... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: Malicious proposer can use pregen_info to drain vault assets through sandwich attack. **Details**
[AdapterVault.vy#L662](https://github.com/adapter-fi/AdapterVault/blob/3c2895a69ad5eb2c4be16d454f63a6f2f074f351/contracts/AdapterVault.vy#L662)
self._balanceAdapters(claim_amount, pregen_info)
When cl... | pg: PregenInfo = empty(PregenInfo)
if len(pregen_info) > 0:
pg = _abi_decode(pregen_info, PregenInfo)
else:
#Info not provided, compute it expensively
pg.approx_params_swapExactYtForPt = self.default_approx_params()
pg.approx_params_swapExactTokenForPt = self.default_approx_params()
ytToPTL: uint256 = 0
pg.mint_returns... | function prepareCondition(
...
) public returns (ConditionID) {
// Limit of 256 because we use a partition array that is a number of 256 bits.
if (outcomeSlotCount < 2 || outcomeSlotCount > 255) revert InvalidOutcomeSlotsAmount();
// If not prepared, initialize, and emit the event, otherwise just return existing condi... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Failure to pass \_withdraw_only to \_getBalanceTXs allows any withdrawing user to drain vault assets through sandwich attack. **Details**
[AdapterVault.vy#L1045-L1060](https://github.com/adapter-fi/AdapterVault/blob/3c2895a69ad5eb2c4be16d454f63a6f2f074f351/contracts/AdapterVault.vy#L1045-L1060)
def... | def _balanceAdapters( _target_asset_balance: uint256, pregen_info: DynArray[Bytes[4096], MAX_ADAPTERS], _withdraw_only : bool = False, _max_txs: uint8 = MAX_BALTX_DEPOSIT ):
# Make sure we have enough assets to send to _receiver.
txs: BalanceTX[MAX_ADAPTERS] = empty(BalanceTX[MAX_ADAPTERS])
blocked_adapters: address[MA... | try
optionsContract.unlock(
params.optionId,
params.closingPrice,
publisherSignInfo.timestamp,
params.isAbove
)
{} catch Error(string memory reason) {
emit FailUnlock(params.optionId, params.targetContract, reason);
continue;
} | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: ADAPTER_BREAKS_LOSS_POINT is too tight for volatile assets leading to near constant adapter blocking. **Details**
[FundsAllocator.vy#L14](https://github.com/adapter-fi/AdapterVault/blob/3c2895a69ad5eb2c4be16d454f63a6f2f074f351/contracts/FundsAllocator.vy#L14)
ADAPTER_BREAKS_LOSS_POINT : constant(... | adapter_brakes_limit : uint256 = adapter.last_value - convert(convert(adapter.last_value, decimal) * ADAPTER_BREAKS_LOSS_POINT, uint256)
if adapter.current < adapter_brakes_limit:
# We've lost value in this adapter! Don't give it more money!
blocked_adapters[blocked_pos] = adapter.adapter
blocked_pos += 1
adapter.delta... | if (
!Validator.verifyMarketDirection(
params,
queuedTrade,
optionInfo.signer
)
) {
emit FailUnlock(
params.optionId,
params.targetContract,
"Router: Wrong market direction"
);
continue;
} | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Withdraw and deposit methodology leads to valuation exploits under certain circumstances. **Details**
[FundsAllocator.vy#L107-L117](https://github.com/adapter-fi/AdapterVault/blob/3c2895a69ad5eb2c4be16d454f63a6f2f074f351/contracts/FundsAllocator.vy#L107-L117)
for pos in range(MAX_ADAPTERS):
... | elif adapter.current > 0:
withdraw : uint256 = min(target_withdraw_balance, adapter.current)
target_withdraw_balance = target_withdraw_balance - withdraw
adapter.delta = convert(withdraw, int256) * -1
if adapter.delta != 0:
adapter_assets_allocated += convert(adapter.delta * -1, uint256) # TODO : eliminate adapter_... | function calcFunding(uint256 collateralAdded, uint256 totalShares, uint256 poolValue)
internal
pure
returns (uint256 sharesMinted)
{
if (totalShares == 0) {
// funding when LP pool is empty
sharesMinted = collateralAdded;
} else {
// mint LP tokens proportional to how much value the new investment
// brings to the pool | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: PT donation attack will DOS spell deposit permanently. **Details**
[PendleSpell.sol#L128-L137](https://github.com/Blueberryfi/blueberry-core/blob/d0ed24769704cf5d9a8b0616cf534f29db32f6ca/contracts/spell/PendleSpell.sol#L128-L137)
(uint256 ptAmount, , ) = IPendleRouter(_pendleRouter).swapExactToke... | (uint256 ptAmount, , ) = IPendleRouter(_pendleRouter).swapExactTokenForPt(
address(this),
market,
minPtOut,
params,
input,
limitOrder
); | elif adapter.current > 0:
withdraw : uint256 = min(target_withdraw_balance, adapter.current)
target_withdraw_balance = target_withdraw_balance - withdraw
adapter.delta = convert(withdraw, int256) * -1
if adapter.delta != 0:
adapter_assets_allocated += convert(adapter.delta * -1, uint256) # TODO : eliminate adapter_... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
LOW severity: Events in BatchBet can be spoofed using custom pool/market. **Details**
[BatchBet.sol#L89-L111](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/7b61ff6631091056be51bf0bd88377560f6986f7/contracts/markets/BatchBet.sol#L89-L111)
for (uint256 i = 0; i < buys.length; i++) {
@> addres... | (, uint256 feeAmount,) = IMarketMakerV1_2(market).buyFor(
buyer,
buys[i].investmentAmount,
buys[i].outcomeIndex,
buys[i].minOutcomeTokensToBuy,
extraFeeDecimal,
feeProfileId
);
totalFees += feeAmount;
}
if (totalInvestment > 0 && (data.length > 0 || affiliate != address(0x0))) {
@> emit BuyWithData(buyer, affilia... | (uint256 ptAmount, , ) = IPendleRouter(_pendleRouter).swapExactTokenForPt(
address(this),
market,
minPtOut,
params,
input,
limitOrder
); | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: BloomPool#redeemBorrower fails to decrement \_idToTotalBorrowed leading to large portions of borrower funds being permanently trapped in the contract. **Details**
[BloomPool.sol#L133-L136](https://github.com/Blueberryfi/bloom-v2/blob/87a60380331cc914be41ad57691f08b532a4d6fb/src/BloomPool.sol#L133-L136)
... | _idToCollateral[id].assetAmount -= uint128(reward);
_tbyBorrowerReturns[id] -= reward;
_borrowerAmounts[msg.sender][id] -= borrowAmount; | function getTargetBalance()
public
view
returns (AmmMath.TargetContext memory targetContext, uint256[] memory fairPriceDecimals)
{
// The logic is such that any excess collateral is always returned to the parent
uint256 localReserves = reserves();
assert(localReserves == 0);
function buyFor(
...
) public returns (uint... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: BloomPool#\_normalize price will cause severe mis-pricing for RWAs that are not 18 dp. **Details**
[BloomPool.sol#L349-L351](https://github.com/Blueberryfi/bloom-v2/blob/87a60380331cc914be41ad57691f08b532a4d6fb/src/BloomPool.sol#L349-L351)
uint256 totalValue = (existingCollateral.mulWad(startPrice)... | uint256 totalValue = (existingCollateral.mulWad(startPrice) + amount.mulWad(currentPrice)) / _rwaScalingFactor;
uint256 totalCollateral = existingCollateral + amount;
return uint128(totalValue.divWad(totalCollateral)); | function _reevaluateGainsOnPool(bool force) private returns (uint256 fees) {
uint256 lastBlock = lastFeeEvaluationBlock;
uint256 period = feeEvaluationBlockPeriod;
if (!force && (block.number - lastBlock <= period)) return fees;
lastFeeEvaluationBlock = uint64(block.number);
uint256 poolValue = getPoolValue();
if (poo... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Malicious borrower can repeatedly fill then kill orders to permanently lock funds of lenders and other borrowers. **Details**
[Orderbook.sol#L118-L133](https://github.com/Blueberryfi/bloom-v2/blob/87a60380331cc914be41ad57691f08b532a4d6fb/src/Orderbook.sol#L118-L133)
function killBorrowerMatch(addre... | uint256 len = matches.length;
for (uint256 i = 0; i != len; ++i) {
if (matches[i].borrower == msg.sender) {
lenderAmount = uint256(matches[i].lCollateral);
borrowerReturn = uint256(matches[i].bCollateral);
// Zero out the match order to preserve the array's order
matches[i] = MatchOrder({lCollateral: 0, bCollateral: 0,... | uint256 transferTokenXAmount = tokenXAmount > ll.amount
? ll.amount
: tokenXAmount; | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Yield spread cannot be decrease without causing significant loss to the stUSDC pool. **Details**
[StUsdc.sol#L313-L324](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/token/StUsdc.sol#L313-L324)
function _liveTbyValue(IBloomPool pool) interna... | function _liveTbyValue(IBloomPool pool) internal view returns (uint256 value) {
uint256 startingId = lastRedeemedTbyId();
// Because we start at type(uint256).max, we need to increment and overflow to 0.
unchecked {
startingId++;
}
uint256 lastMintedId = pool.lastMintedId();
if (lastMintedId == type(uint256).max) retur... | function prepareCondition(
...
) public returns (ConditionID) {
// Limit of 256 because we use a partition array that is a number of 256 bits.
if (outcomeSlotCount < 2 || outcomeSlotCount > 255) revert InvalidOutcomeSlotsAmount();
// If not prepared, initialize, and emit the event, otherwise just return existing condi... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: The yield distribution methodology for stUSDC#poke will lead to substantial loss of yield due to MEV for both stUSDC and StakeUpStaking. **Details**
[StUsdc.sol#L166-L185](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/token/StUsdc.sol#L166-L185)
... | uint256 globalShares_ = _globalShares;
uint256 protocolValue = _protocolValue(pool);
uint256 newUsdPerShare = protocolValue.divWad(globalShares_);
uint256 lastUsdPerShare = _lastUsdPerShare;
if (newUsdPerShare > lastUsdPerShare) {
uint256 yieldPerShare = newUsdPerShare - lastUsdPerShare;
// Calculate performance fee
u... | function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
if (from != address(0)) {
// LP tokens being transferred away from a funder - any fees that
// have accumulated so far due to trading activity should be given
// to the original owner for the period of time he held the LP
// tok... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Shares of stUSDC can be lost/gained during cross chain transfers due to differing conversion rates across chains. **Details**
[StUsdcLite.sol#L418-L428](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/token/StUsdcLite.sol#L418-L428)
function _... | function _debit(uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid)
internal
override
returns (uint256 amountSentLD, uint256 amountReceivedLD)
{
(amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);
uint256 shares = sharesByUsd(amountSentLD);
_burnShares(msg.sender, shares);
_setTotalUs... | function liquidatePosition(address _vault, address _target, uint256 _debtToRepay, uint256 _sharesToLiquidate)
external
{
if (msg.sender != liquidationManager) {
revert OnlyLiquidatorManager();
}
// Debt and collateral shares are adjusted for the liquidated account
_debtSnapshot[_target][_vault] -= _debtToRepay;
collate... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: SUP rewards will be completely lost when depositing TBYs to stUSDC via wstUSDC. **Details**
[StUsdc.sol#L118-L130](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/token/StUsdc.sol#L118-L130)
function depositTby(uint256 tbyId, uint256 amount) e... | function depositTby(uint256 tbyId, uint256 amount) external nonReentrant returns (uint256 amountMinted) {
IBloomPool pool = _bloomPool;
require(amount > 0, Errors.ZeroAmount());
require(!pool.isTbyRedeemable(tbyId), Errors.RedeemableTbyNotAllowed());
// If the token is a TBY, we need to get the current exchange rate of... | function removeCollateral(uint256 sharesToBurn)
external
whenNotPaused
returns (uint256 collateralReturned, uint256 sharesBurnt)
{
address funder = _msgSender();
// force re-evaluation because some value is exiting
_reevaluateGainsOnPool(true);
uint256[] memory noTokens = new uint256[](0);
emit FundingRemoved(funder, ... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: TBY#burn incorrectly burns id 0 for all burns causing complete loss of funds for lenders. **Details**
[Tby.sol#L78-L82](https://github.com/Blueberryfi/bloom-v2/blob/87a60380331cc914be41ad57691f08b532a4d6fb/src/token/Tby.sol#L78-L82)
function burn(uint256 id, address account, uint256 amount) externa... | function burn(uint256 id, address account, uint256 amount) external onlyBloom {
_totalSupply[id] -= amount;
_burn(account, 0, amount);
emit Burn(account, id, amount);
} | function liquidatePosition(address _vault, address _target, uint256 _debtToRepay, uint256 _sharesToLiquidate)
external
{
if (msg.sender != liquidationManager) {
revert OnlyLiquidatorManager();
}
// Debt and collateral shares are adjusted for the liquidated account
_debtSnapshot[_target][_vault] -= _debtToRepay;
collate... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: \_convertMatchOrders will fail to function properly for lenders if any borrower has canceled a matched order. **Details**
function killBorrowerMatch(address lender) external returns (uint256 lenderAmount, uint256 borrowerReturn) {
MatchOrder[] storage matches = _userMatchedOrders[lender];
... | uint256 len = matches.length;
for (uint256 i = 0; i != len; ++i) {
if (matches[i].borrower == msg.sender) {
lenderAmount = uint256(matches[i].lCollateral);
borrowerReturn = uint256(matches[i].bCollateral);
// Zero out the match order to preserve the array's order
matches[i] = MatchOrder({lCollateral: 0, bCollateral: 0,... | function prepareCondition(
...
) public returns (ConditionID) {
// Limit of 256 because we use a partition array that is a number of 256 bits.
if (outcomeSlotCount < 2 || outcomeSlotCount > 255) revert InvalidOutcomeSlotsAmount();
// If not prepared, initialize, and emit the event, otherwise just return existing condi... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: In the event of a partial match inside \_convertMatchOrders, borrower funds will be over-allocated. **Details**
[BloomPool.sol#L399-L403](https://github.com/Blueberryfi/bloom-v2/blob/87a60380331cc914be41ad57691f08b532a4d6fb/src/BloomPool.sol#L399-L403)
if (lenderFunds == matches[index].lCollatera... | if (lenderFunds == matches[index].lCollateral) {
matches.pop();
} else {
matches[index].lCollateral -= uint128(lenderFunds);
} | elif adapter.current > 0:
withdraw : uint256 = min(target_withdraw_balance, adapter.current)
target_withdraw_balance = target_withdraw_balance - withdraw
adapter.delta = convert(withdraw, int256) * -1
if adapter.delta != 0:
adapter_assets_allocated += convert(adapter.delta * -1, uint256) # TODO : eliminate adapter_... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Using address rather than bytes32 for destinationAddress in wstUsdcBridge#bridgeWstUsdc causes incompatibility with chains that utilize 32 byte addresses. **Details**
[WstUsdcBridge.sol#L44-L49](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/mes... | function bridgeWstUsdc(
address destinationAddress, <- @audit uses address instead of bytes32
uint256 wstUsdcAmount,
uint32 dstEid,
LzSettings calldata settings
) external payable returns (LzBridgeReceipt memory bridgingReceipt) { | if (blbIsToken0) {
return FullMath.mulDiv(_priceX96, 10 ** (18 + BLB_DECIMALS stableDecimals), 2 ** 96);
} else {
uint256 inversePrice = FullMath.mulDiv(_priceX96, 10 ** (18 - BLB_DECIMALS + stableDecimals), 2 ** 96);
return 10**36 / inversePrice;
} | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: stUSDC#deposit compares current tby price with potentially stale pool price which can lead to small yield loss for pool. **Details**
[StUsdc.sol#L154-L157](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/token/StUsdc.sol#L154-L157)
function ... | function poke() external nonReentrant {
uint256 currentTimestamp = block.timestamp;
uint256 lastUpdate = _lastRateUpdate;
if (currentTimestamp - lastUpdate < 24 hours) return;
function depositTby(uint256 tbyId, uint256 amount) external nonReentrant returns (uint256 amountMinted) {
IBloomPool pool = _bloomPool;
require... | (uint256 ptAmount, , ) = IPendleRouter(_pendleRouter).swapExactTokenForPt(
address(this),
market,
minPtOut,
params,
input,
limitOrder
); | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: In the event of yield loss, yield will be double counted leading to excess fees. **Details**
[StUsdc.sol#L171-L181](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/token/StUsdc.sol#L171-L181)
if (newUsdPerShare > lastUsdPerShare) {
u... | if (newUsdPerShare > lastUsdPerShare) {
uint256 yieldPerShare = newUsdPerShare - lastUsdPerShare;
// Calculate performance fee
uint256 fee = _calculateFee(yieldPerShare, globalShares_);
// Calculate the new total value of the protocol for users
uint256 userValue = protocolValue - fee;
newUsdPerShare = userValue.divWad(... | function _afterTokenTransfer(address from, address to, uint256 amount) internal override {
// When address other than parent gets shares, immediately eject them to
// maintain invariant that all funding is by parent
if (from == getParentPool() && to != address(0x0)) {
_removeFunding(to, amount);
}
}
function _removeFu... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: SUP rewards for depositing TBYs can be gamed by depositing TBYs that are close to expiration. **Details**
[StUsdc.sol#L118-L130](https://github.com/stakeup-protocol/stakeup-contracts/blob/b4d8a83e9455efb8c7543a0fc62b5aea598c7f49/src/token/StUsdc.sol#L118-L130)
function depositTby(uint256 tbyId, u... | function depositTby(uint256 tbyId, uint256 amount) external nonReentrant returns (uint256 amountMinted) {
IBloomPool pool = _bloomPool;
require(amount > 0, Errors.ZeroAmount());
require(!pool.isTbyRedeemable(tbyId), Errors.RedeemableTbyNotAllowed());
// If the token is a TBY, we need to get the current exchange rate of... | uint256 vestIndexLength = vests.length;
if (vesting[msg.sender].length < vestIndexLength) {
revert InvalidLength();
} | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: Donations to MarketMaker will completely freeze all buy/sell capability of market. **Details**
[MarketMaker.sol#L672-L679](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/64157824f67d6000588ae4235a49ccd24dede5c3/contracts/markets/MarketMaker.sol#L672-L679)
function getTargetBalance()
... | function getTargetBalance()
public
view
returns (AmmMath.TargetContext memory targetContext, uint256[] memory fairPriceDecimals)
{
// The logic is such that any excess collateral is always returned to the parent
uint256 localReserves = reserves();
assert(localReserves == 0);
function buyFor(
...
) public returns (uint... | uint256 transferTokenXAmount = tokenXAmount > ll.amount
? ll.amount
: tokenXAmount; | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Frontrunning or reorg attacks can be used to corrupt initial pricing data to drain funds from MarketMaker. **Details**
[ConditionalTokens.sol#L92-L131](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/64157824f67d6000588ae4235a49ccd24dede5c3/contracts/conditions/ConditionalTokens.sol#L92-L131)
... | function prepareCondition(
...
) public returns (ConditionID) {
// Limit of 256 because we use a partition array that is a number of 256 bits.
if (outcomeSlotCount < 2 || outcomeSlotCount > 255) revert InvalidOutcomeSlotsAmount();
// If not prepared, initialize, and emit the event, otherwise just return existing condi... | adapter_brakes_limit : uint256 = adapter.last_value - convert(convert(adapter.last_value, decimal) * ADAPTER_BREAKS_LOSS_POINT, uint256)
if adapter.current < adapter_brakes_limit:
# We've lost value in this adapter! Don't give it more money!
blocked_adapters[blocked_pos] = adapter.adapter
blocked_pos += 1
adapter.delta... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Sending child shares before burning shares allow reentrancy vulnerability in ParentFundingPool#removeChildShares. **Details**
[MarketMaker.sol#L268-L274](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/64157824f67d6000588ae4235a49ccd24dede5c3/contracts/markets/MarketMaker.sol#L268-L274)
... | function _afterTokenTransfer(address from, address to, uint256 amount) internal override {
// When address other than parent gets shares, immediately eject them to
// maintain invariant that all funding is by parent
if (from == getParentPool() && to != address(0x0)) {
_removeFunding(to, amount);
}
}
function _removeFu... | function depositTby(uint256 tbyId, uint256 amount) external nonReentrant returns (uint256 amountMinted) {
IBloomPool pool = _bloomPool;
require(amount > 0, Errors.ZeroAmount());
require(!pool.isTbyRedeemable(tbyId), Errors.RedeemableTbyNotAllowed());
// If the token is a TBY, we need to get the current exchange rate of... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: Fees will be lost in the event that a user withdraws from MarketFundingPool and there isn't enough reserves to cover fees. **Details**
[ParentFundingPool.sol#L631-L646](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/64157824f67d6000588ae4235a49ccd24dede5c3/contracts/funding/ParentFundingPool.... | function _reevaluateGainsOnPool(bool force) private returns (uint256 fees) {
uint256 lastBlock = lastFeeEvaluationBlock;
uint256 period = feeEvaluationBlockPeriod;
if (!force && (block.number - lastBlock <= period)) return fees;
lastFeeEvaluationBlock = uint64(block.number);
uint256 poolValue = getPoolValue();
if (poo... | function burn(uint256 id, address account, uint256 amount) external onlyBloom {
_totalSupply[id] -= amount;
_burn(account, 0, amount);
emit Burn(account, id, amount);
} | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: ParentFundingPool#removeCollateral fails to update valueHighPoint resulting in lost fees. **Details**
[ParentFundingPool.sol#L233-L251](https://github.com/SportsFI-UBet/ubet-contracts-v1/blob/64157824f67d6000588ae4235a49ccd24dede5c3/contracts/funding/ParentFundingPool.sol#L233-L251)
function remo... | function removeCollateral(uint256 sharesToBurn)
external
whenNotPaused
returns (uint256 collateralReturned, uint256 sharesBurnt)
{
address funder = _msgSender();
// force re-evaluation because some value is exiting
_reevaluateGainsOnPool(true);
uint256[] memory noTokens = new uint256[](0);
emit FundingRemoved(funder, ... | function _liveTbyValue(IBloomPool pool) internal view returns (uint256 value) {
uint256 startingId = lastRedeemedTbyId();
// Because we start at type(uint256).max, we need to increment and overflow to 0.
unchecked {
startingId++;
}
uint256 lastMintedId = pool.lastMintedId();
if (lastMintedId == type(uint256).max) retur... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: `RewardDistributor#claim` will revert for tokens with expired locks leading to loss of rewards. **Details**
[RewardsDistributor.sol#L277-L287](https://github.com/hyperstable/contracts/blob/35db5f2d3c8c1adac30758357fbbcfe55f0144a3/src/governance/RewardsDistributor.sol#L277-L287)
function claim(u... | function claim(uint256 _tokenId) external returns (uint256) {
if (block.timestamp >= time_cursor) _checkpoint_total_supply();
uint256 _last_token_time = last_token_time;
_last_token_time = _last_token_time / WEEK * WEEK;
uint256 amount = _claim(_tokenId, voting_escrow, _last_token_time);
if (amount != 0) {
@> ... | function rewardPerToken(address _ibToken) public view returns (uint256) {
if (totalSupply[_ibToken] == 0) {
return rewardPerTokenStored[_ibToken];
} | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: `PositionManager#liquidatePosition` fails to update vaultDebt and vaultCollateral. **Details**
**First discovered by Dev team during audit period**
[PositionManager.sol#L169-L185](https://github.com/hyperstable/contracts/blob/35db5f2d3c8c1adac30758357fbbcfe55f0144a3/src/core/PositionManager.sol#L169-... | function liquidatePosition(address _vault, address _target, uint256 _debtToRepay, uint256 _sharesToLiquidate)
external
{
if (msg.sender != liquidationManager) {
revert OnlyLiquidatorManager();
}
// Debt and collateral shares are adjusted for the liquidated account
_debtSnapshot[_target][_vault] -= _debtToRepay;
collate... | elif adapter.current > 0:
withdraw : uint256 = min(target_withdraw_balance, adapter.current)
target_withdraw_balance = target_withdraw_balance - withdraw
adapter.delta = convert(withdraw, int256) * -1
if adapter.delta != 0:
adapter_assets_allocated += convert(adapter.delta * -1, uint256) # TODO : eliminate adapter_... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Airdrop supply methodology has been changed leading to excess token emissions. **Details**
[MerkleClaim.sol#L48-L69](https://github.com/velodrome-finance/v1/blob/de6b2a19b5174013112ad41f07cf98352bfe1f24/contracts/redeem/MerkleClaim.sol#L48-L69)
function claim(
address to,
... | function claim(
address to,
uint256 amount,
bytes32[] calldata proof
) external {
// Throw if address has already claimed tokens
require(!hasClaimed[to], "ALREADY_CLAIMED");
// Verify merkle proof, or revert if not in tree
bytes32 leaf = keccak256(abi.encodePacked(to, amount));
bool isValidLeaf = MerkleProof.verify(pr... | function _debit(uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid)
internal
override
returns (uint256 amountSentLD, uint256 amountReceivedLD)
{
(amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);
uint256 shares = sharesByUsd(amountSentLD);
_burnShares(msg.sender, shares);
_setTotalUs... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Curve gauge rewards can be griefed. **Details**
[Gauge.sol#L123-L131](https://github.com/hyperstable/contracts/blob/35db5f2d3c8c1adac30758357fbbcfe55f0144a3/src/governance/Gauge.sol#L123-L131)
function claimFees() external lock {
@> require(msg.sender == IVotingEscrow(_ve).team(), "o... | def claim_rewards(_addr: address = msg.sender, _receiver: address = ZERO_ADDRESS):
"""
@notice Claim available reward tokens for _addr
@param _addr Address to claim for
@param _receiver Address to transfer rewards to - if set to
ZERO_ADDRESS, uses the default reward receiver
for the caller
"""
if _receiver != ZERO_ADDR... | function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
if (from != address(0)) {
// LP tokens being transferred away from a funder - any fees that
// have accumulated so far due to trading activity should be given
// to the original owner for the period of time he held the LP
// tok... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: `AdaptiveIRM#_curve` multiples instead of dividing leading to "V" shaped curve instead of expected "L" shaped curve. **Details**
[AdaptiveIRM.sol#L110-L115](https://github.com/hyperstable/contracts/blob/35db5f2d3c8c1adac30758357fbbcfe55f0144a3/src/libraries/AdaptiveIRM.sol#L110-L115)
function... | function _curve(int256 _rateAtTarget, int256 err) private pure returns (int256) {
// Non negative because 1 - 1/C >= 0, C - 1 >= 0.
@> int256 coeff = err < 0 ? INT_WAD - INT_WAD.sMulWad(CURVE_STEEPNESS) : CURVE_STEEPNESS - INT_WAD;
// Non negative if _rateAtTarget >= 0 because if err < 0, coeff <= 1.
return (coeff... | function calcFunding(uint256 collateralAdded, uint256 totalShares, uint256 poolValue)
internal
pure
returns (uint256 sharesMinted)
{
if (totalShares == 0) {
// funding when LP pool is empty
sharesMinted = collateralAdded;
} else {
// mint LP tokens proportional to how much value the new investment
// brings to the pool | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: `AdaptiveIRM` has been integrated incorrectly and will not work as expected. **Details**
[Morpho.sol#L483-L509](https://github.com/morpho-org/morpho-blue/blob/eb65770e12c4cdae5836c0027e35b9c82794c3eb/src/Morpho.sol#L483-L509)
function _accrueInterest(MarketParams memory marketParams, Id id) i... | function _accrueInterest(MarketParams memory marketParams, Id id) internal {
uint256 elapsed = block.timestamp - market[id].lastUpdate;
if (elapsed == 0) return;
if (marketParams.irm != address(0)) {
@> uint256 borrowRate = IIrm(marketParams.irm).borrowRate(marketParams, market[id]);
@> uint256 inter... | uint256 len = matches.length;
for (uint256 i = 0; i != len; ++i) {
if (matches[i].borrower == msg.sender) {
lenderAmount = uint256(matches[i].lCollateral);
borrowerReturn = uint256(matches[i].bCollateral);
// Zero out the match order to preserve the array's order
matches[i] = MatchOrder({lCollateral: 0, bCollateral: 0,... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: No storage gap for upgradeable contracts. **Description:**
1. `__gap` is used in base upgradable contracts to avoid storage clashes while using inheritance.
2. It was observed that both `ERC721ACollection.sol`and `ERC20Token.sol`were missing the `\_\_gap`variable which could lead to... | uint256[50]private \_\_gap;
\ | function decimals() external pure returns (uint8 dec) {
dec = 8;
}
uint256 public constant TARGET_DIGITS = 18;
function _scalePriceByDigits(uint256 _price, uint256 _answerDigits) internal pure returns (uint256 scaledPrice) {
if (_answerDigits == TARGET_DIGITS) {
scaledPrice = _price;
} else if (_a... | random | Solodit | HIGH | 2 | |
HIGH severity: `initialize`functions not protected. **Description:**
ERC20Token is an upgradeable contract that does not protect its initialize functions from inherited contracts.
**Recommendations:**
Add constructor to ERC20 contract as mentioned in the OpenZeppelin docs... | /// @custom:oz-upgrades-unsafe-allow constructor
constructor(){
\_disableInitializers();
}
\ | assert(!registry.hasRole(REMOVE_TOKEN_FROM_ALLOWED_LIST_ROLE, address(this)));
assert(!registry.hasRole(DEFAULT_ADMIN_ROLE, address(this))); | random | Solodit | HIGH | 2 | |
HIGH severity: Basic validation missing on `mint`and `mintTo`. **Description:**
Observe that both `mint`and `mintTo`functions are missing basic validation for `to`address,amount/quantity.
**Recommendations:**
Add below to mint &mintTo function at ERC20Token.sol
\
Add below to mint &mintTo function at ERC721AColl... | require(to!=address(0)&&amount>0,""Incorrect params"");
\
require(quantity>0 &&to!=address(0),""Incorrect params"");// for mintTo require(quantity>0,""Incorrect params"");// for mint
\ | function addLock(
bytes32 Id,
bytes32 hashlock,
uint48 timelock
) external _exists(Id) _validTimelock(timelock) nonReentrant returns (bytes32) {
HTLC storage htlc = contracts[Id];
if (htlc.claimed == 2 || htlc.claimed == 3) revert AlreadyClaimed();
if (msg.sender == htlc.sender) {
if (ht... | random | Solodit | HIGH | 2 | |
MEDIUM severity: Specified `minOutput` will remain locked in `LSSVMRouter::swapNFTsForSpecificNFTsThroughETH`. **Description:**
The Cyfrin team understands that `LSSVMRouter` is slightly out of scope for this audit, given that it is intended to be deprecated and replaced by `VeryFastRouter`; however, a slightly modifie... | diff --git a/src/test/interfaces/ILSSVMPairFactoryMainnet.sol b/src/test/interfaces/ILSSVMPairFactoryMainnet.sol
new file mode 100644
index 0000000..3cdea5b
--- /dev/null
+++ b/src/test/interfaces/ILSSVMPairFactoryMainnet.sol
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.0;
+
+import {IERC721}... | /// handle a received message
function _ccipReceive(Client.Any2EVMMessage memory any2EvmMessage) internal override {
bytes memory message = abi.decode(any2EvmMessage.data, (bytes)); // abi-decoding of the sent text
BridgeSendPayload memory payload = Codec.decodeBridgeSendPayload(message);
bytes32 _hash = ke... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: Malicious pair can re-enter `VeryFastRouter` to drain original caller's funds. **Description:**
[`VeryFastRouter::swap`](https://github.com/sudoswap/lssvm2/blob/78d38753b2042d7813132f26e5573c6699b605ef/src/VeryFastRouter.sol#L266) is the main entry point for a user to perform a batch of sell and buy orde... | diff --git a/src/VeryFastRouter.sol b/src/VeryFastRouter.sol
index 16047b9..2bd3797 100644
--- a/src/VeryFastRouter.sol
+++ b/src/VeryFastRouter.sol
@@ -85,6 +85,7 @@ contract VeryFastRouter {
error VeryFastRouter__InvalidPair();
error VeryFastRouter__BondingCurveQuoteError();
+ event vfr_log_named_uint ... | File: factory/PoolFactory.sol
43: event DaoPoolDeployed(
File: gov/ERC721/multipliers/AbstractERC721Multiplier.sol
25: event Minted(uint256 tokenId, address to, uint256 multiplier, uint256 duration);
26: event Locked(uint256 tokenId, address sender, bool isLocked);
27: event Changed(uint256 tokenId... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Linearity assumption on the royalty can lead to denial of service. **Description:**
`VeryFastRouter::swap` relies on the internal functions [`VeryFastRouter::_findMaxFillableAmtForSell`](https://github.com/sudoswap/lssvm2/blob/78d38753b2042d7813132f26e5573c6699b605ef/src/VeryFastRouter.sol#L556) and... | VeryFastRouter.sol
576: // Perform binary search
577: while (start <= end) {
578: // We check the price to sell index + 1
579: (
580: CurveErrorCodes.Error error,
581: /* newSpotPrice */
582: ,
583: /* newDelta */
58... | function checkWalletsForList(address _from, address _to) private {
if (super.balanceOf(_from) == 0) {
removeWalletFromList(_from);
}
function removeWallet(address _address, string memory _id) public override onlyExchangeOrAbove walletExists(_address) walletBelongsToInvestor(_address, _id) returns (bool... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Possible reverts due to using stricter requirements in inner swap. **Description:**
`VeryFastRouter::swap` relies on the internal functions `VeryFastRouter::_findMaxFillableAmtForSell` and `VeryFastRouter::_findMaxFillableAmtForBuy` to find the maximum possible amount of tokens to be swapped.
The output ... | VeryFastRouter.sol
326: uint256 numItemsToFill;
327: uint256 priceToFillAt;
328:
329: {
330: // Grab royalty for calc in _findMaxFillableAmtForSell
331: (,, uint256 royaltyAmount) = order.pair.calculateRoyaltiesView(
332: ... | uint256 scaleDown = 10 ** (18 - d);
execPrice = rawExecPriceWad / scaleDown;
function _pricingFromCurveBuy(
uint256 amountInQuote,
uint256 curvePriceWad,
uint256 anchorPriceWad
) internal view returns (uint256 baseOut, uint256 execPriceWad) {
require(anchorPriceWad > 0, "anchor=0"... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: GDACurve does not validate new spot price. **Description:**
The new spot price calculated in `GDACurve::getBuyInfo` and `GDACurve::getSellInfo` is not currently validated against `MIN_PRICE`, meaning that the price could fall below this value.
While a minimum price check is performed explicitly in `GD... | GDACurve.sol (Line 81-91)
// The new spot price is multiplied by alpha^n and divided by the time decay so future
// calculations do not need to track number of items sold or the initial time/price. This new spot price
// implicitly stores the initial price, total items sold so far, and time ela... | // new import at top
import { IVerifierProxy } from "@zaros/external/chainlink/interfaces/IVerifierProxy.sol";
function test_ImpossibleToClosePositionIfSettlementDisabledButStillLiquidatable() external {
// give naruto some tokens
uint256 USER_STARTING_BALANCE = 100_000e18;
int128 USER_POS_SIZE_DELTA = ... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Binary search implementation may not always find the optimal solution. **Description:**
`VeryFastRouter::_findMaxFillableAmtForBuy` and `VeryFastRouter::_findMaxFillableAmtForSell` utilize binary search to determine the maximum trade amount. The binary search seeks a solution in a linear, sorted space ... | function testSwapBinarySearch_audit() public{
//START_INDEX=0, END_INDEX=10
uint256[] memory nftIds;
LSSVMPair pair;
uint256 numNFTsForQuote = END_INDEX + 1;
//1. create an array of nft ids
nftIds = _getArray(START_INDEX, END_INDEX);
assertEq(nftIds.length, END_I... | // Send Relayer message
wormholeRelayer.sendPayloadToEvm{value: msg.value} (
targetChain,
targetAddress,
abi.encode(
investorDetail.investorId,
value,
msg.sender,
investorDetail.country,
investorD... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: Owner calling `LSSVMPair::changeSpotPrice` can cause arithmetic over/underflows on later swaps. **Description:**
Changing the spot price to a value higher than the current ERC20 (or ETH) balance of the pair can cause unintended reverts in valid swap calls later on.
**Proof of Concept:**
Full proof of c... | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "forge-std/Test.sol";
import {InvariantERC721LinearERC20} from "./InvariantERC721LinearERC20.t.sol";
import {IERC721Mintable} from "../interfaces/IERC721Mintable.sol";
contract SwapArithmeticOverflow is InvariantERC721LinearERC20 {
function setUp() p... | function lock(uint256 amount) external {
uint256 mintAmount = _GiBGTMintAmount(amount);
poolSize += amount;
_refreshiBGT(amount); //@audit should call after depositing funds
SafeTransferLib.safeTransferFrom(ibgt, msg.sender, address(this), amount);
_mint(msg.sender, mintAmount);
emit iBGTLock(ms... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Unreachable code path in `RoyaltyEngine::_getRoyaltyAndSpec`. Within `RoyaltyEngine`, `int16` values have been copied over from the manifold contract for use as enum values relating to different royalty specifications with `int16 private constant NONE = -1;` and `int16 private constant NOT_CONFIGURED = 0... | if (spec == NONE) {
return (recipients, amounts, spec, royaltyAddress, addToCache);
} | // whitelist reward distributors for transferring Karma tokens
karma.setAllowedToTransfer(address(stakeManager), true);
console.log("Whitelisted reward distributor (StakeManager)", address(stakeManager), "for transfer");
@> karma.setAllowedToTransfer(address(stakeManager), true);
console.lo... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
LOW severity: <a name="GAS-4"></a>[GAS-4] Using bools for storage incurs overhead. Use uint256(1) and uint256(2) for true/false to avoid a Gwarmaccess (100 gas), and to avoid Gsset (20000 gas) when changing from ‘false’ to ‘true’, after having been ‘true’ in the past. See [source](https://github.com/OpenZeppelin/openze... | File: LSSVMPairFactory.sol
56: mapping(ICurve => bool) public bondingCurveAllowed;
57: mapping(address => bool) public override callAllowed;
60: mapping(address => mapping(address => bool)) public settingsForCollection; | function K(PoolId) internal view virtual returns (uint48) {
return 7200;
}
uint48 internal immutable _K;
function K(PoolId) internal view virtual override returns (uint48) {
return _K;
}
Mainnet
AMAMM_K_1=7200
Arbitrum
AMAMM_K_42161=345600
Base
AMAMM_K_8453=43200
Unichain
AMAMM_K_130=86400 | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: <a name="GAS-5"></a>[GAS-5] Cache array length outside of loop. If not cached, the solidity compiler will always read the length of the array during each iteration. That is, if it is a storage array, this is an extra sload operation (100 additional extra gas for each iteration except for the first) and i... | File: LSSVMPair.sol
673: for (uint256 i; i < calls.length;) {
File: LSSVMPairERC20.sol
68: for (uint256 i; i < royaltyRecipients.length;) {
93: for (uint256 i; i < royaltyRecipients.length;) {
File: LSSVMPairETH.sol
57: for (uint256 i; i < royaltyRecipients.length;) { | /// @notice For regular EVK vaults, it transfers the specified amount of vault shares from the sender to the receiver
/// @dev For ERC721WrapperBase, transfers a proportional amount of ERC6909 tokens (calculated as totalSupply(tokenId) * amount / balanceOf(sender)) for each enabled tokenId from the sender to the receiv... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: <a name="GAS-7"></a>[GAS-7] Use Custom Errors. [Source](https://blog.soliditylang.org/2021/04/21/custom-errors/)
Instead of using error strings, to reduce deployment and runtime cost, you should use Custom Errors. This would save both deployment and runtime cost.
*Instances (21)*: | File: LSSVMRouter.sol
504: require(factory.isValidPair(msg.sender), "Not pair");
506: require(factory.getPairTokenType(msg.sender) == ILSSVMPairFactoryLike.PairTokenType.ERC20, "Not ERC20 pair");
522: require(factory.isValidPair(msg.sender), "Not pair");
536: require(factory.isValidP... | require(isTokenAccepted(token), "Token not accepted");
uint256 hostingFee = calculateHostingFee(duration);
uint256 totalRequiredToken = convertAvaxToToken(
token,
avaxStakeAmount + hostingFee
);
require(amount >= totalRequiredToken, "Insufficient token");
// Transfer tokens from the user to the contract
IERC... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
LOW severity: <a name="GAS-9"></a>[GAS-9] Using `private` rather than `public` for constants, saves gas. If needed, the values can be read from the verified contract source code, or if there are multiple values there can be a single getter function that [returns a tuple](https://github.com/code-423n4/2022-08-frax/blob/... | File: bonding-curves/ExponentialCurve.sol
15: uint256 public constant MIN_PRICE = 1000000 wei;
File: bonding-curves/GDACurve.sol
21: uint256 public constant MIN_PRICE = 1 gwei; | /* snip */
// now check rate limits
bool isAmountRateLimited = _isOutboundAmountRateLimited(internalAmount);
if (!shouldQueue && isAmountRateLimited) {
revert NotEnoughCapacity(getCurrentOutboundCapacity(), amount);
}
if (shouldQueue && isAmountRateLimited) {
// emit an event to notify the user that the transfe... | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: <a name="GAS-13"></a>[GAS-13] `internal` functions not called by the contract should be removed. If the functions are required by an interface, the contract should inherit from that interface and use the `override` keyword
*Instances (8)*: | File: lib/LSSVMPairCloner.sol
22: function cloneERC721ETHPair(
112: function cloneERC721ERC20Pair(
204: function isERC721ETHPairClone(address factory, address implementation, address query)
238: function isERC721ERC20PairClone(address factory, address implementation, address query)
274: add... | File: gov/ERC20/ERC20Gov.sol
55: for (uint256 i = 0; i < params.users.length; i++) {
File: gov/proposals/TokenSaleProposal.sol
82: for (uint256 i = 0; i < tierInitParams.length; i++) {
96: for (uint256 i = 0; i < requests.length; i++) {
102: for (uint256 i = 0; i < tierIds.length; i... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: <a name="N"></a>[NMissing checks for `address(0)` when assigning values to address state variables. *Instances (4)*: | File: LSSVMPairFactory.sol
110: _caller = _NOT_ENTERED;
349: _caller = _NOT_ENTERED;
File: lib/OwnableWithTransferCallback.sol
25: _owner = initialOwner;
71: _owner = newOwner; | function _updateAllUserState(IncentivizedPoolId id, address account) internal virtual {
if(!userLiquiditySynced[id][account]) {
_syncUserLiquidity(id, account);
userLiquiditySynced[id][account] = true;
}
address[] memory _tokens = poolRewards[id];
uint256 _length = _tokens.length;
f... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: <a name="N"></a>[N`require()` / `revert()` statements should have descriptive reason strings. *Instances (1)*: | File: LSSVMPairETH.sol
126: require(msg.data.length == _immutableParamsLength()); | function initiateMigration(uint256 _amount) external {
- if (_amount == 0) revert InvalidAmount();
+ if (_amount < queueDepositMin) revert InvalidAmount();
(uint256 minStakeAmount, ) = communityPool.getStakerLimits();
if (_amount < minStakeAmount) revert InvalidAmount(); | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: <a name="N"></a>[NEvent is missing `indexed` fields. Index event fields make the field more quickly accessible to off-chain tools 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). Eac... | File: LSSVMPair.sol
82: event SwapNFTInPair(uint256 amountIn, uint256[] ids);
83: event SwapNFTInPair(uint256 amountIn, uint256 numNFTs);
84: event SwapNFTOutPair(uint256 amountOut, uint256[] ids);
85: event SwapNFTOutPair(uint256 amountOut, uint256 numNFTs);
86: event SpotPriceUpdate(uint128 n... | function _buildBoost(
address[] calldata partnerNFTs,
uint256[] calldata partnerNFTIds
) internal returns (Boost memory newUserBoost) {
uint256 magnitude;
Boost storage userBoost = boosts[msg.sender];
if(userBoost.expiry == 0) {
...
}
else {
address[] storage nfts = userBoost.partner... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: <a name="N"></a>[NConstants should be defined rather than using magic numbers. *Instances (3)*: | File: settings/Splitter.sol
23: return _getArgAddress(20);
File: settings/StandardSettings.sol
70: return _getArgUint64(40);
77: return _getArgUint64(48); | contract IncentivizedERC20 is ERC20, Owned {
...
constructor(string memory name, string memory symbol, PoolId id) ERC20(name, symbol, 18) Owned(msg.sender) {
hook = msg.sender;
poolId = id;
}
...
}
function test_LessThan18Decimals() public {
MockERC20 token0WithLessDecimals = new Mo... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: <a name="N"></a>[NFunctions not used internally could be marked external. *Instances (28)*: | File: LSSVMPair.sol
323: function getAssetRecipient() public view returns (address payable) {
344: function getFeeRecipient() public view returns (address payable _feeRecipient) {
File: LSSVMPairFactory.sol
342: function openLock() public {
347: function closeLock() public {
499: function getS... | function setPoolFee(uint16 _poolFee) external {
require(ISolidlyV2Factory(factory).isFeeSetter(msg.sender) || msg.sender == copilot, 'UA');
if (msg.sender == copilot) {
require(_poolFee >= ISolidlyV2Factory(factory).minFee() && !copilotRevoked); // minimum fee enforced for copilot
} else {
r... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: <a name="N"></a>[NTypos. *Instances (84)*: | File: LSSVMPair.sol
- 52: // Sudoswap Royalty Engine
+ 52: // @notice Sudoswap Royalty Engine
- 60: // However, this should NOT be assumed, as bonding curves may use spotPrice in different ways.
+ 60: // @notice However, this should NOT be assumed, as bonding curves may use spotPrice in different ways... | modifier timeTransitions(uint256 marketId) {
if (block.timestamp > markets[marketId].closesAtTimestamp && markets[marketId].state == MarketState.open) {
_nextState(marketId);
}
_;
}
function testTradeRightAtMarketClose() public {
uint256 marketId = _createTestMarket();
// Get marke... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
LOW severity: <a name=""></a>`abi.encodePacked()` should not be used with dynamic types when passing the result to a hash function such as `keccak256()`. Use `abi.encode()` instead which will pad items to 32 bytes, which will [prevent hash collisions](https://docs.soliditylang.org/en/v0.8.13/abi-spec.html#non-standard-... | File: property-checking/MerklePropertyChecker.sol
25: if (!MerkleProof.verify(proof, root, keccak256(abi.encodePacked(ids[i])))) { | while (toUnbondRemaining != 0) {
// Process vault[i]...
++i;
if (i >= vaults.length) i = 0;
}
validatorWithdrawalIndex = i; // @audit This happens regardless of whether unbonding occurred on the last processed vault or not | same_firm_diff_protocol | Solodit | LOW | 2 | |
LOW severity: <a name=""></a>Empty Function Body - Consider commenting why. *Instances (32)*: | File: LSSVMPairETH.sol
130: function _preCallCheck(address) internal pure override {}
File: LSSVMPairFactory.sol
373: } catch {}
375: } catch {}
379: } catch {}
384: } catch {}
385: } catch {}
390: } catch {}
391: } catch {}
398: ... | it('Should demonstrate orphaned entity relationships after role removal', async function() {
const [owner, entityOwner, operator, resource] = await hre.ethers.getSigners();
const { trustService } = await loadFixture(deployDSTokenRegulated);
// Step 1: Give entityOwner ISSUER role
await trustSer... | same_firm_diff_protocol | Solodit | LOW | 2 | |
LOW severity: <a name=""></a>Initializers could be front-run. Initializers could be front-run, allowing an attacker to either set their own values, take ownership of the contract, and in the best case forcing a re-deployment
*Instances (10)*: | File: LSSVMPair.sol
132: function initialize(
140: __Ownable_init(_owner);
File: LSSVMPairFactory.sol
568: _pair.initialize(msg.sender, _assetRecipient, _delta, _fee, _spotPrice);
596: _pair.initialize(msg.sender, _assetRecipient, _delta, _fee, _spotPrice);
625: _pair.initializ... | uint256 _feeInUSD = _feeAmount * _tokenPrice / 10**18;
total = 1e6 (USDT) + 1e18 (DAI) = 1000000000001000000 wei-USD
uint8 decimals = IERC20Metadata(token).decimals(); // OZ ERC20Metadata
uint256 scale = 10 ** decimals; // token’s native unit
// feeAmount is already in token-units
... | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: <a name=""></a>Unsafe ERoperation(s). *Instances (7)*: | File: LSSVMPairFactory.sol
576: _nft.transferFrom(msg.sender, address(_pair), _initialNFTIDs[i]);
606: _nft.transferFrom(msg.sender, address(_pair), _initialNFTIDs[i]);
673: _nft.transferFrom(msg.sender, recipient, ids[i]);
File: LSSVMRouter.sol
525: nft.transferFrom(fro... | function cancelProposal(uint256 id) external {
require(msg.sender == babelCore.guardian(), "Only guardian can cancel proposals");
require(id < proposalData.length, "Invalid ID");
Action[] storage payload = proposalPayloads[id];
require(!_containsSetGuardianPayload(payload.length, payload), "Guardian re... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: <a name=""></a>Centralization Risk for trusted owners. **Impact:**
Contracts have owners with privileged rights to perform admin tasks and need to be trusted to not perform malicious updates or drain funds.
*Instances (23)*: | File: LSSVMPair.sol
582: function changeSpotPrice(uint128 newSpotPrice) external onlyOwner {
595: function changeDelta(uint128 newDelta) external onlyOwner {
610: function changeFee(uint96 newFee) external onlyOwner {
625: function changeAssetRecipient(address payable newRecipient) external onlyOwne... | // Validate vest duration is within bounds
// require!(dur_secs >= min_secs, ErrorCode::VestDurationTooShort);
// require!(dur_secs <= max_secs, ErrorCode::VestDurationTooLong); | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: <a name=""></a>Solmate's SafeTransferLib does not check for token contract's existence. There is a subtle difference between the implementation of solmate’s SafeTransferLib and OZ’s SafeERC20: OZ’s SafeERC20 checks if the token is a contract or not, solmate’s SafeTransferLib does not.
https://github.co... | File: LSSVMPairERC20.sol
90: token_.safeTransferFrom(msg.sender, _assetRecipient, inputAmountExcludingRoyalty - protocolFee);
94: token_.safeTransferFrom(msg.sender, royaltyRecipients[i], royaltyAmounts[i]);
102: token_.safeTransferFrom(msg.sender, address(factory()), prot... | function forceUpdateNodes(
address operator,
uint256 limitStake
) external updateStakeCache(getCurrentEpoch(), PRIMARY_ASSET_CLASS) onlyDuringFinalWindowOfEpoch updateGlobalNodeStakeOncePerEpoch {
// ... validation and setup code ...
// ... stake calculation logic ...
uint256 newStake = previo... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Calls to `LimitOrderRegistry::newOrder` might revert due to overflow. **Description:** Reasonable input could cause an arithmetic overflow when opening new orders because large multiplications are performed on variables defined as `uint128` instead of `uint256`. Specifically, in `LimitOrderRegistry::_m... | uint128 amount0Min = amount0 == 0 ? 0 : (amount0 * 0.9999e18) / 1e18;
uint128 amount1Min = amount1 == 0 ? 0 : (amount1 * 0.9999e18) / 1e18;
function test_OverflowingNewOrder() public {
uint96 amount = 340_316_398_560_794_542_918;
address msgSender = 0xE0b906ae06BfB1b54fad61E222b2E324D51e1da6;
deal(address(... | for (uint256 i = 0; i < proposers.length; i++) {
timelock.grantRole(timelock.PROPOSER_ROLE(), proposers[i]);
}
for (uint256 i = 0; i < executors.length; i++) {
timelock.grantRole(timelock.EXECUTOR_ROLE(), executors[i]);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/Test.sol";
i... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: New orders on a given pool in the opposite direction, separated by zero/one tick space, are not possible until previous `BatchOrder` is removed from the order book. **Description:** New order creation will revert with `LimitOrderRegistry__DirectionMisMatch()` if the direction opposes any existing order... | function testOppositeOrders() external {
uint256 amount = 1_000e6;
deal(address(USDC), address(this), amount);
// Current tick 204332
// 204367
// Current block 16371089
USDC.approve(address(registry), amount);
registry.newOrder(USDC_WETH_05_POOL, 204910, uint96(amount), true, 0);
// M... | function calculateCCSendTokenFeeAndMessage(
uint64 destinationChainSelector,
address messageReceiver,
address sender,
address recipient,
uint value,
bytes calldata extraArgs
)
public
view
returns (uint256 fee, Client.EVM2AnyMessage memory evm2A... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: Calls to `LimitOrderRegistry::cancelOrder` might revert due to overflow. **Description:** Reasonable input could cause an arithmetic overflow when cancelling orders because large multiplications are performed on variables defined as `uint128` instead of `uint256`. Specifically, when calculating the liq... | uint128 depositAmount = batchIdToUserDepositAmount[batchId][sender];
if (depositAmount == 0) revert LimitOrderRegistry__UserNotFound(sender, batchId);
// Remove one from the userCount.
order.userCount--;
// Zero out user balance.
delete batchIdToUserDepositAmount[batchId][sender];
uint128 orderAmount;
if (order.dire... | if (bal0 > 0) {
amount0 = bal0 * price() / PRECISION;
} | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: A malicious user can cancel an ITM order at a given target tick by calling `LimitOrderRegistry::cancelOrder` with the opposite direction, separated by one tick space. **Description:** Users are able to cancel their limit orders by calling `LimitOrderRegistry::cancelOrder`. By internally calling `_getOr... | function cancelOrder(
UniswapV3Pool pool,
int24 targetTick,
bool direction //@audit don't validate order.direction == direction
) external returns (uint128 amount0, uint128 amount1, uint128 batchId) {
uint256 positionId;
{
// Make sure order is OTM.
(,... | function cancelProposal(uint256 id) external {
require(msg.sender == babelCore.guardian(), "Only guardian can cancel proposals");
require(id < proposalData.length, "Invalid ID");
Action[] storage payload = proposalPayloads[id];
require(!_containsSetGuardianPayload(payload.length, payload), "Guardian re... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
LOW severity: Perform additional validation on Chainlink fast gas feed. **Description:** When consuming data feeds provided by Chainlink, it is important to validate a number of thresholds and return values. Without this, it is possible for a consuming contract to use stale or otherwise incorrect/invalid data. `LimitOr... | require(signedGasPrice > 0, "Negative gas price");
require(signedGasPrice < maxGasPrice, "Upper gas price bound breached");
require(signedGasPrice > minGasPrice, "Lower gas price bound breached");
require(answeredInRound >= roundID, "Round incomplete"); | if is_new_account(asset_token_acc) {
let decimals = *asset_mint
.data
.borrow()
.get(MINT_DECIMALS_OFFSET)
.ok_or_else(|| drv_err!(DeriverseErrorKind::InvalidClientDataFormat))?
as u32;
if !(MIN_DECS_COUNT..=MAX_DECS_COUNT).contains(&decimals)... | same_firm_diff_protocol | Solodit | LOW | 2 | |
LOW severity: Withdrawing native assets may revert if wrapped native balance is zero. **Description:** The function `LimitOrderRegistry::withdrawNative` allows the owner to withdraw native and wrapped native assets from the contract. If balances of both are zero, calls to this function revert as there is nothing to wit... | /**
* @notice Allows owner to withdraw wrapped native and native assets from this contract.
*/
function withdrawNative() external onlyOwner {
uint256 wrappedNativeBalance = WRAPPED_NATIVE.balanceOf(address(this));
uint256 nativeBalance = address(this).balance;
// Make sure there is something to withdraw.
... | function test_InvalidTickRangeCreation() public {
int24 lowerTick = -90;
int24 upperTick = 90;
// Pool with 20 tick spacing
initPool(key2.currency0, key2.currency1, IHooks(address(multiRange)), 1000, SQRT_PRICE_1_1);
rangeKey = RangeKey(id2, lowerTick, upperTick);
rangeId = rangeKey.toId();
... | same_firm_diff_protocol | Solodit | LOW | 2 | |
LOW severity: Fee-on-transfer/deflationary tokens will not be supported. **Description:** When creating a new order, `LimitOrderRegistry::newOrder` assumes that the amount of deposited tokens is equal to the
function parameter plus the balance before the deposit. For tokens which take a fee on every transfer, this assu... | uint128 amount0Min = amount0 == 0 ? 0 : (amount0 * 0.9999e18) / 1e18; | address _token0 = IHypervisor(_hypervisor).token0();
address _unwantedToken = IHypervisor(_hypervisor).token0() == _wantedToken ?
IHypervisor(_hypervisor).token1() :
_token0; | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: Improvements to use of ternary operator. There is currently one [instance](https://github.com/crispymangoes/uniswap-v3-limit-orders/blob/83f5db9cb90926c11ee6ce872dc165b7f600f3d8/src/LimitOrderRegistry.sol#L903) of ternary operator usage that can be simplified, with the boolean expression being evaluated ... | bool direction = targetTick > node.tickUpper ? true : false;
if (direction)
assetIn = poolToData[pool].token0;
else assetIn = poolToData[pool].token1;
assetIn = direction ? poolToData[pool].token0 : poolToData[pool].token1; | function recordBurn(address _who, uint256 _value) internal override returns (bool) {
if (compareInvestorBalance(_who, _value, _value)) {
adjustTotalInvestorsCounts(_who, CommonUtils.IncDec.Decrease);
}
return true;
} | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Protocol's invariants can be broken. **Description:** The protocol intends to provide a generalized framework for constant-function AMM liquidity pools.
We have identified some invariants that should hold at any given time. One of these invariants is `totalSupply() == calcLpTokenSupply(reserves)`, and we... | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IERC20} from "test/TestHelper.sol";
import {IWellFunction} from "src/functions/ConstantProduct2.sol";
import {LiquidityHelper} from "test/LiquidityHelper.sol";
import "forge-std/Test.sol";
import {MockToken} from "mocks/tokens/MockToken.sol";
contract ... | #[account]
pub struct StakeCounter {
pub count: u64,
}
impl StakeCounter {
pub const LEN: usize = 8;
} | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Each Well is responsible for ensuring that an `update` call cannot be made with a reserve of 0. **Description:** The current implementation of `GeoEmaAndCumSmaPump` assumes each well will call `update()` with non-zero reserves, as commented at the beginning of the file:
However, there is no actual requi... | /**
* @title GeoEmaAndCumSmaPump
* @author Publius
* @notice Stores a geometric EMA and cumulative geometric SMA for each reserve.
* @dev A Pump designed for use in Beanstalk with 2 tokens.
*
* This Pump has 3 main features:
* 1. Multi-block MEV resistence reserves
* 2. MEV-resistant Geometric EMA intended fo... | function burn(uint256 tokenId) public override whenNotPaused {
// require sender is owner or approved has been removed as the internal burn function already checks this
ERC2981Upgradeable._resetTokenRoyalty(tokenId);
ERC721BurnableUpgradeable.burn(tokenId);
emit Burned(tokenId);
+ ... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: `removeLiquidity` logic is not correct for generalized Well functions other than ConstantProduct. **Description:** The protocol intends to provide a generalized framework for constant-function AMM liquidity pools where various Well functions can be used. Currently, only the constant-product type Well fun... | // QuadraticWell.sol
/**
* SPDX-License-Identifier: MIT
**/
pragma solidity ^0.8.17;
import "src/interfaces/IWellFunction.sol";
import "src/libraries/LibMath.sol";
contract QuadraticWell is IWellFunction {
using LibMath for uint;
uint constant PRECISION = 1e18; //@audit-info assume 1:1 upperbound for thi... | function leave() external whenNotPaused onlyTrustedCodehash {
_updateGlobalState();
_updateVault(msg.sender, false);
VaultData storage vault = vaultData[msg.sender];
if (vault.stakedBalance > 0) {
// calling `_unstake` to update accounting accordingly
@> _unstake(v... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Read-only reentrancy. **Description:** The current implementation is vulnerable to read-only reentrancy, especially in [Wells::removeLiquidity](https://github.com/BeanstalkFarms/Wells/blob/e5441fc78f0fd4b77a898812d0fd22cb43a0af55/src/Well.sol#L440).
The implementation does not strictly follow the... | // MockCallbackRecipient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {console} from "forge-std/Test.sol";
contract MockCallbackRecipient {
fallback() external payable {
console.log("here");
(bool success, bytes memory result) = msg.sender.call(abi.encodeWithSignature("getR... | function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData) {
(uint160 sqrtPriceX96,,,,,,) = pool.slot0();
upkeepNeeded = sqrtPriceX96 <= triggerPrice;
}
function calculateUSDsToTargetPrice() private view returns (uint256 _usdc) {
int24 _spacing = pool.tick... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: Should ensure uniqueness of the tokens of Wells. **Description:** The current implementation does not enforce uniqueness in the tokens of Wells.
Anyone can call `Aquifer::boreWell()` with malicious `Well` implementation to set up a trap for victims.
Through communication with the protocol team, it is u... | function skim(address recipient) external nonReentrant returns (uint[] memory skimAmounts) {
IERC20[] memory _tokens = tokens();
uint[] memory reserves = _getReserves(_tokens.length);
skimAmounts = new uint[](_tokens.length);
for (uint i; i < _tokens.length; ++i) {
skimAmounts[i] = _tokens[i].ba... | userToPrizesWon[user][selectedPrizeId] += 1;
delete requestIdToUser[_requestId];
emit PrizeWon(user, selectedPrizeId);
return;
}
}
emit NoPrizeWon(user);
}
function _fulfillRandomness(
uint256 _randomness,
uint256 _requestId,
bytes memory
) internal over... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: `LibLastReserveBytes::storeLastReserves` has no check for reserves being too large. **Description:** After every liquidity event & swap, the `IPump::update`()` is called.
To update the pump, the `LibLastReserveBytes::storeLastReserves` function is used. This packs the reserve data into `bytes32` slots ... | src\libraries\LibLastReserveBytes.sol
21: uint8 n = uint8(reserves.length);
22: if (n == 1) {
23: assembly {
24: sstore(slot, or(or(shl(208, lastTimestamp), shl(248, n)), shl(104, shr(152, mload(add(reserves, 32))))))
25: }
26: return;
27: }
28: assembly {
29: sstore(
... | finalUserAmount = finalToken.balanceOf(address(this)) - relayerFeeAmount; | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
LOW severity: TWAP is incorrect when only 1 update has occurred. **Description:** If there has only been a single update to the pump, `GeoEmaAndCumSmaPump::readTwaReserves` will return an incorrect value.
**Impact:** Given this affects only one oracle update when the pump is still ramping up, we evaluate the severity ... | // NOTE: place in `Pump.Update.t.sol`
function testTWAReservesIsWrong() public {
increaseTime(12); // increase 12 seconds
bytes memory startCumulativeReserves = pump.readCumulativeReserves(
address(mWell)
);
uint256 lastTimestamp = block.timestamp;
increaseTime(120); // increase 120 seconds... | /// @dev Throws if called by any account other than BGT contract.
modifier onlyBGT() {
if (msg.sender != address(stakeToken)) NotBGT.selector.revertWith();
_;
}
...
function stake(address account, uint256 amount) external onlyBGT {
_stake(account, amount);
} | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: Incorrect sload in LibBytes. **Description:** The function `storeUint128` in `LibBytes` intends to pack uint128 `reserves` starting at the given slot but will overwrite the final slot if [storing an odd number of reserves](https://github.com/BeanstalkFarms/Wells/blob/e5441fc78f0fd4b77a898812d0fd22cb43a0a... | // NOTE: Add to LibBytes.t.sol
function test_exploitStoreAndRead() public {
// Write to storage slot to demonstrate overwriting existing values
// In this case, 420 will be stored in the lower 128 bits of the last slot
bytes32 slot = RESERVES_STORAGE_SLOT;
uint256 maxI = (NUM_RESERVES_MAX - 1) / 2;
... | File: helpers/FeeData.sol
18: mapping(address => bool) public feeTokenMap;
File: helpers/TransferHelper.sol
16: bool public rewardsActive; | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: The off-chain mechanism must be ensured to work in a correct order strictly. **Severity:** Medium
**Description:** The `PriorityPool` contract relies on the distribution oracle for accounting and the accounting calculation is done off-chain.
According to the communication with the protocol team, the ... | it('Cyfrin: off-chain mechanism in an incorrect order can lead to user funds being stolen', async () => {
// try deposit 1500 while the capacity is 1000
await strategy.setMaxDeposits(toEther(1000))
await sq.connect(signers[1]).deposit(toEther(1500), true)
// 500 ether is queued for accounts[1]
asse... | function _withdraw(address caller, address receiver, address owner, uint256 pUSDeAssets, uint256 shares) internal override {
if (!withdrawalsEnabled) {
revert WithdrawalsDisabled();
}
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
_bur... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: User's funds are locked temporarily in the PriorityPool contract. **Severity:** Medium
**Description:** The protocol intended to utilize the deposit queue for withdrawal to minimize the stake/unstake interaction with the staking pool.
When a user wants to withdraw, they are supposed to call the function... | function withdraw(uint256 _amount) external {//@audit-info LSD token
if (_amount == 0) revert InvalidAmount();
IERC20Upgradeable(address(stakingPool)).safeTransferFrom(msg.sender, address(this), _amount);//@audit-info get LSD token from the user
_withdraw(msg.sender, _amount);
}
function _withdraw(address ... | // maximum lock time in years
uint256 public constant MAX_LOCK_TIME = 4;
// address of SDL token
IERC677 public immutable sdlToken;
// address of SDL pool
ISDLPool public immutable sdlPool;
// whether vesting has been terminated
bool public vestingTerminated;
// amount of tokens claim... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
LOW severity: Do not use deprecated library functions. **Client:**
Fixed in this [PR](https://github.com/stakedotlink/contracts/pull/32).
**Cyfrin:** Verified. | File: PriorityPool.sol
103: token.safeApprove(_stakingPool, type(uint256).max); | * @custom:reverts IncorrectToAsset Thrown if the `toAsset` in `swapParams` does not match the target market's base token.
* @custom:reverts RedeemFailed Thrown if the QiToken redemption process fails.
* - {MintFailed}: Thrown if the minting of tokens to the target market fails.
* @custom:reverts MintFailed Thrown... | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: Non-standard ERtokens are not supported. **Severity:** Medium
**Description:** The protocol implemented a function `deposit()` to allow users to deposit.
Looking at the line L49, we can see that the protocol assumes `amount` of tokens were transferred.
But this does not hold true for some non-standard ... | DepositVault.sol
37: function deposit(uint256 amount, address tokenAddress) public payable {
38: require(amount > 0 || msg.value > 0, "Deposit amount must be greater than 0");
39: if(msg.value > 0) {
40: require(tokenAddress == address(0), "Token address must be 0x0 for ETH deposits");
4... | function finalizeWithdrawal(uint256 tokenId) external override {
if (AccessControlManager.withdrawalsPaused()) {
revert WithdrawalsPaused();
}
address owner = _ownerOf(tokenId);
- if (owner == address(0)) {
- revert WithdrawalRequestDoesNotExist();
+ if (owner == ... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
LOW severity: Unnecessary parameter amount in withdraw function. **Severity:** Informational
**Description:** The function `withdraw()` has a parameter `amount` but we don't understand the necessity of this parameter.
At line L67, the amount is required to be the same to the whole deposit amount. This means the user d... | DepositVault.sol
59: function withdraw(uint256 amount, uint256 nonce, bytes memory signature, address payable recipient) public {
60: require(nonce < deposits.length, "Invalid deposit index");
61: Deposit storage depositToWithdraw = deposits[nonce];
62: bytes32 withdrawalHash = getWithdrawal... | function test_GetUnvestedAmount_CanResurrectAfterVestingPeriodIncrease_AndMakeTotalAssetsUnderflow()
public
{
// Enable direct withdraw/redeem path (so user can exit fully)
vm.prank(operationalAdmin);
isusbdMgmt.setCooldownDuration(0);
vm.prank(operationalAdmin);
isusbdMgmt.setVestingPeriod(1);... | same_firm_diff_protocol | Solodit | LOW | 2 | |
HIGH severity: Use != 0 instead of > 0 for unsigned integer comparison. **Client:**
Fixed.
**Cyfrin:** Verified in commit [b21d23e](https://github.com/HyperGood/woosh-contracts/commit/b21d23e661b0f25f0e757dc00ee90e4464730b1b). | File: DepositVault.sol
38: require(amount > 0 || msg.value > 0, "Deposit amount must be greater than 0");
38: require(amount > 0 || msg.value > 0, "Deposit amount must be greater than 0");
39: if(msg.value > 0)
85: require(depositToWithdraw.amount > 0, "Deposit has already been withd... | function _withdraw(address caller, address receiver, address owner, uint256 pUSDeAssets, uint256 shares) internal override {
if (!withdrawalsEnabled) {
revert WithdrawalsDisabled();
}
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
_bur... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Intermediate value sent by the caller can be drained via reentrancy when `Pipeline` execution is handed off to an untrusted external contract. **Description:** Pipeline is a utility contract created by the Beanstalk Farms team that enables the execution of an arbitrary number of valid actions in a single... | function advancedPipe(AdvancedPipeCall[] calldata pipes, uint256 value)
external
payable
returns (bytes[] memory results)
{
results = IPipeline(PIPELINE).advancedPipe{value: value}(pipes);
LibEth.refundEth();
}
function refundEth()
internal
{
AppStorage storage s = LibAppStorage.diamondStor... | if (_hypervisor != address(0)) {
address _yieldManager = ISmartVaultManager(manager).yieldManager();
IERC20(_hypervisor).safeIncreaseAllowance(_yieldManager, getAssetBalance(_hypervisor));
_withdrawn = ISmartVaultYieldManager(_yieldManager).quickWithdraw(_hypervisor, _collateralToken);
IERC20(_hyperviso... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: `FarmFacet` functions are susceptible to the draining of intermediate value sent by the caller via reentrancy when execution is handed off to an untrusted external contract. **Description:** The `FarmFacet` enables multiple Beanstalk functions to be called in a single transaction using Farm calls. Any fu... | // signals to Beanstalk functions that they should not refund Eth
// at the end of the function because the function is wrapped in a Farm function
modifier withEth() {
if (msg.value > 0) s.isFarm = 2;
_;
if (msg.value > 0) {
s.isFarm = 1;
LibEth.refundEth();
}
}
function refundEth()
... | function test_deactivateSupplyGauge_usesExistingSpeed() public {
// Set existing speeds
comptroller.setRewardSpeeds(QITOKEN_1, 1000, 2000);
// Only provide borrow gauge, not supply
IDistributionGaugeVote.GaugeVote[] memory gauges = new IDistributionGaugeVote.GaugeVote[](1);
gauges[0] = IDistributio... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: `LibTokenPermit` logic is susceptible to signature replay attacks in the case of a hard fork. **Description:** Due to the implementation of [`LibTokenPermit::_buildDomainSeparator`](https://github.com/BeanstalkFarms/Beanstalk/blob/c7a20e56a0a6659c09314a877b440198eff0cd81/protocol/contracts/libraries/Toke... | function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) internal view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
- C.getChainId(),
+ block.chainid,
addr... | contract SegregatedVault is ERC4626Upgradeable, ISegregatedVault, IVaultAccessControl, BaseContract {
+ /// @custom:oz-upgrades-unsafe-allow constructor
+ constructor() {
+ _disableInitializers();
+ } | same_firm_diff_protocol | Solodit | HIGH | 2 | |
MEDIUM severity: Duplicate fees will be paid by `LibTransfer::transferFee` when transferring fee-on-transfer tokens with `EXTERNAL_INTERNAL` 'from' mode and `EXTERNAL` 'to' mode. **Description:** Beanstalk utilizes an internal virtual balance system that significantly reduces transaction fees when using tokens that are... | // LibTransfer::transferToken
if (fromMode == From.EXTERNAL && toMode == To.EXTERNAL) {
uint256 beforeBalance = token.balanceOf(recipient);
token.safeTransferFrom(sender, recipient, amount);
return token.balanceOf(recipient).sub(beforeBalance);
}
amount = receiveToken(token, amount, sender, fromMode);
sendT... | function executeStableCoinTransfer(address from, uint256 value) private {
if (bridgeChainId != 0 && address(USDCBridge) != address(0)) {
- stableCoinToken.transferFrom(from, address(this), value);
- stableCoinToken.approve(address(USDCBridge), value);
+ SafeERC20.safeTransferFrom(s... | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
MEDIUM severity: FundraiserFacet logic does not consider contract upgrades which can increase token decimals. **Description:** The fundraiser logic in `FundraiserFacet` assumes that the decimals of the token being raised will remain with the same number of decimals from when a fundraiser is created to when it is funded... | // FundraiserFacet.sol
function createFundraiser(
address payee,
address token,
uint256 amount
) external payable {
LibDiamond.enforceIsOwnerOrContract();
// The {FundraiserFacet} was initially created to support USDC, which has the
// same number of decimals as ... | // Require that the user sends a fee of "claimFee" amount
if (msg.value != claimFee) revert InvalidClaimFee();
// Require that the user sends a fee of "claimFee" amount per box
if (msg.value != claimFee * _boxIds.length) revert InvalidClaimFee(); | same_firm_diff_protocol | Solodit | MEDIUM | 2 | |
HIGH severity: Flood mechanism is susceptible to DoS attacks by a frontrunner, breaking re-peg mechanism when BEAN is above 1 USD. **Description:** A [call](https://github.com/BeanstalkFarms/Beanstalk/blob/c7a20e56a0a6659c09314a877b440198eff0cd81/protocol/contracts/beanstalk/sun/SeasonFacet/Weather.sol#L276) to the BEA... | function getDeltaB() internal view returns (int256 deltaB) {
uint256[2] memory balances = C.curveMetapool().get_balances();
uint256 d = getDFroms(balances);
deltaB = getDeltaBWithD(balances[0], d);
}
function sop() private {
- int256 newBeans = LibBeanMetaCurve.getDeltaB();
+ in... | function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable)
onlyIfTokenExists(tokenId)
returns (string memory)
{
- string[2] memory uris = _tokenURIs[tokenId];
+ string[2] storage uris = _tokenURIs[tokenId];
string memory uri = uris[_getToke... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Spender can front-run calls to modify token allowances, resulting in DoS and/or spending more than was intended. **Description:** When updating the allowance for a spender that is less than the value currently set, a well-known race condition allows the spender to spend more than the caller intended by f... | require(
currentAllowance >= subtractedValue,
"Silo: decreased allowance below zero"
); | SecuritizeSwap.sol
191: uint256 value = _params[0];
192: uint256 gasLimit = _params[1];
193: assembly {
194: let ptr := add(_data, 0x20)
195: let result := call(gasLimit, _destination, value, ptr, mload(_data), 0, 0)
196: let size := returndatasize()
197: ... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Legacy Pipeline address defined in `DepotFacet`. Currently, `DepotFacet` references an old implementation of Pipeline with the todo comment that it should be updated:
It is understood that this todo comment has been resolved in a more recent commit and should now appear as follows: | address private constant PIPELINE =
0xb1bE0000bFdcDDc92A8290202830C4Ef689dCeaa; // TODO: Update with final address.
- address private constant PIPELINE = 0xb1bE0000bFdcDDc92A8290202830C4Ef689dCeaa; // TODO: Update with final address.
+ address private constant PIPELINE = 0xb1bE0000C6B3C62749b5F0c92480146452D15423; | //ERC721TransferEnforcer.sol
bytes4 selector_ = bytes4(callData_[0:4]);
if (target_ != permittedContract_) {
revert("ERC721TransferEnforcer:unauthorized-contract-target");
} else if (selector_ != IERC721.transferFrom.selector) {
revert("ERC721TransferEnforcer:unauthorized-selector");
} else if (transferTokenId... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: Incorrect comment in `FieldFacet::_sow` NatSpec. The [comment](https://github.com/BeanstalkFarms/Beanstalk/blob/c7a20e56a0a6659c09314a877b440198eff0cd81/protocol/contracts/beanstalk/field/FieldFacet.sol#L131) explaining how `FundraiserFacet::fund` bypasses soil updates in the `FieldFacet::_sow` NatSpec i... | /**
* @dev Burn Beans, Sows at the provided `_morningTemperature`, increments the total
* number of `beanSown`.
*
* NOTE: {FundraiserFacet} also burns Beans but bypasses the soil mechanism
- * by calling {LibDibbler.sowWithMin} which bypasses updates to `s.f.beanSown`
+ * by calling {LibDibble... | In Solidity, memory slot `0x40` is reserved for the free-memory pointer, which tracks the next available memory location for dynamic allocations. Overwriting this slot corrupts the allocator state.
Immediately after this assembly block, the contract performs dynamic memory allocations via `bytes.concat(...)` and `abi.... | same_firm_diff_protocol | Solodit | HIGH | 2 | |
HIGH severity: `Sun::setSoilAbovePeg` considers intervals for `caseId` larger than intended. As is [commented](https://github.com/BeanstalkFarms/Beanstalk/blob/c7a20e56a0a6659c09314a877b440198eff0cd81/protocol/contracts/beanstalk/sun/SeasonFacet/Sun.sol#L219) in the NatSpec of [`Sun::setSoilAbovePeg`](https://github.co... | - if (caseId >= 24) {
+ if (caseId >= 28) {
newSoil = newSoil.mul(SOIL_COEFFICIENT_HIGH).div(C.PRECISION); // high podrate
- } else if (caseId < 8) {
+ } else if (4 <= caseId < 8) {
newSoil = newSoil.mul(SOIL_COEFFICIENT_LOW).div(C.PRECISION); // low podrate
} | // In `_curveBuy`:
newQuote = Y + amountInQuote;
newBase = kLocal / newQuote; // Rounds down
// After trade execution:
baseReserves = newBase;
quoteReserves = newQuote;
k = newBase * newQuote; // New k ≤ old k due to truncation
if (shouldReset) {
uint256 newBase = baseReserves; // Uses current depleted value
... | same_firm_diff_protocol | Solodit | HIGH | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.